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 "AArch64RegisterBankInfo.h"
16 #include "AArch64Subtarget.h"
17 #include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
18 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
19 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
20 #include "llvm/CodeGen/GlobalISel/Utils.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/TargetOpcodes.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IntrinsicsAArch64.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/MathExtras.h"
29 #include <initializer_list>
30 
31 #define DEBUG_TYPE "aarch64-legalinfo"
32 
33 using namespace llvm;
34 using namespace LegalizeActions;
35 using namespace LegalizeMutations;
36 using namespace LegalityPredicates;
37 
38 AArch64LegalizerInfo::AArch64LegalizerInfo(const AArch64Subtarget &ST)
39     : ST(&ST) {
40   using namespace TargetOpcode;
41   const LLT p0 = LLT::pointer(0, 64);
42   const LLT s1 = LLT::scalar(1);
43   const LLT s8 = LLT::scalar(8);
44   const LLT s16 = LLT::scalar(16);
45   const LLT s32 = LLT::scalar(32);
46   const LLT s64 = LLT::scalar(64);
47   const LLT s128 = LLT::scalar(128);
48   const LLT s256 = LLT::scalar(256);
49   const LLT v16s8 = LLT::fixed_vector(16, 8);
50   const LLT v8s8 = LLT::fixed_vector(8, 8);
51   const LLT v4s8 = LLT::fixed_vector(4, 8);
52   const LLT v8s16 = LLT::fixed_vector(8, 16);
53   const LLT v4s16 = LLT::fixed_vector(4, 16);
54   const LLT v2s16 = LLT::fixed_vector(2, 16);
55   const LLT v2s32 = LLT::fixed_vector(2, 32);
56   const LLT v4s32 = LLT::fixed_vector(4, 32);
57   const LLT v2s64 = LLT::fixed_vector(2, 64);
58   const LLT v2p0 = LLT::fixed_vector(2, p0);
59 
60   std::initializer_list<LLT> PackedVectorAllTypeList = {/* Begin 128bit types */
61                                                         v16s8, v8s16, v4s32,
62                                                         v2s64, v2p0,
63                                                         /* End 128bit types */
64                                                         /* Begin 64bit types */
65                                                         v8s8, v4s16, v2s32};
66 
67   const TargetMachine &TM = ST.getTargetLowering()->getTargetMachine();
68 
69   // FIXME: support subtargets which have neon/fp-armv8 disabled.
70   if (!ST.hasNEON() || !ST.hasFPARMv8()) {
71     getLegacyLegalizerInfo().computeTables();
72     return;
73   }
74 
75   // Some instructions only support s16 if the subtarget has full 16-bit FP
76   // support.
77   const bool HasFP16 = ST.hasFullFP16();
78   const LLT &MinFPScalar = HasFP16 ? s16 : s32;
79 
80   getActionDefinitionsBuilder({G_IMPLICIT_DEF, G_FREEZE})
81       .legalFor({p0, s1, s8, s16, s32, s64})
82       .legalFor(PackedVectorAllTypeList)
83       .clampScalar(0, s8, s64)
84       .widenScalarToNextPow2(0, 8)
85       .fewerElementsIf(
86           [=](const LegalityQuery &Query) {
87             return Query.Types[0].isVector() &&
88                    (Query.Types[0].getElementType() != s64 ||
89                     Query.Types[0].getNumElements() != 2);
90           },
91           [=](const LegalityQuery &Query) {
92             LLT EltTy = Query.Types[0].getElementType();
93             if (EltTy == s64)
94               return std::make_pair(0, LLT::fixed_vector(2, 64));
95             return std::make_pair(0, EltTy);
96           });
97 
98   getActionDefinitionsBuilder(G_PHI).legalFor({p0, s16, s32, s64})
99       .legalFor(PackedVectorAllTypeList)
100       .clampScalar(0, s16, s64)
101       .widenScalarToNextPow2(0);
102 
103   getActionDefinitionsBuilder(G_BSWAP)
104       .legalFor({s32, s64, v4s32, v2s32, v2s64})
105       .clampScalar(0, s32, s64)
106       .widenScalarToNextPow2(0)
107       .customIf(typeIs(0, v2s16)); // custom lower as G_REV32 + G_LSHR
108 
109   getActionDefinitionsBuilder({G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR})
110       .legalFor({s32, s64, v2s32, v4s32, v4s16, v8s16, v16s8, v8s8})
111       .scalarizeIf(
112           [=](const LegalityQuery &Query) {
113             return Query.Opcode == G_MUL && Query.Types[0] == v2s64;
114           },
115           0)
116       .legalFor({v2s64})
117       .clampScalar(0, s32, s64)
118       .widenScalarToNextPow2(0)
119       .clampNumElements(0, v2s32, v4s32)
120       .clampNumElements(0, v2s64, v2s64)
121       .moreElementsToNextPow2(0);
122 
123   getActionDefinitionsBuilder({G_SHL, G_ASHR, G_LSHR})
124       .customIf([=](const LegalityQuery &Query) {
125         const auto &SrcTy = Query.Types[0];
126         const auto &AmtTy = Query.Types[1];
127         return !SrcTy.isVector() && SrcTy.getSizeInBits() == 32 &&
128                AmtTy.getSizeInBits() == 32;
129       })
130       .legalFor({
131           {s32, s32},
132           {s32, s64},
133           {s64, s64},
134           {v8s8, v8s8},
135           {v16s8, v16s8},
136           {v4s16, v4s16},
137           {v8s16, v8s16},
138           {v2s32, v2s32},
139           {v4s32, v4s32},
140           {v2s64, v2s64},
141       })
142       .widenScalarToNextPow2(0)
143       .clampScalar(1, s32, s64)
144       .clampScalar(0, s32, s64)
145       .clampNumElements(0, v2s32, v4s32)
146       .clampNumElements(0, v2s64, v2s64)
147       .moreElementsToNextPow2(0)
148       .minScalarSameAs(1, 0);
149 
150   getActionDefinitionsBuilder(G_PTR_ADD)
151       .legalFor({{p0, s64}, {v2p0, v2s64}})
152       .clampScalar(1, s64, s64);
153 
154   getActionDefinitionsBuilder(G_PTRMASK).legalFor({{p0, s64}});
155 
156   getActionDefinitionsBuilder({G_SDIV, G_UDIV})
157       .legalFor({s32, s64})
158       .libcallFor({s128})
159       .clampScalar(0, s32, s64)
160       .widenScalarToNextPow2(0)
161       .scalarize(0);
162 
163   getActionDefinitionsBuilder({G_SREM, G_UREM, G_SDIVREM, G_UDIVREM})
164       .lowerFor({s1, s8, s16, s32, s64});
165 
166   getActionDefinitionsBuilder({G_SMULO, G_UMULO}).lowerFor({{s64, s1}});
167 
168   getActionDefinitionsBuilder({G_SMULH, G_UMULH}).legalFor({s32, s64});
169 
170   getActionDefinitionsBuilder({G_SMIN, G_SMAX, G_UMIN, G_UMAX})
171       .legalFor({v8s8, v16s8, v4s16, v8s16, v2s32, v4s32})
172       .clampNumElements(0, v8s8, v16s8)
173       .clampNumElements(0, v4s16, v8s16)
174       .clampNumElements(0, v2s32, v4s32)
175       // FIXME: This sholdn't be needed as v2s64 types are going to
176       // be expanded anyway, but G_ICMP doesn't support splitting vectors yet
177       .clampNumElements(0, v2s64, v2s64)
178       .lower();
179 
180   getActionDefinitionsBuilder(
181       {G_SADDE, G_SSUBE, G_UADDE, G_USUBE, G_SADDO, G_SSUBO, G_UADDO, G_USUBO})
182       .legalFor({{s32, s1}, {s64, s1}})
183       .clampScalar(0, s32, s64)
184       .widenScalarToNextPow2(0);
185 
186   getActionDefinitionsBuilder({G_FADD, G_FSUB, G_FMUL, G_FDIV, G_FNEG})
187       .legalFor({s32, s64, v2s64, v4s32, v2s32})
188       .clampNumElements(0, v2s32, v4s32)
189       .clampNumElements(0, v2s64, v2s64);
190 
191   getActionDefinitionsBuilder(G_FREM).libcallFor({s32, s64});
192 
193   getActionDefinitionsBuilder({G_FCEIL, G_FABS, G_FSQRT, G_FFLOOR, G_FRINT,
194                                G_FMA, G_INTRINSIC_TRUNC, G_INTRINSIC_ROUND,
195                                G_FNEARBYINT, G_INTRINSIC_LRINT})
196       // If we don't have full FP16 support, then scalarize the elements of
197       // vectors containing fp16 types.
198       .fewerElementsIf(
199           [=, &ST](const LegalityQuery &Query) {
200             const auto &Ty = Query.Types[0];
201             return Ty.isVector() && Ty.getElementType() == s16 &&
202                    !ST.hasFullFP16();
203           },
204           [=](const LegalityQuery &Query) { return std::make_pair(0, s16); })
205       // If we don't have full FP16 support, then widen s16 to s32 if we
206       // encounter it.
207       .widenScalarIf(
208           [=, &ST](const LegalityQuery &Query) {
209             return Query.Types[0] == s16 && !ST.hasFullFP16();
210           },
211           [=](const LegalityQuery &Query) { return std::make_pair(0, s32); })
212       .legalFor({s16, s32, s64, v2s32, v4s32, v2s64, v2s16, v4s16, v8s16});
213 
214   getActionDefinitionsBuilder(
215       {G_FCOS, G_FSIN, G_FLOG10, G_FLOG, G_FLOG2, G_FEXP, G_FEXP2, G_FPOW})
216       // We need a call for these, so we always need to scalarize.
217       .scalarize(0)
218       // Regardless of FP16 support, widen 16-bit elements to 32-bits.
219       .minScalar(0, s32)
220       .libcallFor({s32, s64, v2s32, v4s32, v2s64});
221 
222   getActionDefinitionsBuilder(G_INSERT)
223       .unsupportedIf([=](const LegalityQuery &Query) {
224         return Query.Types[0].getSizeInBits() <= Query.Types[1].getSizeInBits();
225       })
226       .legalIf([=](const LegalityQuery &Query) {
227         const LLT &Ty0 = Query.Types[0];
228         const LLT &Ty1 = Query.Types[1];
229         if (Ty0 != s32 && Ty0 != s64 && Ty0 != p0)
230           return false;
231         return isPowerOf2_32(Ty1.getSizeInBits()) &&
232                (Ty1.getSizeInBits() == 1 || Ty1.getSizeInBits() >= 8);
233       })
234       .clampScalar(0, s32, s64)
235       .widenScalarToNextPow2(0)
236       .maxScalarIf(typeInSet(0, {s32}), 1, s16)
237       .maxScalarIf(typeInSet(0, {s64}), 1, s32)
238       .widenScalarToNextPow2(1);
239 
240   getActionDefinitionsBuilder(G_EXTRACT)
241       .unsupportedIf([=](const LegalityQuery &Query) {
242         return Query.Types[0].getSizeInBits() >= Query.Types[1].getSizeInBits();
243       })
244       .legalIf([=](const LegalityQuery &Query) {
245         const LLT &Ty0 = Query.Types[0];
246         const LLT &Ty1 = Query.Types[1];
247         if (Ty1 != s32 && Ty1 != s64 && Ty1 != s128)
248           return false;
249         if (Ty1 == p0)
250           return true;
251         return isPowerOf2_32(Ty0.getSizeInBits()) &&
252                (Ty0.getSizeInBits() == 1 || Ty0.getSizeInBits() >= 8);
253       })
254       .clampScalar(1, s32, s128)
255       .widenScalarToNextPow2(1)
256       .maxScalarIf(typeInSet(1, {s32}), 0, s16)
257       .maxScalarIf(typeInSet(1, {s64}), 0, s32)
258       .widenScalarToNextPow2(0);
259 
260   getActionDefinitionsBuilder({G_SEXTLOAD, G_ZEXTLOAD})
261       .lowerIf(atomicOrderingAtLeastOrStrongerThan(0, AtomicOrdering::Unordered))
262       .legalForTypesWithMemDesc({{s32, p0, s8, 8},
263                                  {s32, p0, s16, 8},
264                                  {s32, p0, s32, 8},
265                                  {s64, p0, s8, 2},
266                                  {s64, p0, s16, 2},
267                                  {s64, p0, s32, 4},
268                                  {s64, p0, s64, 8},
269                                  {p0, p0, s64, 8},
270                                  {v2s32, p0, s64, 8}})
271       .clampScalar(0, s32, s64)
272       .widenScalarToNextPow2(0)
273       // TODO: We could support sum-of-pow2's but the lowering code doesn't know
274       //       how to do that yet.
275       .unsupportedIfMemSizeNotPow2()
276       // Lower anything left over into G_*EXT and G_LOAD
277       .lower();
278 
279   auto IsPtrVecPred = [=](const LegalityQuery &Query) {
280     const LLT &ValTy = Query.Types[0];
281     if (!ValTy.isVector())
282       return false;
283     const LLT EltTy = ValTy.getElementType();
284     return EltTy.isPointer() && EltTy.getAddressSpace() == 0;
285   };
286 
287   getActionDefinitionsBuilder(G_LOAD)
288       .legalForTypesWithMemDesc({{s8, p0, s8, 8},
289                                  {s16, p0, s16, 8},
290                                  {s32, p0, s32, 8},
291                                  {s64, p0, s64, 8},
292                                  {p0, p0, s64, 8},
293                                  {s128, p0, s128, 8},
294                                  {v8s8, p0, s64, 8},
295                                  {v16s8, p0, s128, 8},
296                                  {v4s16, p0, s64, 8},
297                                  {v8s16, p0, s128, 8},
298                                  {v2s32, p0, s64, 8},
299                                  {v4s32, p0, s128, 8},
300                                  {v2s64, p0, s128, 8}})
301       // These extends are also legal
302       .legalForTypesWithMemDesc({{s32, p0, s8, 8}, {s32, p0, s16, 8}})
303       .clampScalar(0, s8, s64)
304       .lowerIfMemSizeNotPow2()
305       .widenScalarToNextPow2(0)
306       .narrowScalarIf([=](const LegalityQuery &Query) {
307         // Clamp extending load results to 32-bits.
308         return Query.Types[0].isScalar() &&
309           Query.Types[0] != Query.MMODescrs[0].MemoryTy &&
310           Query.Types[0].getSizeInBits() > 32;
311         },
312         changeTo(0, s32))
313       // Lower any any-extending loads left into G_ANYEXT and G_LOAD
314       .lowerIf([=](const LegalityQuery &Query) {
315         return Query.Types[0] != Query.MMODescrs[0].MemoryTy;
316       })
317       .clampMaxNumElements(0, s8, 16)
318       .clampMaxNumElements(0, s16, 8)
319       .clampMaxNumElements(0, s32, 4)
320       .clampMaxNumElements(0, s64, 2)
321       .customIf(IsPtrVecPred)
322       .scalarizeIf(typeIs(0, v2s16), 0);
323 
324   getActionDefinitionsBuilder(G_STORE)
325       .legalForTypesWithMemDesc({{s8, p0, s8, 8},
326                                  {s16, p0, s8, 8}, // truncstorei8 from s16
327                                  {s32, p0, s8, 8}, // truncstorei8 from s32
328                                  {s64, p0, s8, 8}, // truncstorei8 from s64
329                                  {s16, p0, s16, 8},
330                                  {s32, p0, s16, 8}, // truncstorei16 from s32
331                                  {s64, p0, s16, 8}, // truncstorei16 from s64
332                                  {s32, p0, s8, 8},
333                                  {s32, p0, s16, 8},
334                                  {s32, p0, s32, 8},
335                                  {s64, p0, s64, 8},
336                                  {s64, p0, s32, 8}, // truncstorei32 from s64
337                                  {p0, p0, s64, 8},
338                                  {s128, p0, s128, 8},
339                                  {v16s8, p0, s128, 8},
340                                  {v8s8, p0, s64, 8},
341                                  {v4s16, p0, s64, 8},
342                                  {v8s16, p0, s128, 8},
343                                  {v2s32, p0, s64, 8},
344                                  {v4s32, p0, s128, 8},
345                                  {v2s64, p0, s128, 8}})
346       .clampScalar(0, s8, s64)
347       .lowerIf([=](const LegalityQuery &Query) {
348         return Query.Types[0].isScalar() &&
349                Query.Types[0] != Query.MMODescrs[0].MemoryTy;
350       })
351       // Maximum: sN * k = 128
352       .clampMaxNumElements(0, s8, 16)
353       .clampMaxNumElements(0, s16, 8)
354       .clampMaxNumElements(0, s32, 4)
355       .clampMaxNumElements(0, s64, 2)
356       .lowerIfMemSizeNotPow2()
357       .customIf(IsPtrVecPred)
358       .scalarizeIf(typeIs(0, v2s16), 0);
359 
360   // Constants
361   getActionDefinitionsBuilder(G_CONSTANT)
362       .legalFor({p0, s8, s16, s32, s64})
363       .clampScalar(0, s8, s64)
364       .widenScalarToNextPow2(0);
365   getActionDefinitionsBuilder(G_FCONSTANT)
366       .legalIf([=](const LegalityQuery &Query) {
367         const auto &Ty = Query.Types[0];
368         if (HasFP16 && Ty == s16)
369           return true;
370         return Ty == s32 || Ty == s64 || Ty == s128;
371       })
372       .clampScalar(0, MinFPScalar, s128);
373 
374   getActionDefinitionsBuilder({G_ICMP, G_FCMP})
375       .legalFor({{s32, s32},
376                  {s32, s64},
377                  {s32, p0},
378                  {v4s32, v4s32},
379                  {v2s32, v2s32},
380                  {v2s64, v2s64},
381                  {v2s64, v2p0},
382                  {v4s16, v4s16},
383                  {v8s16, v8s16},
384                  {v8s8, v8s8},
385                  {v16s8, v16s8}})
386       .clampScalar(1, s32, s64)
387       .clampScalar(0, s32, s32)
388       .minScalarEltSameAsIf(
389           [=](const LegalityQuery &Query) {
390             const LLT &Ty = Query.Types[0];
391             const LLT &SrcTy = Query.Types[1];
392             return Ty.isVector() && !SrcTy.getElementType().isPointer() &&
393                    Ty.getElementType() != SrcTy.getElementType();
394           },
395           0, 1)
396       .minScalarOrEltIf(
397           [=](const LegalityQuery &Query) { return Query.Types[1] == v2s16; },
398           1, s32)
399       .minScalarOrEltIf(
400           [=](const LegalityQuery &Query) { return Query.Types[1] == v2p0; }, 0,
401           s64)
402       .widenScalarOrEltToNextPow2(1)
403       .clampNumElements(0, v2s32, v4s32);
404 
405   // Extensions
406   auto ExtLegalFunc = [=](const LegalityQuery &Query) {
407     unsigned DstSize = Query.Types[0].getSizeInBits();
408 
409     if (DstSize == 128 && !Query.Types[0].isVector())
410       return false; // Extending to a scalar s128 needs narrowing.
411 
412     // Make sure that we have something that will fit in a register, and
413     // make sure it's a power of 2.
414     if (DstSize < 8 || DstSize > 128 || !isPowerOf2_32(DstSize))
415       return false;
416 
417     const LLT &SrcTy = Query.Types[1];
418 
419     // Special case for s1.
420     if (SrcTy == s1)
421       return true;
422 
423     // Make sure we fit in a register otherwise. Don't bother checking that
424     // the source type is below 128 bits. We shouldn't be allowing anything
425     // through which is wider than the destination in the first place.
426     unsigned SrcSize = SrcTy.getSizeInBits();
427     if (SrcSize < 8 || !isPowerOf2_32(SrcSize))
428       return false;
429 
430     return true;
431   };
432   getActionDefinitionsBuilder({G_ZEXT, G_SEXT, G_ANYEXT})
433       .legalIf(ExtLegalFunc)
434       .clampScalar(0, s64, s64); // Just for s128, others are handled above.
435 
436   getActionDefinitionsBuilder(G_TRUNC)
437       .minScalarOrEltIf(
438           [=](const LegalityQuery &Query) { return Query.Types[0].isVector(); },
439           0, s8)
440       .customIf([=](const LegalityQuery &Query) {
441         LLT DstTy = Query.Types[0];
442         LLT SrcTy = Query.Types[1];
443         return DstTy == v8s8 && SrcTy.getSizeInBits() > 128;
444       })
445       .alwaysLegal();
446 
447   getActionDefinitionsBuilder(G_SEXT_INREG).legalFor({s32, s64}).lower();
448 
449   // FP conversions
450   getActionDefinitionsBuilder(G_FPTRUNC)
451       .legalFor(
452           {{s16, s32}, {s16, s64}, {s32, s64}, {v4s16, v4s32}, {v2s32, v2s64}})
453       .clampMaxNumElements(0, s32, 2);
454   getActionDefinitionsBuilder(G_FPEXT)
455       .legalFor(
456           {{s32, s16}, {s64, s16}, {s64, s32}, {v4s32, v4s16}, {v2s64, v2s32}})
457       .clampMaxNumElements(0, s64, 2);
458 
459   // Conversions
460   getActionDefinitionsBuilder({G_FPTOSI, G_FPTOUI})
461       .legalForCartesianProduct({s32, s64, v2s64, v4s32, v2s32})
462       .clampScalar(0, s32, s64)
463       .widenScalarToNextPow2(0)
464       .clampScalar(1, s32, s64)
465       .widenScalarToNextPow2(1);
466 
467   getActionDefinitionsBuilder({G_SITOFP, G_UITOFP})
468       .legalForCartesianProduct({s32, s64, v2s64, v4s32, v2s32})
469       .clampScalar(1, s32, s64)
470       .minScalarSameAs(1, 0)
471       .clampScalar(0, s32, s64)
472       .widenScalarToNextPow2(0);
473 
474   // Control-flow
475   getActionDefinitionsBuilder(G_BRCOND).legalFor({s1, s8, s16, s32});
476   getActionDefinitionsBuilder(G_BRINDIRECT).legalFor({p0});
477 
478   getActionDefinitionsBuilder(G_SELECT)
479       .legalFor({{s32, s1}, {s64, s1}, {p0, s1}})
480       .clampScalar(0, s32, s64)
481       .widenScalarToNextPow2(0)
482       .minScalarEltSameAsIf(all(isVector(0), isVector(1)), 1, 0)
483       .lowerIf(isVector(0));
484 
485   // Pointer-handling
486   getActionDefinitionsBuilder(G_FRAME_INDEX).legalFor({p0});
487 
488   if (TM.getCodeModel() == CodeModel::Small)
489     getActionDefinitionsBuilder(G_GLOBAL_VALUE).custom();
490   else
491     getActionDefinitionsBuilder(G_GLOBAL_VALUE).legalFor({p0});
492 
493   getActionDefinitionsBuilder(G_PTRTOINT)
494       .legalForCartesianProduct({s1, s8, s16, s32, s64}, {p0})
495       .maxScalar(0, s64)
496       .widenScalarToNextPow2(0, /*Min*/ 8);
497 
498   getActionDefinitionsBuilder(G_INTTOPTR)
499       .unsupportedIf([&](const LegalityQuery &Query) {
500         return Query.Types[0].getSizeInBits() != Query.Types[1].getSizeInBits();
501       })
502       .legalFor({{p0, s64}, {v2p0, v2s64}});
503 
504   // Casts for 32 and 64-bit width type are just copies.
505   // Same for 128-bit width type, except they are on the FPR bank.
506   getActionDefinitionsBuilder(G_BITCAST)
507       // FIXME: This is wrong since G_BITCAST is not allowed to change the
508       // number of bits but it's what the previous code described and fixing
509       // it breaks tests.
510       .legalForCartesianProduct({s1, s8, s16, s32, s64, s128, v16s8, v8s8, v4s8,
511                                  v8s16, v4s16, v2s16, v4s32, v2s32, v2s64,
512                                  v2p0});
513 
514   getActionDefinitionsBuilder(G_VASTART).legalFor({p0});
515 
516   // va_list must be a pointer, but most sized types are pretty easy to handle
517   // as the destination.
518   getActionDefinitionsBuilder(G_VAARG)
519       .customForCartesianProduct({s8, s16, s32, s64, p0}, {p0})
520       .clampScalar(0, s8, s64)
521       .widenScalarToNextPow2(0, /*Min*/ 8);
522 
523   getActionDefinitionsBuilder(G_ATOMIC_CMPXCHG_WITH_SUCCESS)
524       .lowerIf(
525           all(typeInSet(0, {s8, s16, s32, s64, s128}), typeIs(1, s1), typeIs(2, p0)));
526 
527   getActionDefinitionsBuilder(G_ATOMIC_CMPXCHG)
528       .customIf([](const LegalityQuery &Query) {
529         return Query.Types[0].getSizeInBits() == 128;
530       })
531       .clampScalar(0, s32, s64)
532       .legalIf(all(typeInSet(0, {s32, s64}), typeIs(1, p0)));
533 
534   getActionDefinitionsBuilder(
535       {G_ATOMICRMW_XCHG, G_ATOMICRMW_ADD, G_ATOMICRMW_SUB, G_ATOMICRMW_AND,
536        G_ATOMICRMW_OR, G_ATOMICRMW_XOR, G_ATOMICRMW_MIN, G_ATOMICRMW_MAX,
537        G_ATOMICRMW_UMIN, G_ATOMICRMW_UMAX})
538       .clampScalar(0, s32, s64)
539       .legalIf(all(typeInSet(0, {s32, s64}), typeIs(1, p0)));
540 
541   getActionDefinitionsBuilder(G_BLOCK_ADDR).legalFor({p0});
542 
543   // Merge/Unmerge
544   for (unsigned Op : {G_MERGE_VALUES, G_UNMERGE_VALUES}) {
545     unsigned BigTyIdx = Op == G_MERGE_VALUES ? 0 : 1;
546     unsigned LitTyIdx = Op == G_MERGE_VALUES ? 1 : 0;
547 
548     auto notValidElt = [](const LegalityQuery &Query, unsigned TypeIdx) {
549       const LLT &Ty = Query.Types[TypeIdx];
550       if (Ty.isVector()) {
551         const LLT &EltTy = Ty.getElementType();
552         if (EltTy.getSizeInBits() < 8 || EltTy.getSizeInBits() > 64)
553           return true;
554         if (!isPowerOf2_32(EltTy.getSizeInBits()))
555           return true;
556       }
557       return false;
558     };
559 
560     // FIXME: This rule is horrible, but specifies the same as what we had
561     // before with the particularly strange definitions removed (e.g.
562     // s8 = G_MERGE_VALUES s32, s32).
563     // Part of the complexity comes from these ops being extremely flexible. For
564     // example, you can build/decompose vectors with it, concatenate vectors,
565     // etc. and in addition to this you can also bitcast with it at the same
566     // time. We've been considering breaking it up into multiple ops to make it
567     // more manageable throughout the backend.
568     getActionDefinitionsBuilder(Op)
569         // Break up vectors with weird elements into scalars
570         .fewerElementsIf(
571             [=](const LegalityQuery &Query) { return notValidElt(Query, 0); },
572             scalarize(0))
573         .fewerElementsIf(
574             [=](const LegalityQuery &Query) { return notValidElt(Query, 1); },
575             scalarize(1))
576         // Clamp the big scalar to s8-s128 and make it a power of 2.
577         .clampScalar(BigTyIdx, s8, s128)
578         .widenScalarIf(
579             [=](const LegalityQuery &Query) {
580               const LLT &Ty = Query.Types[BigTyIdx];
581               return !isPowerOf2_32(Ty.getSizeInBits()) &&
582                      Ty.getSizeInBits() % 64 != 0;
583             },
584             [=](const LegalityQuery &Query) {
585               // Pick the next power of 2, or a multiple of 64 over 128.
586               // Whichever is smaller.
587               const LLT &Ty = Query.Types[BigTyIdx];
588               unsigned NewSizeInBits = 1
589                                        << Log2_32_Ceil(Ty.getSizeInBits() + 1);
590               if (NewSizeInBits >= 256) {
591                 unsigned RoundedTo = alignTo<64>(Ty.getSizeInBits() + 1);
592                 if (RoundedTo < NewSizeInBits)
593                   NewSizeInBits = RoundedTo;
594               }
595               return std::make_pair(BigTyIdx, LLT::scalar(NewSizeInBits));
596             })
597         // Clamp the little scalar to s8-s256 and make it a power of 2. It's not
598         // worth considering the multiples of 64 since 2*192 and 2*384 are not
599         // valid.
600         .clampScalar(LitTyIdx, s8, s256)
601         .widenScalarToNextPow2(LitTyIdx, /*Min*/ 8)
602         // So at this point, we have s8, s16, s32, s64, s128, s192, s256, s384,
603         // s512, <X x s8>, <X x s16>, <X x s32>, or <X x s64>.
604         // At this point it's simple enough to accept the legal types.
605         .legalIf([=](const LegalityQuery &Query) {
606           const LLT &BigTy = Query.Types[BigTyIdx];
607           const LLT &LitTy = Query.Types[LitTyIdx];
608           if (BigTy.isVector() && BigTy.getSizeInBits() < 32)
609             return false;
610           if (LitTy.isVector() && LitTy.getSizeInBits() < 32)
611             return false;
612           return BigTy.getSizeInBits() % LitTy.getSizeInBits() == 0;
613         })
614         // Any vectors left are the wrong size. Scalarize them.
615         .scalarize(0)
616         .scalarize(1);
617   }
618 
619   getActionDefinitionsBuilder(G_EXTRACT_VECTOR_ELT)
620       .unsupportedIf([=](const LegalityQuery &Query) {
621         const LLT &EltTy = Query.Types[1].getElementType();
622         return Query.Types[0] != EltTy;
623       })
624       .minScalar(2, s64)
625       .legalIf([=](const LegalityQuery &Query) {
626         const LLT &VecTy = Query.Types[1];
627         return VecTy == v2s16 || VecTy == v4s16 || VecTy == v8s16 ||
628                VecTy == v4s32 || VecTy == v2s64 || VecTy == v2s32 ||
629                VecTy == v16s8 || VecTy == v2s32 || VecTy == v2p0;
630       })
631       .minScalarOrEltIf(
632           [=](const LegalityQuery &Query) {
633             // We want to promote to <M x s1> to <M x s64> if that wouldn't
634             // cause the total vec size to be > 128b.
635             return Query.Types[1].getNumElements() <= 2;
636           },
637           0, s64)
638       .minScalarOrEltIf(
639           [=](const LegalityQuery &Query) {
640             return Query.Types[1].getNumElements() <= 4;
641           },
642           0, s32)
643       .minScalarOrEltIf(
644           [=](const LegalityQuery &Query) {
645             return Query.Types[1].getNumElements() <= 8;
646           },
647           0, s16)
648       .minScalarOrEltIf(
649           [=](const LegalityQuery &Query) {
650             return Query.Types[1].getNumElements() <= 16;
651           },
652           0, s8)
653       .minScalarOrElt(0, s8) // Worst case, we need at least s8.
654       .clampMaxNumElements(1, s64, 2)
655       .clampMaxNumElements(1, s32, 4)
656       .clampMaxNumElements(1, s16, 8)
657       .clampMaxNumElements(1, p0, 2);
658 
659   getActionDefinitionsBuilder(G_INSERT_VECTOR_ELT)
660       .legalIf(typeInSet(0, {v8s16, v2s32, v4s32, v2s64}));
661 
662   getActionDefinitionsBuilder(G_BUILD_VECTOR)
663       .legalFor({{v8s8, s8},
664                  {v16s8, s8},
665                  {v2s16, s16},
666                  {v4s16, s16},
667                  {v8s16, s16},
668                  {v2s32, s32},
669                  {v4s32, s32},
670                  {v2p0, p0},
671                  {v2s64, s64}})
672       .clampNumElements(0, v4s32, v4s32)
673       .clampNumElements(0, v2s64, v2s64)
674       .minScalarSameAs(1, 0);
675 
676   getActionDefinitionsBuilder(G_BUILD_VECTOR_TRUNC).lower();
677 
678   getActionDefinitionsBuilder(G_CTLZ)
679       .legalForCartesianProduct(
680           {s32, s64, v8s8, v16s8, v4s16, v8s16, v2s32, v4s32})
681       .scalarize(1);
682   getActionDefinitionsBuilder(G_CTLZ_ZERO_UNDEF).lower();
683 
684   // TODO: Custom lowering for v2s32, v4s32, v2s64.
685   getActionDefinitionsBuilder(G_BITREVERSE).legalFor({s32, s64, v8s8, v16s8});
686 
687   getActionDefinitionsBuilder(G_CTTZ_ZERO_UNDEF).lower();
688 
689   // TODO: Handle vector types.
690   getActionDefinitionsBuilder(G_CTTZ)
691       .clampScalar(0, s32, s64)
692       .scalarSameSizeAs(1, 0)
693       .customFor({s32, s64});
694 
695   getActionDefinitionsBuilder(G_SHUFFLE_VECTOR)
696       .legalIf([=](const LegalityQuery &Query) {
697         const LLT &DstTy = Query.Types[0];
698         const LLT &SrcTy = Query.Types[1];
699         // For now just support the TBL2 variant which needs the source vectors
700         // to be the same size as the dest.
701         if (DstTy != SrcTy)
702           return false;
703         for (auto &Ty : {v2s32, v4s32, v2s64, v2p0, v16s8, v8s16}) {
704           if (DstTy == Ty)
705             return true;
706         }
707         return false;
708       })
709       // G_SHUFFLE_VECTOR can have scalar sources (from 1 x s vectors), we
710       // just want those lowered into G_BUILD_VECTOR
711       .lowerIf([=](const LegalityQuery &Query) {
712         return !Query.Types[1].isVector();
713       })
714       .moreElementsToNextPow2(0)
715       .clampNumElements(0, v4s32, v4s32)
716       .clampNumElements(0, v2s64, v2s64);
717 
718   getActionDefinitionsBuilder(G_CONCAT_VECTORS)
719       .legalFor({{v4s32, v2s32}, {v8s16, v4s16}});
720 
721   getActionDefinitionsBuilder(G_JUMP_TABLE).legalFor({{p0}, {s64}});
722 
723   getActionDefinitionsBuilder(G_BRJT).legalIf([=](const LegalityQuery &Query) {
724     return Query.Types[0] == p0 && Query.Types[1] == s64;
725   });
726 
727   getActionDefinitionsBuilder(G_DYN_STACKALLOC).lower();
728 
729   getActionDefinitionsBuilder({G_BZERO, G_MEMCPY, G_MEMMOVE, G_MEMSET})
730       .libcall();
731 
732   // FIXME: Legal types are only legal with NEON.
733   getActionDefinitionsBuilder(G_ABS)
734       .lowerIf(isScalar(0))
735       .legalFor(PackedVectorAllTypeList);
736 
737   getActionDefinitionsBuilder(G_VECREDUCE_FADD)
738       // We only have FADDP to do reduction-like operations. Lower the rest.
739       .legalFor({{s32, v2s32}, {s64, v2s64}})
740       .clampMaxNumElements(1, s64, 2)
741       .clampMaxNumElements(1, s32, 2)
742       .lower();
743 
744   getActionDefinitionsBuilder(G_VECREDUCE_ADD)
745       .legalFor(
746           {{s8, v16s8}, {s16, v8s16}, {s32, v4s32}, {s32, v2s32}, {s64, v2s64}})
747       .clampMaxNumElements(1, s64, 2)
748       .clampMaxNumElements(1, s32, 4)
749       .lower();
750 
751   getActionDefinitionsBuilder({G_UADDSAT, G_USUBSAT})
752       .lowerIf([=](const LegalityQuery &Q) { return Q.Types[0].isScalar(); });
753 
754   getActionDefinitionsBuilder({G_FSHL, G_FSHR}).lower();
755 
756   getActionDefinitionsBuilder(G_ROTR)
757       .legalFor({{s32, s64}, {s64, s64}})
758       .customIf([=](const LegalityQuery &Q) {
759         return Q.Types[0].isScalar() && Q.Types[1].getScalarSizeInBits() < 64;
760       })
761       .lower();
762   getActionDefinitionsBuilder(G_ROTL).lower();
763 
764   getActionDefinitionsBuilder({G_SBFX, G_UBFX})
765       .customFor({{s32, s32}, {s64, s64}});
766 
767   // TODO: Custom legalization for s128
768   // TODO: Use generic lowering when custom lowering is not possible.
769   auto always = [=](const LegalityQuery &Q) { return true; };
770   getActionDefinitionsBuilder(G_CTPOP)
771       .legalFor({{v8s8, v8s8}, {v16s8, v16s8}})
772       .clampScalar(0, s32, s128)
773       .widenScalarToNextPow2(0)
774       .minScalarEltSameAsIf(always, 1, 0)
775       .maxScalarEltSameAsIf(always, 1, 0)
776       .customFor({{s32, s32},
777                   {s64, s64},
778                   {v2s64, v2s64},
779                   {v2s32, v2s32},
780                   {v4s32, v4s32},
781                   {v4s16, v4s16},
782                   {v8s16, v8s16}});
783 
784   getLegacyLegalizerInfo().computeTables();
785   verify(*ST.getInstrInfo());
786 }
787 
788 bool AArch64LegalizerInfo::legalizeCustom(LegalizerHelper &Helper,
789                                           MachineInstr &MI) const {
790   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
791   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
792   GISelChangeObserver &Observer = Helper.Observer;
793   switch (MI.getOpcode()) {
794   default:
795     // No idea what to do.
796     return false;
797   case TargetOpcode::G_VAARG:
798     return legalizeVaArg(MI, MRI, MIRBuilder);
799   case TargetOpcode::G_LOAD:
800   case TargetOpcode::G_STORE:
801     return legalizeLoadStore(MI, MRI, MIRBuilder, Observer);
802   case TargetOpcode::G_BSWAP:
803     return legalizeBSwap(MI, MRI, MIRBuilder);
804   case TargetOpcode::G_SHL:
805   case TargetOpcode::G_ASHR:
806   case TargetOpcode::G_LSHR:
807     return legalizeShlAshrLshr(MI, MRI, MIRBuilder, Observer);
808   case TargetOpcode::G_GLOBAL_VALUE:
809     return legalizeSmallCMGlobalValue(MI, MRI, MIRBuilder, Observer);
810   case TargetOpcode::G_TRUNC:
811     return legalizeVectorTrunc(MI, Helper);
812   case TargetOpcode::G_SBFX:
813   case TargetOpcode::G_UBFX:
814     return legalizeBitfieldExtract(MI, MRI, Helper);
815   case TargetOpcode::G_ROTR:
816     return legalizeRotate(MI, MRI, Helper);
817   case TargetOpcode::G_CTPOP:
818     return legalizeCTPOP(MI, MRI, Helper);
819   case TargetOpcode::G_ATOMIC_CMPXCHG:
820     return legalizeAtomicCmpxchg128(MI, MRI, Helper);
821   case TargetOpcode::G_CTTZ:
822     return legalizeCTTZ(MI, Helper);
823   }
824 
825   llvm_unreachable("expected switch to return");
826 }
827 
828 bool AArch64LegalizerInfo::legalizeRotate(MachineInstr &MI,
829                                           MachineRegisterInfo &MRI,
830                                           LegalizerHelper &Helper) const {
831   // To allow for imported patterns to match, we ensure that the rotate amount
832   // is 64b with an extension.
833   Register AmtReg = MI.getOperand(2).getReg();
834   LLT AmtTy = MRI.getType(AmtReg);
835   (void)AmtTy;
836   assert(AmtTy.isScalar() && "Expected a scalar rotate");
837   assert(AmtTy.getSizeInBits() < 64 && "Expected this rotate to be legal");
838   auto NewAmt = Helper.MIRBuilder.buildSExt(LLT::scalar(64), AmtReg);
839   Helper.Observer.changingInstr(MI);
840   MI.getOperand(2).setReg(NewAmt.getReg(0));
841   Helper.Observer.changedInstr(MI);
842   return true;
843 }
844 
845 static void extractParts(Register Reg, MachineRegisterInfo &MRI,
846                          MachineIRBuilder &MIRBuilder, LLT Ty, int NumParts,
847                          SmallVectorImpl<Register> &VRegs) {
848   for (int I = 0; I < NumParts; ++I)
849     VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
850   MIRBuilder.buildUnmerge(VRegs, Reg);
851 }
852 
853 bool AArch64LegalizerInfo::legalizeVectorTrunc(
854     MachineInstr &MI, LegalizerHelper &Helper) const {
855   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
856   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
857   // Similar to how operand splitting is done in SelectiondDAG, we can handle
858   // %res(v8s8) = G_TRUNC %in(v8s32) by generating:
859   //   %inlo(<4x s32>), %inhi(<4 x s32>) = G_UNMERGE %in(<8 x s32>)
860   //   %lo16(<4 x s16>) = G_TRUNC %inlo
861   //   %hi16(<4 x s16>) = G_TRUNC %inhi
862   //   %in16(<8 x s16>) = G_CONCAT_VECTORS %lo16, %hi16
863   //   %res(<8 x s8>) = G_TRUNC %in16
864 
865   Register DstReg = MI.getOperand(0).getReg();
866   Register SrcReg = MI.getOperand(1).getReg();
867   LLT DstTy = MRI.getType(DstReg);
868   LLT SrcTy = MRI.getType(SrcReg);
869   assert(isPowerOf2_32(DstTy.getSizeInBits()) &&
870          isPowerOf2_32(SrcTy.getSizeInBits()));
871 
872   // Split input type.
873   LLT SplitSrcTy =
874       SrcTy.changeElementCount(SrcTy.getElementCount().divideCoefficientBy(2));
875   // First, split the source into two smaller vectors.
876   SmallVector<Register, 2> SplitSrcs;
877   extractParts(SrcReg, MRI, MIRBuilder, SplitSrcTy, 2, SplitSrcs);
878 
879   // Truncate the splits into intermediate narrower elements.
880   LLT InterTy = SplitSrcTy.changeElementSize(DstTy.getScalarSizeInBits() * 2);
881   for (unsigned I = 0; I < SplitSrcs.size(); ++I)
882     SplitSrcs[I] = MIRBuilder.buildTrunc(InterTy, SplitSrcs[I]).getReg(0);
883 
884   auto Concat = MIRBuilder.buildConcatVectors(
885       DstTy.changeElementSize(DstTy.getScalarSizeInBits() * 2), SplitSrcs);
886 
887   Helper.Observer.changingInstr(MI);
888   MI.getOperand(1).setReg(Concat.getReg(0));
889   Helper.Observer.changedInstr(MI);
890   return true;
891 }
892 
893 bool AArch64LegalizerInfo::legalizeSmallCMGlobalValue(
894     MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder,
895     GISelChangeObserver &Observer) const {
896   assert(MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE);
897   // We do this custom legalization to convert G_GLOBAL_VALUE into target ADRP +
898   // G_ADD_LOW instructions.
899   // By splitting this here, we can optimize accesses in the small code model by
900   // folding in the G_ADD_LOW into the load/store offset.
901   auto &GlobalOp = MI.getOperand(1);
902   const auto* GV = GlobalOp.getGlobal();
903   if (GV->isThreadLocal())
904     return true; // Don't want to modify TLS vars.
905 
906   auto &TM = ST->getTargetLowering()->getTargetMachine();
907   unsigned OpFlags = ST->ClassifyGlobalReference(GV, TM);
908 
909   if (OpFlags & AArch64II::MO_GOT)
910     return true;
911 
912   auto Offset = GlobalOp.getOffset();
913   Register DstReg = MI.getOperand(0).getReg();
914   auto ADRP = MIRBuilder.buildInstr(AArch64::ADRP, {LLT::pointer(0, 64)}, {})
915                   .addGlobalAddress(GV, Offset, OpFlags | AArch64II::MO_PAGE);
916   // Set the regclass on the dest reg too.
917   MRI.setRegClass(ADRP.getReg(0), &AArch64::GPR64RegClass);
918 
919   // MO_TAGGED on the page indicates a tagged address. Set the tag now. We do so
920   // by creating a MOVK that sets bits 48-63 of the register to (global address
921   // + 0x100000000 - PC) >> 48. The additional 0x100000000 offset here is to
922   // prevent an incorrect tag being generated during relocation when the the
923   // global appears before the code section. Without the offset, a global at
924   // `0x0f00'0000'0000'1000` (i.e. at `0x1000` with tag `0xf`) that's referenced
925   // by code at `0x2000` would result in `0x0f00'0000'0000'1000 - 0x2000 =
926   // 0x0eff'ffff'ffff'f000`, meaning the tag would be incorrectly set to `0xe`
927   // instead of `0xf`.
928   // This assumes that we're in the small code model so we can assume a binary
929   // size of <= 4GB, which makes the untagged PC relative offset positive. The
930   // binary must also be loaded into address range [0, 2^48). Both of these
931   // properties need to be ensured at runtime when using tagged addresses.
932   if (OpFlags & AArch64II::MO_TAGGED) {
933     assert(!Offset &&
934            "Should not have folded in an offset for a tagged global!");
935     ADRP = MIRBuilder.buildInstr(AArch64::MOVKXi, {LLT::pointer(0, 64)}, {ADRP})
936                .addGlobalAddress(GV, 0x100000000,
937                                  AArch64II::MO_PREL | AArch64II::MO_G3)
938                .addImm(48);
939     MRI.setRegClass(ADRP.getReg(0), &AArch64::GPR64RegClass);
940   }
941 
942   MIRBuilder.buildInstr(AArch64::G_ADD_LOW, {DstReg}, {ADRP})
943       .addGlobalAddress(GV, Offset,
944                         OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
945   MI.eraseFromParent();
946   return true;
947 }
948 
949 bool AArch64LegalizerInfo::legalizeIntrinsic(LegalizerHelper &Helper,
950                                              MachineInstr &MI) const {
951   return true;
952 }
953 
954 bool AArch64LegalizerInfo::legalizeShlAshrLshr(
955     MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder,
956     GISelChangeObserver &Observer) const {
957   assert(MI.getOpcode() == TargetOpcode::G_ASHR ||
958          MI.getOpcode() == TargetOpcode::G_LSHR ||
959          MI.getOpcode() == TargetOpcode::G_SHL);
960   // If the shift amount is a G_CONSTANT, promote it to a 64 bit type so the
961   // imported patterns can select it later. Either way, it will be legal.
962   Register AmtReg = MI.getOperand(2).getReg();
963   auto VRegAndVal = getConstantVRegValWithLookThrough(AmtReg, MRI);
964   if (!VRegAndVal)
965     return true;
966   // Check the shift amount is in range for an immediate form.
967   int64_t Amount = VRegAndVal->Value.getSExtValue();
968   if (Amount > 31)
969     return true; // This will have to remain a register variant.
970   auto ExtCst = MIRBuilder.buildConstant(LLT::scalar(64), Amount);
971   Observer.changingInstr(MI);
972   MI.getOperand(2).setReg(ExtCst.getReg(0));
973   Observer.changedInstr(MI);
974   return true;
975 }
976 
977 // FIXME: This should be removed and replaced with the generic bitcast legalize
978 // action.
979 bool AArch64LegalizerInfo::legalizeLoadStore(
980     MachineInstr &MI, MachineRegisterInfo &MRI, MachineIRBuilder &MIRBuilder,
981     GISelChangeObserver &Observer) const {
982   assert(MI.getOpcode() == TargetOpcode::G_STORE ||
983          MI.getOpcode() == TargetOpcode::G_LOAD);
984   // Here we just try to handle vector loads/stores where our value type might
985   // have pointer elements, which the SelectionDAG importer can't handle. To
986   // allow the existing patterns for s64 to fire for p0, we just try to bitcast
987   // the value to use s64 types.
988 
989   // Custom legalization requires the instruction, if not deleted, must be fully
990   // legalized. In order to allow further legalization of the inst, we create
991   // a new instruction and erase the existing one.
992 
993   Register ValReg = MI.getOperand(0).getReg();
994   const LLT ValTy = MRI.getType(ValReg);
995 
996   if (!ValTy.isVector() || !ValTy.getElementType().isPointer() ||
997       ValTy.getElementType().getAddressSpace() != 0) {
998     LLVM_DEBUG(dbgs() << "Tried to do custom legalization on wrong load/store");
999     return false;
1000   }
1001 
1002   unsigned PtrSize = ValTy.getElementType().getSizeInBits();
1003   const LLT NewTy = LLT::vector(ValTy.getElementCount(), PtrSize);
1004   auto &MMO = **MI.memoperands_begin();
1005   MMO.setType(NewTy);
1006 
1007   if (MI.getOpcode() == TargetOpcode::G_STORE) {
1008     auto Bitcast = MIRBuilder.buildBitcast(NewTy, ValReg);
1009     MIRBuilder.buildStore(Bitcast.getReg(0), MI.getOperand(1), MMO);
1010   } else {
1011     auto NewLoad = MIRBuilder.buildLoad(NewTy, MI.getOperand(1), MMO);
1012     MIRBuilder.buildBitcast(ValReg, NewLoad);
1013   }
1014   MI.eraseFromParent();
1015   return true;
1016 }
1017 
1018 bool AArch64LegalizerInfo::legalizeBSwap(MachineInstr &MI,
1019                                          MachineRegisterInfo &MRI,
1020                                          MachineIRBuilder &MIRBuilder) const {
1021   assert(MI.getOpcode() == TargetOpcode::G_BSWAP);
1022 
1023   // The <2 x half> case needs special lowering because there isn't an
1024   // instruction that does that directly. Instead, we widen to <8 x i8>
1025   // and emit a G_REV32 followed by a G_LSHR knowing that instruction selection
1026   // will later match them as:
1027   //
1028   //   rev32.8b v0, v0
1029   //   ushr.2s v0, v0, #16
1030   //
1031   // We could emit those here directly, but it seems better to keep things as
1032   // generic as possible through legalization, and avoid committing layering
1033   // violations by legalizing & selecting here at the same time.
1034 
1035   Register ValReg = MI.getOperand(1).getReg();
1036   assert(LLT::fixed_vector(2, 16) == MRI.getType(ValReg));
1037   const LLT v2s32 = LLT::fixed_vector(2, 32);
1038   const LLT v8s8 = LLT::fixed_vector(8, 8);
1039   const LLT s32 = LLT::scalar(32);
1040 
1041   auto Undef = MIRBuilder.buildUndef(v8s8);
1042   auto Insert =
1043       MIRBuilder
1044           .buildInstr(TargetOpcode::INSERT_SUBREG, {v8s8}, {Undef, ValReg})
1045           .addImm(AArch64::ssub);
1046   auto Rev32 = MIRBuilder.buildInstr(AArch64::G_REV32, {v8s8}, {Insert});
1047   auto Bitcast = MIRBuilder.buildBitcast(v2s32, Rev32);
1048   auto Amt = MIRBuilder.buildConstant(v2s32, 16);
1049   auto UShr =
1050       MIRBuilder.buildInstr(TargetOpcode::G_LSHR, {v2s32}, {Bitcast, Amt});
1051   auto Zero = MIRBuilder.buildConstant(s32, 0);
1052   auto Extract = MIRBuilder.buildExtractVectorElement(s32, UShr, Zero);
1053   MIRBuilder.buildBitcast({MI.getOperand(0).getReg()}, Extract);
1054   MI.eraseFromParent();
1055   return true;
1056 }
1057 
1058 bool AArch64LegalizerInfo::legalizeVaArg(MachineInstr &MI,
1059                                          MachineRegisterInfo &MRI,
1060                                          MachineIRBuilder &MIRBuilder) const {
1061   MachineFunction &MF = MIRBuilder.getMF();
1062   Align Alignment(MI.getOperand(2).getImm());
1063   Register Dst = MI.getOperand(0).getReg();
1064   Register ListPtr = MI.getOperand(1).getReg();
1065 
1066   LLT PtrTy = MRI.getType(ListPtr);
1067   LLT IntPtrTy = LLT::scalar(PtrTy.getSizeInBits());
1068 
1069   const unsigned PtrSize = PtrTy.getSizeInBits() / 8;
1070   const Align PtrAlign = Align(PtrSize);
1071   auto List = MIRBuilder.buildLoad(
1072       PtrTy, ListPtr,
1073       *MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOLoad,
1074                                PtrTy, PtrAlign));
1075 
1076   MachineInstrBuilder DstPtr;
1077   if (Alignment > PtrAlign) {
1078     // Realign the list to the actual required alignment.
1079     auto AlignMinus1 =
1080         MIRBuilder.buildConstant(IntPtrTy, Alignment.value() - 1);
1081     auto ListTmp = MIRBuilder.buildPtrAdd(PtrTy, List, AlignMinus1.getReg(0));
1082     DstPtr = MIRBuilder.buildMaskLowPtrBits(PtrTy, ListTmp, Log2(Alignment));
1083   } else
1084     DstPtr = List;
1085 
1086   LLT ValTy = MRI.getType(Dst);
1087   uint64_t ValSize = ValTy.getSizeInBits() / 8;
1088   MIRBuilder.buildLoad(
1089       Dst, DstPtr,
1090       *MF.getMachineMemOperand(MachinePointerInfo(), MachineMemOperand::MOLoad,
1091                                ValTy, std::max(Alignment, PtrAlign)));
1092 
1093   auto Size = MIRBuilder.buildConstant(IntPtrTy, alignTo(ValSize, PtrAlign));
1094 
1095   auto NewList = MIRBuilder.buildPtrAdd(PtrTy, DstPtr, Size.getReg(0));
1096 
1097   MIRBuilder.buildStore(NewList, ListPtr,
1098                         *MF.getMachineMemOperand(MachinePointerInfo(),
1099                                                  MachineMemOperand::MOStore,
1100                                                  PtrTy, PtrAlign));
1101 
1102   MI.eraseFromParent();
1103   return true;
1104 }
1105 
1106 bool AArch64LegalizerInfo::legalizeBitfieldExtract(
1107     MachineInstr &MI, MachineRegisterInfo &MRI, LegalizerHelper &Helper) const {
1108   // Only legal if we can select immediate forms.
1109   // TODO: Lower this otherwise.
1110   return getConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), MRI) &&
1111          getConstantVRegValWithLookThrough(MI.getOperand(3).getReg(), MRI);
1112 }
1113 
1114 bool AArch64LegalizerInfo::legalizeCTPOP(MachineInstr &MI,
1115                                          MachineRegisterInfo &MRI,
1116                                          LegalizerHelper &Helper) const {
1117   // While there is no integer popcount instruction, it can
1118   // be more efficiently lowered to the following sequence that uses
1119   // AdvSIMD registers/instructions as long as the copies to/from
1120   // the AdvSIMD registers are cheap.
1121   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
1122   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
1123   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
1124   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
1125   //
1126   // For 128 bit vector popcounts, we lower to the following sequence:
1127   //  cnt.16b   v0, v0  // v8s16, v4s32, v2s64
1128   //  uaddlp.8h v0, v0  // v8s16, v4s32, v2s64
1129   //  uaddlp.4s v0, v0  //        v4s32, v2s64
1130   //  uaddlp.2d v0, v0  //               v2s64
1131   //
1132   // For 64 bit vector popcounts, we lower to the following sequence:
1133   //  cnt.8b    v0, v0  // v4s16, v2s32
1134   //  uaddlp.4h v0, v0  // v4s16, v2s32
1135   //  uaddlp.2s v0, v0  //        v2s32
1136 
1137   if (!ST->hasNEON() ||
1138       MI.getMF()->getFunction().hasFnAttribute(Attribute::NoImplicitFloat))
1139     return false;
1140   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
1141   Register Dst = MI.getOperand(0).getReg();
1142   Register Val = MI.getOperand(1).getReg();
1143   LLT Ty = MRI.getType(Val);
1144 
1145   assert(Ty == MRI.getType(Dst) &&
1146          "Expected src and dst to have the same type!");
1147   unsigned Size = Ty.getSizeInBits();
1148 
1149   // Pre-conditioning: widen Val up to the nearest vector type.
1150   // s32,s64,v4s16,v2s32 -> v8i8
1151   // v8s16,v4s32,v2s64 -> v16i8
1152   LLT VTy = Size == 128 ? LLT::fixed_vector(16, 8) : LLT::fixed_vector(8, 8);
1153   if (Ty.isScalar()) {
1154     // TODO: Handle s128.
1155     assert((Size == 32 || Size == 64) && "Expected only 32 or 64 bit scalars!");
1156     if (Size == 32) {
1157       Val = MIRBuilder.buildZExt(LLT::scalar(64), Val).getReg(0);
1158     }
1159   }
1160   Val = MIRBuilder.buildBitcast(VTy, Val).getReg(0);
1161 
1162   // Count bits in each byte-sized lane.
1163   auto CTPOP = MIRBuilder.buildCTPOP(VTy, Val);
1164 
1165   // Sum across lanes.
1166   Register HSum = CTPOP.getReg(0);
1167   unsigned Opc;
1168   SmallVector<LLT> HAddTys;
1169   if (Ty.isScalar()) {
1170     Opc = Intrinsic::aarch64_neon_uaddlv;
1171     HAddTys.push_back(LLT::scalar(32));
1172   } else if (Ty == LLT::fixed_vector(8, 16)) {
1173     Opc = Intrinsic::aarch64_neon_uaddlp;
1174     HAddTys.push_back(LLT::fixed_vector(8, 16));
1175   } else if (Ty == LLT::fixed_vector(4, 32)) {
1176     Opc = Intrinsic::aarch64_neon_uaddlp;
1177     HAddTys.push_back(LLT::fixed_vector(8, 16));
1178     HAddTys.push_back(LLT::fixed_vector(4, 32));
1179   } else if (Ty == LLT::fixed_vector(2, 64)) {
1180     Opc = Intrinsic::aarch64_neon_uaddlp;
1181     HAddTys.push_back(LLT::fixed_vector(8, 16));
1182     HAddTys.push_back(LLT::fixed_vector(4, 32));
1183     HAddTys.push_back(LLT::fixed_vector(2, 64));
1184   } else if (Ty == LLT::fixed_vector(4, 16)) {
1185     Opc = Intrinsic::aarch64_neon_uaddlp;
1186     HAddTys.push_back(LLT::fixed_vector(4, 16));
1187   } else if (Ty == LLT::fixed_vector(2, 32)) {
1188     Opc = Intrinsic::aarch64_neon_uaddlp;
1189     HAddTys.push_back(LLT::fixed_vector(4, 16));
1190     HAddTys.push_back(LLT::fixed_vector(2, 32));
1191   } else
1192     llvm_unreachable("unexpected vector shape");
1193   MachineInstrBuilder UADD;
1194   for (LLT HTy : HAddTys) {
1195     UADD = MIRBuilder.buildIntrinsic(Opc, {HTy}, /*HasSideEffects =*/false)
1196                      .addUse(HSum);
1197     HSum = UADD.getReg(0);
1198   }
1199 
1200   // Post-conditioning.
1201   if (Ty.isScalar() && Size == 64)
1202     MIRBuilder.buildZExt(Dst, UADD);
1203   else
1204     UADD->getOperand(0).setReg(Dst);
1205   MI.eraseFromParent();
1206   return true;
1207 }
1208 
1209 bool AArch64LegalizerInfo::legalizeAtomicCmpxchg128(
1210     MachineInstr &MI, MachineRegisterInfo &MRI, LegalizerHelper &Helper) const {
1211   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
1212   LLT s64 = LLT::scalar(64);
1213   auto Addr = MI.getOperand(1).getReg();
1214   auto DesiredI = MIRBuilder.buildUnmerge({s64, s64}, MI.getOperand(2));
1215   auto NewI = MIRBuilder.buildUnmerge({s64, s64}, MI.getOperand(3));
1216   auto DstLo = MRI.createGenericVirtualRegister(s64);
1217   auto DstHi = MRI.createGenericVirtualRegister(s64);
1218 
1219   MachineInstrBuilder CAS;
1220   if (ST->hasLSE()) {
1221     // We have 128-bit CASP instructions taking XSeqPair registers, which are
1222     // s128. We need the merge/unmerge to bracket the expansion and pair up with
1223     // the rest of the MIR so we must reassemble the extracted registers into a
1224     // 128-bit known-regclass one with code like this:
1225     //
1226     //     %in1 = REG_SEQUENCE Lo, Hi    ; One for each input
1227     //     %out = CASP %in1, ...
1228     //     %OldLo = G_EXTRACT %out, 0
1229     //     %OldHi = G_EXTRACT %out, 64
1230     auto Ordering = (*MI.memoperands_begin())->getMergedOrdering();
1231     unsigned Opcode;
1232     switch (Ordering) {
1233     case AtomicOrdering::Acquire:
1234       Opcode = AArch64::CASPAX;
1235       break;
1236     case AtomicOrdering::Release:
1237       Opcode = AArch64::CASPLX;
1238       break;
1239     case AtomicOrdering::AcquireRelease:
1240     case AtomicOrdering::SequentiallyConsistent:
1241       Opcode = AArch64::CASPALX;
1242       break;
1243     default:
1244       Opcode = AArch64::CASPX;
1245       break;
1246     }
1247 
1248     LLT s128 = LLT::scalar(128);
1249     auto CASDst = MRI.createGenericVirtualRegister(s128);
1250     auto CASDesired = MRI.createGenericVirtualRegister(s128);
1251     auto CASNew = MRI.createGenericVirtualRegister(s128);
1252     MIRBuilder.buildInstr(TargetOpcode::REG_SEQUENCE, {CASDesired}, {})
1253         .addUse(DesiredI->getOperand(0).getReg())
1254         .addImm(AArch64::sube64)
1255         .addUse(DesiredI->getOperand(1).getReg())
1256         .addImm(AArch64::subo64);
1257     MIRBuilder.buildInstr(TargetOpcode::REG_SEQUENCE, {CASNew}, {})
1258         .addUse(NewI->getOperand(0).getReg())
1259         .addImm(AArch64::sube64)
1260         .addUse(NewI->getOperand(1).getReg())
1261         .addImm(AArch64::subo64);
1262 
1263     CAS = MIRBuilder.buildInstr(Opcode, {CASDst}, {CASDesired, CASNew, Addr});
1264 
1265     MIRBuilder.buildExtract({DstLo}, {CASDst}, 0);
1266     MIRBuilder.buildExtract({DstHi}, {CASDst}, 64);
1267   } else {
1268     // The -O0 CMP_SWAP_128 is friendlier to generate code for because LDXP/STXP
1269     // can take arbitrary registers so it just has the normal GPR64 operands the
1270     // rest of AArch64 is expecting.
1271     auto Ordering = (*MI.memoperands_begin())->getMergedOrdering();
1272     unsigned Opcode;
1273     switch (Ordering) {
1274     case AtomicOrdering::Acquire:
1275       Opcode = AArch64::CMP_SWAP_128_ACQUIRE;
1276       break;
1277     case AtomicOrdering::Release:
1278       Opcode = AArch64::CMP_SWAP_128_RELEASE;
1279       break;
1280     case AtomicOrdering::AcquireRelease:
1281     case AtomicOrdering::SequentiallyConsistent:
1282       Opcode = AArch64::CMP_SWAP_128;
1283       break;
1284     default:
1285       Opcode = AArch64::CMP_SWAP_128_MONOTONIC;
1286       break;
1287     }
1288 
1289     auto Scratch = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1290     CAS = MIRBuilder.buildInstr(Opcode, {DstLo, DstHi, Scratch},
1291                                 {Addr, DesiredI->getOperand(0),
1292                                  DesiredI->getOperand(1), NewI->getOperand(0),
1293                                  NewI->getOperand(1)});
1294   }
1295 
1296   CAS.cloneMemRefs(MI);
1297   constrainSelectedInstRegOperands(*CAS, *ST->getInstrInfo(),
1298                                    *MRI.getTargetRegisterInfo(),
1299                                    *ST->getRegBankInfo());
1300 
1301   MIRBuilder.buildMerge(MI.getOperand(0), {DstLo, DstHi});
1302   MI.eraseFromParent();
1303   return true;
1304 }
1305 
1306 bool AArch64LegalizerInfo::legalizeCTTZ(MachineInstr &MI,
1307                                         LegalizerHelper &Helper) const {
1308   MachineIRBuilder &MIRBuilder = Helper.MIRBuilder;
1309   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
1310   LLT Ty = MRI.getType(MI.getOperand(1).getReg());
1311   auto BitReverse = MIRBuilder.buildBitReverse(Ty, MI.getOperand(1));
1312   MIRBuilder.buildCTLZ(MI.getOperand(0).getReg(), BitReverse);
1313   MI.eraseFromParent();
1314   return true;
1315 }
1316