• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- AArch64LegalizerInfo.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
10 /// AArch64.
11 /// \todo This should be generated by TableGen.
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64LegalizerInfo.h"
15 #include "AArch64Subtarget.h"
16 #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
17 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
18 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
19 #include "llvm/CodeGen/GlobalISel/Utils.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/TargetOpcodes.h"
23 #include "llvm/CodeGen/ValueTypes.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Type.h"
26 #include <initializer_list>
27 #include "llvm/Support/MathExtras.h"
28 
29 #define DEBUG_TYPE "aarch64-legalinfo"
30 
31 using namespace llvm;
32 using namespace LegalizeActions;
33 using namespace LegalizeMutations;
34 using namespace LegalityPredicates;
35 
AArch64LegalizerInfo(const AArch64Subtarget & ST)36 AArch64LegalizerInfo::AArch64LegalizerInfo(const AArch64Subtarget &ST)
37     : ST(&ST) {
38   using namespace TargetOpcode;
39   const LLT p0 = LLT::pointer(0, 64);
40   const LLT s1 = LLT::scalar(1);
41   const LLT s8 = LLT::scalar(8);
42   const LLT s16 = LLT::scalar(16);
43   const LLT s32 = LLT::scalar(32);
44   const LLT s64 = LLT::scalar(64);
45   const LLT s128 = LLT::scalar(128);
46   const LLT s256 = LLT::scalar(256);
47   const LLT s512 = LLT::scalar(512);
48   const LLT v16s8 = LLT::vector(16, 8);
49   const LLT v8s8 = LLT::vector(8, 8);
50   const LLT v4s8 = LLT::vector(4, 8);
51   const LLT v8s16 = LLT::vector(8, 16);
52   const LLT v4s16 = LLT::vector(4, 16);
53   const LLT v2s16 = LLT::vector(2, 16);
54   const LLT v2s32 = LLT::vector(2, 32);
55   const LLT v4s32 = LLT::vector(4, 32);
56   const LLT v2s64 = LLT::vector(2, 64);
57   const LLT v2p0 = LLT::vector(2, p0);
58 
59   std::initializer_list<LLT> PackedVectorAllTypeList = {/* Begin 128bit types */
60                                                         v16s8, v8s16, v4s32,
61                                                         v2s64, v2p0,
62                                                         /* End 128bit types */
63                                                         /* Begin 64bit types */
64                                                         v8s8, v4s16, v2s32};
65 
66   const TargetMachine &TM = ST.getTargetLowering()->getTargetMachine();
67 
68   // FIXME: support subtargets which have neon/fp-armv8 disabled.
69   if (!ST.hasNEON() || !ST.hasFPARMv8()) {
70     computeTables();
71     return;
72   }
73 
74   // Some instructions only support s16 if the subtarget has full 16-bit FP
75   // support.
76   const bool HasFP16 = ST.hasFullFP16();
77   const LLT &MinFPScalar = HasFP16 ? s16 : s32;
78 
79   getActionDefinitionsBuilder({G_IMPLICIT_DEF, G_FREEZE})
80       .legalFor({p0, s1, s8, s16, s32, s64})
81       .legalFor(PackedVectorAllTypeList)
82       .clampScalar(0, s1, s64)
83       .widenScalarToNextPow2(0, 8)
84       .fewerElementsIf(
85           [=](const LegalityQuery &Query) {
86             return Query.Types[0].isVector() &&
87                    (Query.Types[0].getElementType() != s64 ||
88                     Query.Types[0].getNumElements() != 2);
89           },
90           [=](const LegalityQuery &Query) {
91             LLT EltTy = Query.Types[0].getElementType();
92             if (EltTy == s64)
93               return std::make_pair(0, LLT::vector(2, 64));
94             return std::make_pair(0, EltTy);
95           });
96 
97   getActionDefinitionsBuilder(G_PHI).legalFor({p0, s16, s32, s64})
98       .legalFor(PackedVectorAllTypeList)
99       .clampScalar(0, s16, s64)
100       .widenScalarToNextPow2(0);
101 
102   getActionDefinitionsBuilder(G_BSWAP)
103       .legalFor({s32, s64, v4s32, v2s32, v2s64})
104       .clampScalar(0, s32, s64)
105       .widenScalarToNextPow2(0);
106 
107   getActionDefinitionsBuilder({G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR})
108       .legalFor({s32, s64, v2s32, v4s32, v4s16, v8s16, v16s8, v8s8})
109       .scalarizeIf(
110           [=](const LegalityQuery &Query) {
111             return Query.Opcode == G_MUL && Query.Types[0] == v2s64;
112           },
113           0)
114       .legalFor({v2s64})
115       .clampScalar(0, s32, s64)
116       .widenScalarToNextPow2(0)
117       .clampNumElements(0, v2s32, v4s32)
118       .clampNumElements(0, v2s64, v2s64)
119       .moreElementsToNextPow2(0);
120 
121   getActionDefinitionsBuilder({G_SHL, G_ASHR, G_LSHR})
122       .customIf([=](const LegalityQuery &Query) {
123         const auto &SrcTy = Query.Types[0];
124         const auto &AmtTy = Query.Types[1];
125         return !SrcTy.isVector() && SrcTy.getSizeInBits() == 32 &&
126                AmtTy.getSizeInBits() == 32;
127       })
128       .legalFor({
129           {s32, s32},
130           {s32, s64},
131           {s64, s64},
132           {v8s8, v8s8},
133           {v16s8, v16s8},
134           {v4s16, v4s16},
135           {v8s16, v8s16},
136           {v2s32, v2s32},
137           {v4s32, v4s32},
138           {v2s64, v2s64},
139       })
140       .clampScalar(1, s32, s64)
141       .clampScalar(0, s32, s64)
142       .widenScalarToNextPow2(0)
143       .clampNumElements(0, v2s32, v4s32)
144       .clampNumElements(0, v2s64, v2s64)
145       .moreElementsToNextPow2(0)
146       .minScalarSameAs(1, 0);
147 
148   getActionDefinitionsBuilder(G_PTR_ADD)
149       .legalFor({{p0, s64}, {v2p0, v2s64}})
150       .clampScalar(1, s64, s64);
151 
152   getActionDefinitionsBuilder(G_PTRMASK).legalFor({{p0, s64}});
153 
154   getActionDefinitionsBuilder({G_SDIV, G_UDIV})
155       .legalFor({s32, s64})
156       .libcallFor({s128})
157       .clampScalar(0, s32, s64)
158       .widenScalarToNextPow2(0)
159       .scalarize(0);
160 
161   getActionDefinitionsBuilder({G_SREM, G_UREM})
162       .lowerFor({s1, s8, s16, s32, s64});
163 
164   getActionDefinitionsBuilder({G_SMULO, G_UMULO}).lowerFor({{s64, s1}});
165 
166   getActionDefinitionsBuilder({G_SMULH, G_UMULH}).legalFor({s32, s64});
167 
168   getActionDefinitionsBuilder({G_UADDE, G_USUBE, G_SADDO, G_SSUBO, G_UADDO})
169       .legalFor({{s32, s1}, {s64, s1}})
170       .minScalar(0, s32);
171 
172   getActionDefinitionsBuilder({G_FADD, G_FSUB, G_FMUL, G_FDIV, G_FNEG})
173       .legalFor({s32, s64, v2s64, v4s32, v2s32})
174       .clampNumElements(0, v2s32, v4s32)
175       .clampNumElements(0, v2s64, v2s64);
176 
177   getActionDefinitionsBuilder(G_FREM).libcallFor({s32, s64});
178 
179   getActionDefinitionsBuilder({G_FCEIL, G_FABS, G_FSQRT, G_FFLOOR, G_FRINT,
180                                G_FMA, G_INTRINSIC_TRUNC, G_INTRINSIC_ROUND,
181                                G_FNEARBYINT, G_INTRINSIC_LRINT})
182       // If we don't have full FP16 support, then scalarize the elements of
183       // vectors containing fp16 types.
184       .fewerElementsIf(
185           [=, &ST](const LegalityQuery &Query) {
186             const auto &Ty = Query.Types[0];
187             return Ty.isVector() && Ty.getElementType() == s16 &&
188                    !ST.hasFullFP16();
189           },
190           [=](const LegalityQuery &Query) { return std::make_pair(0, s16); })
191       // If we don't have full FP16 support, then widen s16 to s32 if we
192       // encounter it.
193       .widenScalarIf(
194           [=, &ST](const LegalityQuery &Query) {
195             return Query.Types[0] == s16 && !ST.hasFullFP16();
196           },
197           [=](const LegalityQuery &Query) { return std::make_pair(0, s32); })
198       .legalFor({s16, s32, s64, v2s32, v4s32, v2s64, v2s16, v4s16, v8s16});
199 
200   getActionDefinitionsBuilder(
201       {G_FCOS, G_FSIN, G_FLOG10, G_FLOG, G_FLOG2, G_FEXP, G_FEXP2, G_FPOW})
202       // We need a call for these, so we always need to scalarize.
203       .scalarize(0)
204       // Regardless of FP16 support, widen 16-bit elements to 32-bits.
205       .minScalar(0, s32)
206       .libcallFor({s32, s64, v2s32, v4s32, v2s64});
207 
208   getActionDefinitionsBuilder(G_INSERT)
209       .unsupportedIf([=](const LegalityQuery &Query) {
210         return Query.Types[0].getSizeInBits() <= Query.Types[1].getSizeInBits();
211       })
212       .legalIf([=](const LegalityQuery &Query) {
213         const LLT &Ty0 = Query.Types[0];
214         const LLT &Ty1 = Query.Types[1];
215         if (Ty0 != s32 && Ty0 != s64 && Ty0 != p0)
216           return false;
217         return isPowerOf2_32(Ty1.getSizeInBits()) &&
218                (Ty1.getSizeInBits() == 1 || Ty1.getSizeInBits() >= 8);
219       })
220       .clampScalar(0, s32, s64)
221       .widenScalarToNextPow2(0)
222       .maxScalarIf(typeInSet(0, {s32}), 1, s16)
223       .maxScalarIf(typeInSet(0, {s64}), 1, s32)
224       .widenScalarToNextPow2(1);
225 
226   getActionDefinitionsBuilder(G_EXTRACT)
227       .unsupportedIf([=](const LegalityQuery &Query) {
228         return Query.Types[0].getSizeInBits() >= Query.Types[1].getSizeInBits();
229       })
230       .legalIf([=](const LegalityQuery &Query) {
231         const LLT &Ty0 = Query.Types[0];
232         const LLT &Ty1 = Query.Types[1];
233         if (Ty1 != s32 && Ty1 != s64 && Ty1 != s128)
234           return false;
235         if (Ty1 == p0)
236           return true;
237         return isPowerOf2_32(Ty0.getSizeInBits()) &&
238                (Ty0.getSizeInBits() == 1 || Ty0.getSizeInBits() >= 8);
239       })
240       .clampScalar(1, s32, s128)
241       .widenScalarToNextPow2(1)
242       .maxScalarIf(typeInSet(1, {s32}), 0, s16)
243       .maxScalarIf(typeInSet(1, {s64}), 0, s32)
244       .widenScalarToNextPow2(0);
245 
246   getActionDefinitionsBuilder({G_SEXTLOAD, G_ZEXTLOAD})
247       .legalForTypesWithMemDesc({{s32, p0, 8, 8},
248                                  {s32, p0, 16, 8},
249                                  {s32, p0, 32, 8},
250                                  {s64, p0, 8, 2},
251                                  {s64, p0, 16, 2},
252                                  {s64, p0, 32, 4},
253                                  {s64, p0, 64, 8},
254                                  {p0, p0, 64, 8},
255                                  {v2s32, p0, 64, 8}})
256       .clampScalar(0, s32, s64)
257       .widenScalarToNextPow2(0)
258       // TODO: We could support sum-of-pow2's but the lowering code doesn't know
259       //       how to do that yet.
260       .unsupportedIfMemSizeNotPow2()
261       // Lower anything left over into G_*EXT and G_LOAD
262       .lower();
263 
264   auto IsPtrVecPred = [=](const LegalityQuery &Query) {
265     const LLT &ValTy = Query.Types[0];
266     if (!ValTy.isVector())
267       return false;
268     const LLT EltTy = ValTy.getElementType();
269     return EltTy.isPointer() && EltTy.getAddressSpace() == 0;
270   };
271 
272   getActionDefinitionsBuilder(G_LOAD)
273       .legalForTypesWithMemDesc({{s8, p0, 8, 8},
274                                  {s16, p0, 16, 8},
275                                  {s32, p0, 32, 8},
276                                  {s64, p0, 64, 8},
277                                  {p0, p0, 64, 8},
278                                  {s128, p0, 128, 8},
279                                  {v8s8, p0, 64, 8},
280                                  {v16s8, p0, 128, 8},
281                                  {v4s16, p0, 64, 8},
282                                  {v8s16, p0, 128, 8},
283                                  {v2s32, p0, 64, 8},
284                                  {v4s32, p0, 128, 8},
285                                  {v2s64, p0, 128, 8}})
286       // These extends are also legal
287       .legalForTypesWithMemDesc({{s32, p0, 8, 8}, {s32, p0, 16, 8}})
288       .clampScalar(0, s8, s64)
289       .lowerIfMemSizeNotPow2()
290       // Lower any any-extending loads left into G_ANYEXT and G_LOAD
291       .lowerIf([=](const LegalityQuery &Query) {
292         return Query.Types[0].getSizeInBits() != Query.MMODescrs[0].SizeInBits;
293       })
294       .widenScalarToNextPow2(0)
295       .clampMaxNumElements(0, s32, 2)
296       .clampMaxNumElements(0, s64, 1)
297       .customIf(IsPtrVecPred);
298 
299   getActionDefinitionsBuilder(G_STORE)
300       .legalForTypesWithMemDesc({{s8, p0, 8, 8},
301                                  {s16, p0, 16, 8},
302                                  {s32, p0, 8, 8},
303                                  {s32, p0, 16, 8},
304                                  {s32, p0, 32, 8},
305                                  {s64, p0, 64, 8},
306                                  {p0, p0, 64, 8},
307                                  {s128, p0, 128, 8},
308                                  {v16s8, p0, 128, 8},
309                                  {v8s8, p0, 64, 8},
310                                  {v4s16, p0, 64, 8},
311                                  {v8s16, p0, 128, 8},
312                                  {v2s32, p0, 64, 8},
313                                  {v4s32, p0, 128, 8},
314                                  {v2s64, p0, 128, 8}})
315       .clampScalar(0, s8, s64)
316       .lowerIfMemSizeNotPow2()
317       .lowerIf([=](const LegalityQuery &Query) {
318         return Query.Types[0].isScalar() &&
319                Query.Types[0].getSizeInBits() != Query.MMODescrs[0].SizeInBits;
320       })
321       .clampMaxNumElements(0, s32, 2)
322       .clampMaxNumElements(0, s64, 1)
323       .customIf(IsPtrVecPred);
324 
325   // Constants
326   getActionDefinitionsBuilder(G_CONSTANT)
327       .legalFor({p0, s8, s16, s32, s64})
328       .clampScalar(0, s8, s64)
329       .widenScalarToNextPow2(0);
330   getActionDefinitionsBuilder(G_FCONSTANT)
331       .legalIf([=](const LegalityQuery &Query) {
332         const auto &Ty = Query.Types[0];
333         if (HasFP16 && Ty == s16)
334           return true;
335         return Ty == s32 || Ty == s64;
336       })
337       .clampScalar(0, MinFPScalar, s64);
338 
339   getActionDefinitionsBuilder({G_ICMP, G_FCMP})
340       .legalFor({{s32, s32},
341                  {s32, s64},
342                  {s32, p0},
343                  {v4s32, v4s32},
344                  {v2s32, v2s32},
345                  {v2s64, v2s64},
346                  {v2s64, v2p0},
347                  {v4s16, v4s16},
348                  {v8s16, v8s16},
349                  {v8s8, v8s8},
350                  {v16s8, v16s8}})
351       .clampScalar(1, s32, s64)
352       .clampScalar(0, s32, s32)
353       .minScalarEltSameAsIf(
354           [=](const LegalityQuery &Query) {
355             const LLT &Ty = Query.Types[0];
356             const LLT &SrcTy = Query.Types[1];
357             return Ty.isVector() && !SrcTy.getElementType().isPointer() &&
358                    Ty.getElementType() != SrcTy.getElementType();
359           },
360           0, 1)
361       .minScalarOrEltIf(
362           [=](const LegalityQuery &Query) { return Query.Types[1] == v2s16; },
363           1, s32)
364       .minScalarOrEltIf(
365           [=](const LegalityQuery &Query) { return Query.Types[1] == v2p0; }, 0,
366           s64)
367       .widenScalarOrEltToNextPow2(1)
368       .clampNumElements(0, v2s32, v4s32);
369 
370   // Extensions
371   auto ExtLegalFunc = [=](const LegalityQuery &Query) {
372     unsigned DstSize = Query.Types[0].getSizeInBits();
373 
374     if (DstSize == 128 && !Query.Types[0].isVector())
375       return false; // Extending to a scalar s128 needs narrowing.
376 
377     // Make sure that we have something that will fit in a register, and
378     // make sure it's a power of 2.
379     if (DstSize < 8 || DstSize > 128 || !isPowerOf2_32(DstSize))
380       return false;
381 
382     const LLT &SrcTy = Query.Types[1];
383 
384     // Special case for s1.
385     if (SrcTy == s1)
386       return true;
387 
388     // Make sure we fit in a register otherwise. Don't bother checking that
389     // the source type is below 128 bits. We shouldn't be allowing anything
390     // through which is wider than the destination in the first place.
391     unsigned SrcSize = SrcTy.getSizeInBits();
392     if (SrcSize < 8 || !isPowerOf2_32(SrcSize))
393       return false;
394 
395     return true;
396   };
397   getActionDefinitionsBuilder({G_ZEXT, G_SEXT, G_ANYEXT})
398       .legalIf(ExtLegalFunc)
399       .clampScalar(0, s64, s64); // Just for s128, others are handled above.
400 
401   getActionDefinitionsBuilder(G_TRUNC)
402       .minScalarOrEltIf(
403           [=](const LegalityQuery &Query) { return Query.Types[0].isVector(); },
404           0, s8)
405       .customIf([=](const LegalityQuery &Query) {
406         LLT DstTy = Query.Types[0];
407         LLT SrcTy = Query.Types[1];
408         return DstTy == v8s8 && SrcTy.getSizeInBits() > 128;
409       })
410       .alwaysLegal();
411 
412   getActionDefinitionsBuilder(G_SEXT_INREG).legalFor({s32, s64}).lower();
413 
414   // FP conversions
415   getActionDefinitionsBuilder(G_FPTRUNC)
416       .legalFor(
417           {{s16, s32}, {s16, s64}, {s32, s64}, {v4s16, v4s32}, {v2s32, v2s64}})
418       .clampMaxNumElements(0, s32, 2);
419   getActionDefinitionsBuilder(G_FPEXT)
420       .legalFor(
421           {{s32, s16}, {s64, s16}, {s64, s32}, {v4s32, v4s16}, {v2s64, v2s32}})
422       .clampMaxNumElements(0, s64, 2);
423 
424   // Conversions
425   getActionDefinitionsBuilder({G_FPTOSI, G_FPTOUI})
426       .legalForCartesianProduct({s32, s64, v2s64, v4s32, v2s32})
427       .clampScalar(0, s32, s64)
428       .widenScalarToNextPow2(0)
429       .clampScalar(1, s32, s64)
430       .widenScalarToNextPow2(1);
431 
432   getActionDefinitionsBuilder({G_SITOFP, G_UITOFP})
433       .legalForCartesianProduct({s32, s64, v2s64, v4s32, v2s32})
434       .clampScalar(1, s32, s64)
435       .minScalarSameAs(1, 0)
436       .clampScalar(0, s32, s64)
437       .widenScalarToNextPow2(0);
438 
439   // Control-flow
440   getActionDefinitionsBuilder(G_BRCOND).legalFor({s1, s8, s16, s32});
441   getActionDefinitionsBuilder(G_BRINDIRECT).legalFor({p0});
442 
443   getActionDefinitionsBuilder(G_SELECT)
444       .legalFor({{s32, s1}, {s64, s1}, {p0, s1}})
445       .clampScalar(0, s32, s64)
446       .widenScalarToNextPow2(0)
447       .minScalarEltSameAsIf(all(isVector(0), isVector(1)), 1, 0)
448       .lowerIf(isVector(0));
449 
450   // Pointer-handling
451   getActionDefinitionsBuilder(G_FRAME_INDEX).legalFor({p0});
452 
453   if (TM.getCodeModel() == CodeModel::Small)
454     getActionDefinitionsBuilder(G_GLOBAL_VALUE).custom();
455   else
456     getActionDefinitionsBuilder(G_GLOBAL_VALUE).legalFor({p0});
457 
458   getActionDefinitionsBuilder(G_PTRTOINT)
459       .legalForCartesianProduct({s1, s8, s16, s32, s64}, {p0})
460       .maxScalar(0, s64)
461       .widenScalarToNextPow2(0, /*Min*/ 8);
462 
463   getActionDefinitionsBuilder(G_INTTOPTR)
464       .unsupportedIf([&](const LegalityQuery &Query) {
465         return Query.Types[0].getSizeInBits() != Query.Types[1].getSizeInBits();
466       })
467       .legalFor({{p0, s64}});
468 
469   // Casts for 32 and 64-bit width type are just copies.
470   // Same for 128-bit width type, except they are on the FPR bank.
471   getActionDefinitionsBuilder(G_BITCAST)
472       // FIXME: This is wrong since G_BITCAST is not allowed to change the
473       // number of bits but it's what the previous code described and fixing
474       // it breaks tests.
475       .legalForCartesianProduct({s1, s8, s16, s32, s64, s128, v16s8, v8s8, v4s8,
476                                  v8s16, v4s16, v2s16, v4s32, v2s32, v2s64,
477                                  v2p0});
478 
479   getActionDefinitionsBuilder(G_VASTART).legalFor({p0});
480 
481   // va_list must be a pointer, but most sized types are pretty easy to handle
482   // as the destination.
483   getActionDefinitionsBuilder(G_VAARG)
484       .customForCartesianProduct({s8, s16, s32, s64, p0}, {p0})
485       .clampScalar(0, s8, s64)
486       .widenScalarToNextPow2(0, /*Min*/ 8);
487 
488   if (ST.hasLSE()) {
489     getActionDefinitionsBuilder(G_ATOMIC_CMPXCHG_WITH_SUCCESS)
490         .lowerIf(all(
491             typeInSet(0, {s8, s16, s32, s64}), typeIs(1, s1), typeIs(2, p0),
492             atomicOrderingAtLeastOrStrongerThan(0, AtomicOrdering::Monotonic)));
493 
494     getActionDefinitionsBuilder(
495         {G_ATOMICRMW_XCHG, G_ATOMICRMW_ADD, G_ATOMICRMW_SUB, G_ATOMICRMW_AND,
496          G_ATOMICRMW_OR, G_ATOMICRMW_XOR, G_ATOMICRMW_MIN, G_ATOMICRMW_MAX,
497          G_ATOMICRMW_UMIN, G_ATOMICRMW_UMAX, G_ATOMIC_CMPXCHG})
498         .legalIf(all(
499             typeInSet(0, {s8, s16, s32, s64}), typeIs(1, p0),
500             atomicOrderingAtLeastOrStrongerThan(0, AtomicOrdering::Monotonic)));
501   }
502 
503   getActionDefinitionsBuilder(G_BLOCK_ADDR).legalFor({p0});
504 
505   // Merge/Unmerge
506   for (unsigned Op : {G_MERGE_VALUES, G_UNMERGE_VALUES}) {
507     unsigned BigTyIdx = Op == G_MERGE_VALUES ? 0 : 1;
508     unsigned LitTyIdx = Op == G_MERGE_VALUES ? 1 : 0;
509 
510     auto notValidElt = [](const LegalityQuery &Query, unsigned TypeIdx) {
511       const LLT &Ty = Query.Types[TypeIdx];
512       if (Ty.isVector()) {
513         const LLT &EltTy = Ty.getElementType();
514         if (EltTy.getSizeInBits() < 8 || EltTy.getSizeInBits() > 64)
515           return true;
516         if (!isPowerOf2_32(EltTy.getSizeInBits()))
517           return true;
518       }
519       return false;
520     };
521 
522     // FIXME: This rule is horrible, but specifies the same as what we had
523     // before with the particularly strange definitions removed (e.g.
524     // s8 = G_MERGE_VALUES s32, s32).
525     // Part of the complexity comes from these ops being extremely flexible. For
526     // example, you can build/decompose vectors with it, concatenate vectors,
527     // etc. and in addition to this you can also bitcast with it at the same
528     // time. We've been considering breaking it up into multiple ops to make it
529     // more manageable throughout the backend.
530     getActionDefinitionsBuilder(Op)
531         // Break up vectors with weird elements into scalars
532         .fewerElementsIf(
533             [=](const LegalityQuery &Query) { return notValidElt(Query, 0); },
534             scalarize(0))
535         .fewerElementsIf(
536             [=](const LegalityQuery &Query) { return notValidElt(Query, 1); },
537             scalarize(1))
538         // Clamp the big scalar to s8-s512 and make it either a power of 2, 192,
539         // or 384.
540         .clampScalar(BigTyIdx, s8, s512)
541         .widenScalarIf(
542             [=](const LegalityQuery &Query) {
543               const LLT &Ty = Query.Types[BigTyIdx];
544               return !isPowerOf2_32(Ty.getSizeInBits()) &&
545                      Ty.getSizeInBits() % 64 != 0;
546             },
547             [=](const LegalityQuery &Query) {
548               // Pick the next power of 2, or a multiple of 64 over 128.
549               // Whichever is smaller.
550               const LLT &Ty = Query.Types[BigTyIdx];
551               unsigned NewSizeInBits = 1
552                                        << Log2_32_Ceil(Ty.getSizeInBits() + 1);
553               if (NewSizeInBits >= 256) {
554                 unsigned RoundedTo = alignTo<64>(Ty.getSizeInBits() + 1);
555                 if (RoundedTo < NewSizeInBits)
556                   NewSizeInBits = RoundedTo;
557               }
558               return std::make_pair(BigTyIdx, LLT::scalar(NewSizeInBits));
559             })
560         // Clamp the little scalar to s8-s256 and make it a power of 2. It's not
561         // worth considering the multiples of 64 since 2*192 and 2*384 are not
562         // valid.
563         .clampScalar(LitTyIdx, s8, s256)
564         .widenScalarToNextPow2(LitTyIdx, /*Min*/ 8)
565         // So at this point, we have s8, s16, s32, s64, s128, s192, s256, s384,
566         // s512, <X x s8>, <X x s16>, <X x s32>, or <X x s64>.
567         // At this point it's simple enough to accept the legal types.
568         .legalIf([=](const LegalityQuery &Query) {
569           const LLT &BigTy = Query.Types[BigTyIdx];
570           const LLT &LitTy = Query.Types[LitTyIdx];
571           if (BigTy.isVector() && BigTy.getSizeInBits() < 32)
572             return false;
573           if (LitTy.isVector() && LitTy.getSizeInBits() < 32)
574             return false;
575           return BigTy.getSizeInBits() % LitTy.getSizeInBits() == 0;
576         })
577         // Any vectors left are the wrong size. Scalarize them.
578         .scalarize(0)
579         .scalarize(1);
580   }
581 
582   getActionDefinitionsBuilder(G_EXTRACT_VECTOR_ELT)
583       .unsupportedIf([=](const LegalityQuery &Query) {
584         const LLT &EltTy = Query.Types[1].getElementType();
585         return Query.Types[0] != EltTy;
586       })
587       .minScalar(2, s64)
588       .legalIf([=](const LegalityQuery &Query) {
589         const LLT &VecTy = Query.Types[1];
590         return VecTy == v2s16 || VecTy == v4s16 || VecTy == v8s16 ||
591                VecTy == v4s32 || VecTy == v2s64 || VecTy == v2s32 ||
592                VecTy == v16s8 || VecTy == v2s32 || VecTy == v2p0;
593       })
594       .minScalarOrEltIf(
595           [=](const LegalityQuery &Query) {
596             // We want to promote to <M x s1> to <M x s64> if that wouldn't
597             // cause the total vec size to be > 128b.
598             return Query.Types[1].getNumElements() <= 2;
599           },
600           0, s64)
601       .minScalarOrEltIf(
602           [=](const LegalityQuery &Query) {
603             return Query.Types[1].getNumElements() <= 4;
604           },
605           0, s32)
606       .minScalarOrEltIf(
607           [=](const LegalityQuery &Query) {
608             return Query.Types[1].getNumElements() <= 8;
609           },
610           0, s16)
611       .minScalarOrEltIf(
612           [=](const LegalityQuery &Query) {
613             return Query.Types[1].getNumElements() <= 16;
614           },
615           0, s8)
616       .minScalarOrElt(0, s8); // Worst case, we need at least s8.
617 
618   getActionDefinitionsBuilder(G_INSERT_VECTOR_ELT)
619       .legalIf(typeInSet(0, {v8s16, v2s32, v4s32, v2s64}));
620 
621   getActionDefinitionsBuilder(G_BUILD_VECTOR)
622       .legalFor({{v8s8, s8},
623                  {v16s8, s8},
624                  {v4s16, s16},
625                  {v8s16, s16},
626                  {v2s32, s32},
627                  {v4s32, s32},
628                  {v2p0, p0},
629                  {v2s64, s64}})
630       .clampNumElements(0, v4s32, v4s32)
631       .clampNumElements(0, v2s64, v2s64)
632 
633       // Deal with larger scalar types, which will be implicitly truncated.
634       .legalIf([=](const LegalityQuery &Query) {
635         return Query.Types[0].getScalarSizeInBits() <
636                Query.Types[1].getSizeInBits();
637       })
638       .minScalarSameAs(1, 0);
639 
640   getActionDefinitionsBuilder(G_CTLZ)
641       .legalForCartesianProduct(
642           {s32, s64, v8s8, v16s8, v4s16, v8s16, v2s32, v4s32})
643       .scalarize(1);
644 
645   getActionDefinitionsBuilder(G_SHUFFLE_VECTOR)
646       .legalIf([=](const LegalityQuery &Query) {
647         const LLT &DstTy = Query.Types[0];
648         const LLT &SrcTy = Query.Types[1];
649         // For now just support the TBL2 variant which needs the source vectors
650         // to be the same size as the dest.
651         if (DstTy != SrcTy)
652           return false;
653         for (auto &Ty : {v2s32, v4s32, v2s64, v2p0, v16s8, v8s16}) {
654           if (DstTy == Ty)
655             return true;
656         }
657         return false;
658       })
659       // G_SHUFFLE_VECTOR can have scalar sources (from 1 x s vectors), we
660       // just want those lowered into G_BUILD_VECTOR
661       .lowerIf([=](const LegalityQuery &Query) {
662         return !Query.Types[1].isVector();
663       })
664       .clampNumElements(0, v4s32, v4s32)
665       .clampNumElements(0, v2s64, v2s64);
666 
667   getActionDefinitionsBuilder(G_CONCAT_VECTORS)
668       .legalFor({{v4s32, v2s32}, {v8s16, v4s16}});
669 
670   getActionDefinitionsBuilder(G_JUMP_TABLE).legalFor({{p0}, {s64}});
671 
672   getActionDefinitionsBuilder(G_BRJT).legalIf([=](const LegalityQuery &Query) {
673     return Query.Types[0] == p0 && Query.Types[1] == s64;
674   });
675 
676   getActionDefinitionsBuilder(G_DYN_STACKALLOC).lower();
677 
678   getActionDefinitionsBuilder({G_MEMCPY, G_MEMMOVE, G_MEMSET}).libcall();
679 
680   getActionDefinitionsBuilder(G_ABS).lowerIf(
681       [=](const LegalityQuery &Query) { return Query.Types[0].isScalar(); });
682 
683   getActionDefinitionsBuilder(G_VECREDUCE_FADD)
684       // We only have FADDP to do reduction-like operations. Lower the rest.
685       .legalFor({{s32, v2s32}, {s64, v2s64}})
686       .lower();
687 
688   getActionDefinitionsBuilder(G_VECREDUCE_ADD)
689       .legalFor({{s8, v16s8}, {s16, v8s16}, {s32, v4s32}, {s64, v2s64}})
690       .lower();
691 
692   computeTables();
693   verify(*ST.getInstrInfo());
694 }
695 
legalizeCustom(LegalizerHelper & Helper,MachineInstr & MI) const696 bool AArch64LegalizerInfo::legalizeCustom(LegalizerHelper &Helper,
697                                           MachineInstr &MI) const {
698   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
699   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
700   GISelChangeObserver &Observer = Helper.Observer;
701   switch (MI.getOpcode()) {
702   default:
703     // No idea what to do.
704     return false;
705   case TargetOpcode::G_VAARG:
706     return legalizeVaArg(MI, MRI, MIRBuilder);
707   case TargetOpcode::G_LOAD:
708   case TargetOpcode::G_STORE:
709     return legalizeLoadStore(MI, MRI, MIRBuilder, Observer);
710   case TargetOpcode::G_SHL:
711   case TargetOpcode::G_ASHR:
712   case TargetOpcode::G_LSHR:
713     return legalizeShlAshrLshr(MI, MRI, MIRBuilder, Observer);
714   case TargetOpcode::G_GLOBAL_VALUE:
715     return legalizeSmallCMGlobalValue(MI, MRI, MIRBuilder, Observer);
716   case TargetOpcode::G_TRUNC:
717     return legalizeVectorTrunc(MI, Helper);
718   }
719 
720   llvm_unreachable("expected switch to return");
721 }
722 
extractParts(Register Reg,MachineRegisterInfo & MRI,MachineIRBuilder & MIRBuilder,LLT Ty,int NumParts,SmallVectorImpl<Register> & VRegs)723 static void extractParts(Register Reg, MachineRegisterInfo &MRI,
724                          MachineIRBuilder &MIRBuilder, LLT Ty, int NumParts,
725                          SmallVectorImpl<Register> &VRegs) {
726   for (int I = 0; I < NumParts; ++I)
727     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
728   MIRBuilder.buildUnmerge(VRegs, Reg);
729 }
730 
legalizeVectorTrunc(MachineInstr & MI,LegalizerHelper & Helper) const731 bool AArch64LegalizerInfo::legalizeVectorTrunc(
732     MachineInstr &MI, LegalizerHelper &Helper) const {
733   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
734   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
735   // Similar to how operand splitting is done in SelectiondDAG, we can handle
736   // %res(v8s8) = G_TRUNC %in(v8s32) by generating:
737   //   %inlo(<4x s32>), %inhi(<4 x s32>) = G_UNMERGE %in(<8 x s32>)
738   //   %lo16(<4 x s16>) = G_TRUNC %inlo
739   //   %hi16(<4 x s16>) = G_TRUNC %inhi
740   //   %in16(<8 x s16>) = G_CONCAT_VECTORS %lo16, %hi16
741   //   %res(<8 x s8>) = G_TRUNC %in16
742 
743   Register DstReg = MI.getOperand(0).getReg();
744   Register SrcReg = MI.getOperand(1).getReg();
745   LLT DstTy = MRI.getType(DstReg);
746   LLT SrcTy = MRI.getType(SrcReg);
747   assert(isPowerOf2_32(DstTy.getSizeInBits()) &&
748          isPowerOf2_32(SrcTy.getSizeInBits()));
749 
750   // Split input type.
751   LLT SplitSrcTy = SrcTy.changeNumElements(SrcTy.getNumElements() / 2);
752   // First, split the source into two smaller vectors.
753   SmallVector<Register, 2> SplitSrcs;
754   extractParts(SrcReg, MRI, MIRBuilder, SplitSrcTy, 2, SplitSrcs);
755 
756   // Truncate the splits into intermediate narrower elements.
757   LLT InterTy = SplitSrcTy.changeElementSize(DstTy.getScalarSizeInBits() * 2);
758   for (unsigned I = 0; I < SplitSrcs.size(); ++I)
759     SplitSrcs[I] = MIRBuilder.buildTrunc(InterTy, SplitSrcs[I]).getReg(0);
760 
761   auto Concat = MIRBuilder.buildConcatVectors(
762       DstTy.changeElementSize(DstTy.getScalarSizeInBits() * 2), SplitSrcs);
763 
764   Helper.Observer.changingInstr(MI);
765   MI.getOperand(1).setReg(Concat.getReg(0));
766   Helper.Observer.changedInstr(MI);
767   return true;
768 }
769 
legalizeSmallCMGlobalValue(MachineInstr & MI,MachineRegisterInfo & MRI,MachineIRBuilder & MIRBuilder,GISelChangeObserver & Observer) const770 bool AArch64LegalizerInfo::legalizeSmallCMGlobalValue(
771     MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder,
772     GISelChangeObserver &Observer) const {
773   assert(MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE);
774   // We do this custom legalization to convert G_GLOBAL_VALUE into target ADRP +
775   // G_ADD_LOW instructions.
776   // By splitting this here, we can optimize accesses in the small code model by
777   // folding in the G_ADD_LOW into the load/store offset.
778   auto GV = MI.getOperand(1).getGlobal();
779   if (GV->isThreadLocal())
780     return true; // Don't want to modify TLS vars.
781 
782   auto &TM = ST->getTargetLowering()->getTargetMachine();
783   unsigned OpFlags = ST->ClassifyGlobalReference(GV, TM);
784 
785   if (OpFlags & AArch64II::MO_GOT)
786     return true;
787 
788   Register DstReg = MI.getOperand(0).getReg();
789   auto ADRP = MIRBuilder.buildInstr(AArch64::ADRP, {LLT::pointer(0, 64)}, {})
790                   .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
791   // Set the regclass on the dest reg too.
792   MRI.setRegClass(ADRP.getReg(0), &AArch64::GPR64RegClass);
793 
794   // MO_TAGGED on the page indicates a tagged address. Set the tag now. We do so
795   // by creating a MOVK that sets bits 48-63 of the register to (global address
796   // + 0x100000000 - PC) >> 48. The additional 0x100000000 offset here is to
797   // prevent an incorrect tag being generated during relocation when the the
798   // global appears before the code section. Without the offset, a global at
799   // `0x0f00'0000'0000'1000` (i.e. at `0x1000` with tag `0xf`) that's referenced
800   // by code at `0x2000` would result in `0x0f00'0000'0000'1000 - 0x2000 =
801   // 0x0eff'ffff'ffff'f000`, meaning the tag would be incorrectly set to `0xe`
802   // instead of `0xf`.
803   // This assumes that we're in the small code model so we can assume a binary
804   // size of <= 4GB, which makes the untagged PC relative offset positive. The
805   // binary must also be loaded into address range [0, 2^48). Both of these
806   // properties need to be ensured at runtime when using tagged addresses.
807   if (OpFlags & AArch64II::MO_TAGGED) {
808     ADRP = MIRBuilder.buildInstr(AArch64::MOVKXi, {LLT::pointer(0, 64)}, {ADRP})
809                .addGlobalAddress(GV, 0x100000000,
810                                  AArch64II::MO_PREL | AArch64II::MO_G3)
811                .addImm(48);
812     MRI.setRegClass(ADRP.getReg(0), &AArch64::GPR64RegClass);
813   }
814 
815   MIRBuilder.buildInstr(AArch64::G_ADD_LOW, {DstReg}, {ADRP})
816       .addGlobalAddress(GV, 0,
817                         OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
818   MI.eraseFromParent();
819   return true;
820 }
821 
legalizeIntrinsic(LegalizerHelper & Helper,MachineInstr & MI) const822 bool AArch64LegalizerInfo::legalizeIntrinsic(LegalizerHelper &Helper,
823                                              MachineInstr &MI) const {
824   return true;
825 }
826 
legalizeShlAshrLshr(MachineInstr & MI,MachineRegisterInfo & MRI,MachineIRBuilder & MIRBuilder,GISelChangeObserver & Observer) const827 bool AArch64LegalizerInfo::legalizeShlAshrLshr(
828     MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder,
829     GISelChangeObserver &Observer) const {
830   assert(MI.getOpcode() == TargetOpcode::G_ASHR ||
831          MI.getOpcode() == TargetOpcode::G_LSHR ||
832          MI.getOpcode() == TargetOpcode::G_SHL);
833   // If the shift amount is a G_CONSTANT, promote it to a 64 bit type so the
834   // imported patterns can select it later. Either way, it will be legal.
835   Register AmtReg = MI.getOperand(2).getReg();
836   auto VRegAndVal = getConstantVRegValWithLookThrough(AmtReg, MRI);
837   if (!VRegAndVal)
838     return true;
839   // Check the shift amount is in range for an immediate form.
840   int64_t Amount = VRegAndVal->Value;
841   if (Amount > 31)
842     return true; // This will have to remain a register variant.
843   auto ExtCst = MIRBuilder.buildConstant(LLT::scalar(64), Amount);
844   MI.getOperand(2).setReg(ExtCst.getReg(0));
845   return true;
846 }
847 
legalizeLoadStore(MachineInstr & MI,MachineRegisterInfo & MRI,MachineIRBuilder & MIRBuilder,GISelChangeObserver & Observer) const848 bool AArch64LegalizerInfo::legalizeLoadStore(
849     MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder,
850     GISelChangeObserver &Observer) const {
851   assert(MI.getOpcode() == TargetOpcode::G_STORE ||
852          MI.getOpcode() == TargetOpcode::G_LOAD);
853   // Here we just try to handle vector loads/stores where our value type might
854   // have pointer elements, which the SelectionDAG importer can't handle. To
855   // allow the existing patterns for s64 to fire for p0, we just try to bitcast
856   // the value to use s64 types.
857 
858   // Custom legalization requires the instruction, if not deleted, must be fully
859   // legalized. In order to allow further legalization of the inst, we create
860   // a new instruction and erase the existing one.
861 
862   Register ValReg = MI.getOperand(0).getReg();
863   const LLT ValTy = MRI.getType(ValReg);
864 
865   if (!ValTy.isVector() || !ValTy.getElementType().isPointer() ||
866       ValTy.getElementType().getAddressSpace() != 0) {
867     LLVM_DEBUG(dbgs() << "Tried to do custom legalization on wrong load/store");
868     return false;
869   }
870 
871   unsigned PtrSize = ValTy.getElementType().getSizeInBits();
872   const LLT NewTy = LLT::vector(ValTy.getNumElements(), PtrSize);
873   auto &MMO = **MI.memoperands_begin();
874   if (MI.getOpcode() == TargetOpcode::G_STORE) {
875     auto Bitcast = MIRBuilder.buildBitcast(NewTy, ValReg);
876     MIRBuilder.buildStore(Bitcast.getReg(0), MI.getOperand(1), MMO);
877   } else {
878     auto NewLoad = MIRBuilder.buildLoad(NewTy, MI.getOperand(1), MMO);
879     MIRBuilder.buildBitcast(ValReg, NewLoad);
880   }
881   MI.eraseFromParent();
882   return true;
883 }
884 
legalizeVaArg(MachineInstr & MI,MachineRegisterInfo & MRI,MachineIRBuilder & MIRBuilder) const885 bool AArch64LegalizerInfo::legalizeVaArg(MachineInstr &MI,
886                                          MachineRegisterInfo &MRI,
887                                          MachineIRBuilder &MIRBuilder) const {
888   MachineFunction &MF = MIRBuilder.getMF();
889   Align Alignment(MI.getOperand(2).getImm());
890   Register Dst = MI.getOperand(0).getReg();
891   Register ListPtr = MI.getOperand(1).getReg();
892 
893   LLT PtrTy = MRI.getType(ListPtr);
894   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
895 
896   const unsigned PtrSize = PtrTy.getSizeInBits() / 8;
897   const Align PtrAlign = Align(PtrSize);
898   auto List = MIRBuilder.buildLoad(
899       PtrTy, ListPtr,
900       *MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOLoad,
901                                PtrSize, PtrAlign));
902 
903   MachineInstrBuilder DstPtr;
904   if (Alignment > PtrAlign) {
905     // Realign the list to the actual required alignment.
906     auto AlignMinus1 =
907         MIRBuilder.buildConstant(IntPtrTy, Alignment.value() - 1);
908     auto ListTmp = MIRBuilder.buildPtrAdd(PtrTy, List, AlignMinus1.getReg(0));
909     DstPtr = MIRBuilder.buildMaskLowPtrBits(PtrTy, ListTmp, Log2(Alignment));
910   } else
911     DstPtr = List;
912 
913   uint64_t ValSize = MRI.getType(Dst).getSizeInBits() / 8;
914   MIRBuilder.buildLoad(
915       Dst, DstPtr,
916       *MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOLoad,
917                                ValSize, std::max(Alignment, PtrAlign)));
918 
919   auto Size = MIRBuilder.buildConstant(IntPtrTy, alignTo(ValSize, PtrAlign));
920 
921   auto NewList = MIRBuilder.buildPtrAdd(PtrTy, DstPtr, Size.getReg(0));
922 
923   MIRBuilder.buildStore(NewList, ListPtr,
924                         *MF.getMachineMemOperand(MachinePointerInfo(),
925                                                  MachineMemOperand::MOStore,
926                                                  PtrSize, PtrAlign));
927 
928   MI.eraseFromParent();
929   return true;
930 }
931