xref: /llvm-project/llvm/lib/Target/RISCV/MCTargetDesc/RISCVMatInt.cpp (revision 186d5c8af5829bc4f6f0a3edcca43cef2d498c26)
1 //===- RISCVMatInt.cpp - Immediate materialisation -------------*- 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 
9 #include "RISCVMatInt.h"
10 #include "MCTargetDesc/RISCVMCTargetDesc.h"
11 #include "llvm/ADT/APInt.h"
12 #include "llvm/Support/MathExtras.h"
13 using namespace llvm;
14 
15 static int getInstSeqCost(RISCVMatInt::InstSeq &Res, bool HasRVC) {
16   if (!HasRVC)
17     return Res.size();
18 
19   int Cost = 0;
20   for (auto Instr : Res) {
21     // Assume instructions that aren't listed aren't compressible.
22     bool Compressed = false;
23     switch (Instr.Opc) {
24     case RISCV::SLLI:
25     case RISCV::SRLI:
26       Compressed = true;
27       break;
28     case RISCV::ADDI:
29     case RISCV::ADDIW:
30     case RISCV::LUI:
31       Compressed = isInt<6>(Instr.Imm);
32       break;
33     }
34     // Two RVC instructions take the same space as one RVI instruction, but
35     // can take longer to execute than the single RVI instruction. Thus, we
36     // consider that two RVC instruction are slightly more costly than one
37     // RVI instruction. For longer sequences of RVC instructions the space
38     // savings can be worth it, though. The costs below try to model that.
39     if (!Compressed)
40       Cost += 100; // Baseline cost of one RVI instruction: 100%.
41     else
42       Cost += 70; // 70% cost of baseline.
43   }
44   return Cost;
45 }
46 
47 // Recursively generate a sequence for materializing an integer.
48 static void generateInstSeqImpl(int64_t Val,
49                                 const FeatureBitset &ActiveFeatures,
50                                 RISCVMatInt::InstSeq &Res) {
51   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
52 
53   if (isInt<32>(Val)) {
54     // Depending on the active bits in the immediate Value v, the following
55     // instruction sequences are emitted:
56     //
57     // v == 0                        : ADDI
58     // v[0,12) != 0 && v[12,32) == 0 : ADDI
59     // v[0,12) == 0 && v[12,32) != 0 : LUI
60     // v[0,32) != 0                  : LUI+ADDI(W)
61     int64_t Hi20 = ((Val + 0x800) >> 12) & 0xFFFFF;
62     int64_t Lo12 = SignExtend64<12>(Val);
63 
64     if (Hi20)
65       Res.push_back(RISCVMatInt::Inst(RISCV::LUI, Hi20));
66 
67     if (Lo12 || Hi20 == 0) {
68       unsigned AddiOpc = (IsRV64 && Hi20) ? RISCV::ADDIW : RISCV::ADDI;
69       Res.push_back(RISCVMatInt::Inst(AddiOpc, Lo12));
70     }
71     return;
72   }
73 
74   assert(IsRV64 && "Can't emit >32-bit imm for non-RV64 target");
75 
76   // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
77   // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emitted. Note
78   // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
79   // while the following ADDI instructions contribute up to 12 bits each.
80   //
81   // On the first glance, implementing this seems to be possible by simply
82   // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
83   // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
84   // fact that ADDI performs a sign extended addition, doing it like that would
85   // only be possible when at most 11 bits of the ADDI instructions are used.
86   // Using all 12 bits of the ADDI instructions, like done by GAS, actually
87   // requires that the constant is processed starting with the least significant
88   // bit.
89   //
90   // In the following, constants are processed from LSB to MSB but instruction
91   // emission is performed from MSB to LSB by recursively calling
92   // generateInstSeq. In each recursion, first the lowest 12 bits are removed
93   // from the constant and the optimal shift amount, which can be greater than
94   // 12 bits if the constant is sparse, is determined. Then, the shifted
95   // remaining constant is processed recursively and gets emitted as soon as it
96   // fits into 32 bits. The emission of the shifts and additions is subsequently
97   // performed when the recursion returns.
98 
99   int64_t Lo12 = SignExtend64<12>(Val);
100   int64_t Hi52 = ((uint64_t)Val + 0x800ull) >> 12;
101   int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
102   Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
103 
104   // If the remaining bits don't fit in 12 bits, we might be able to reduce the
105   // shift amount in order to use LUI which will zero the lower 12 bits.
106   bool Unsigned = false;
107   if (ShiftAmount > 12 && !isInt<12>(Hi52)) {
108     if (isInt<32>((uint64_t)Hi52 << 12)) {
109       // Reduce the shift amount and add zeros to the LSBs so it will match LUI.
110       ShiftAmount -= 12;
111       Hi52 = (uint64_t)Hi52 << 12;
112     } else if (isUInt<32>((uint64_t)Hi52 << 12) &&
113                ActiveFeatures[RISCV::FeatureStdExtZba]) {
114       // Reduce the shift amount and add zeros to the LSBs so it will match
115       // LUI, then shift left with SLLI.UW to clear the upper 32 set bits.
116       ShiftAmount -= 12;
117       Hi52 = ((uint64_t)Hi52 << 12) | (0xffffffffull << 32);
118       Unsigned = true;
119     }
120   }
121 
122   // Try to use SLLI_UW for Hi52 when it is uint32 but not int32.
123   if (isUInt<32>((uint64_t)Hi52) && !isInt<32>((uint64_t)Hi52) &&
124       ActiveFeatures[RISCV::FeatureStdExtZba]) {
125     // Use LUI+ADDI or LUI to compose, then clear the upper 32 bits with
126     // SLLI_UW.
127     Hi52 = ((uint64_t)Hi52) | (0xffffffffull << 32);
128     Unsigned = true;
129   }
130 
131   generateInstSeqImpl(Hi52, ActiveFeatures, Res);
132 
133   if (Unsigned)
134     Res.push_back(RISCVMatInt::Inst(RISCV::SLLI_UW, ShiftAmount));
135   else
136     Res.push_back(RISCVMatInt::Inst(RISCV::SLLI, ShiftAmount));
137   if (Lo12)
138     Res.push_back(RISCVMatInt::Inst(RISCV::ADDI, Lo12));
139 }
140 
141 static unsigned extractRotateInfo(int64_t Val) {
142   // for case: 0b111..1..xxxxxx1..1..
143   unsigned LeadingOnes = countLeadingOnes((uint64_t)Val);
144   unsigned TrailingOnes = countTrailingOnes((uint64_t)Val);
145   if (TrailingOnes > 0 && TrailingOnes < 64 &&
146       (LeadingOnes + TrailingOnes) > (64 - 12))
147     return 64 - TrailingOnes;
148 
149   // for case: 0bxxx1..1..1...xxx
150   unsigned UpperTrailingOnes = countTrailingOnes(Hi_32(Val));
151   unsigned LowerLeadingOnes = countLeadingOnes(Lo_32(Val));
152   if (UpperTrailingOnes < 32 &&
153       (UpperTrailingOnes + LowerLeadingOnes) > (64 - 12))
154     return 32 - UpperTrailingOnes;
155 
156   return 0;
157 }
158 
159 namespace llvm {
160 namespace RISCVMatInt {
161 InstSeq generateInstSeq(int64_t Val, const FeatureBitset &ActiveFeatures) {
162   RISCVMatInt::InstSeq Res;
163   generateInstSeqImpl(Val, ActiveFeatures, Res);
164 
165   // If the constant is positive we might be able to generate a shifted constant
166   // with no leading zeros and use a final SRLI to restore them.
167   if (Val > 0 && Res.size() > 2) {
168     assert(ActiveFeatures[RISCV::Feature64Bit] &&
169            "Expected RV32 to only need 2 instructions");
170     unsigned LeadingZeros = countLeadingZeros((uint64_t)Val);
171     uint64_t ShiftedVal = (uint64_t)Val << LeadingZeros;
172     // Fill in the bits that will be shifted out with 1s. An example where this
173     // helps is trailing one masks with 32 or more ones. This will generate
174     // ADDI -1 and an SRLI.
175     ShiftedVal |= maskTrailingOnes<uint64_t>(LeadingZeros);
176 
177     RISCVMatInt::InstSeq TmpSeq;
178     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
179     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros));
180 
181     // Keep the new sequence if it is an improvement.
182     if (TmpSeq.size() < Res.size()) {
183       Res = TmpSeq;
184       // A 2 instruction sequence is the best we can do.
185       if (Res.size() <= 2)
186         return Res;
187     }
188 
189     // Some cases can benefit from filling the lower bits with zeros instead.
190     ShiftedVal &= maskTrailingZeros<uint64_t>(LeadingZeros);
191     TmpSeq.clear();
192     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
193     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros));
194 
195     // Keep the new sequence if it is an improvement.
196     if (TmpSeq.size() < Res.size()) {
197       Res = TmpSeq;
198       // A 2 instruction sequence is the best we can do.
199       if (Res.size() <= 2)
200         return Res;
201     }
202 
203     // If we have exactly 32 leading zeros and Zba, we can try using zext.w at
204     // the end of the sequence.
205     if (LeadingZeros == 32 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
206       // Try replacing upper bits with 1.
207       uint64_t LeadingOnesVal = Val | maskLeadingOnes<uint64_t>(LeadingZeros);
208       TmpSeq.clear();
209       generateInstSeqImpl(LeadingOnesVal, ActiveFeatures, TmpSeq);
210       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADD_UW, 0));
211 
212       // Keep the new sequence if it is an improvement.
213       if (TmpSeq.size() < Res.size()) {
214         Res = TmpSeq;
215         // A 2 instruction sequence is the best we can do.
216         if (Res.size() <= 2)
217           return Res;
218       }
219     }
220   }
221 
222   // Perform optimization with BCLRI/BSETI in the Zbs extension.
223   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) {
224     assert(ActiveFeatures[RISCV::Feature64Bit] &&
225            "Expected RV32 to only need 2 instructions");
226 
227     // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000,
228     //    call generateInstSeqImpl with Val|0x80000000 (which is expected be
229     //    an int32), then emit (BCLRI r, 31).
230     // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl
231     //    with Val&~0x80000000 (which is expected to be an int32), then
232     //    emit (BSETI r, 31).
233     int64_t NewVal;
234     unsigned Opc;
235     if (Val < 0) {
236       Opc = RISCV::BCLRI;
237       NewVal = Val | 0x80000000ll;
238     } else {
239       Opc = RISCV::BSETI;
240       NewVal = Val & ~0x80000000ll;
241     }
242     if (isInt<32>(NewVal)) {
243       RISCVMatInt::InstSeq TmpSeq;
244       generateInstSeqImpl(NewVal, ActiveFeatures, TmpSeq);
245       TmpSeq.push_back(RISCVMatInt::Inst(Opc, 31));
246       if (TmpSeq.size() < Res.size())
247         Res = TmpSeq;
248     }
249 
250     // Try to use BCLRI for upper 32 bits if the original lower 32 bits are
251     // negative int32, or use BSETI for upper 32 bits if the original lower
252     // 32 bits are positive int32.
253     int32_t Lo = Val;
254     uint32_t Hi = Val >> 32;
255     Opc = 0;
256     RISCVMatInt::InstSeq TmpSeq;
257     generateInstSeqImpl(Lo, ActiveFeatures, TmpSeq);
258     // Check if it is profitable to use BCLRI/BSETI.
259     if (Lo > 0 && TmpSeq.size() + countPopulation(Hi) < Res.size()) {
260       Opc = RISCV::BSETI;
261     } else if (Lo < 0 && TmpSeq.size() + countPopulation(~Hi) < Res.size()) {
262       Opc = RISCV::BCLRI;
263       Hi = ~Hi;
264     }
265     // Search for each bit and build corresponding BCLRI/BSETI.
266     if (Opc > 0) {
267       while (Hi != 0) {
268         unsigned Bit = countTrailingZeros(Hi);
269         TmpSeq.push_back(RISCVMatInt::Inst(Opc, Bit + 32));
270         Hi &= ~(1 << Bit);
271       }
272       if (TmpSeq.size() < Res.size())
273         Res = TmpSeq;
274     }
275   }
276 
277   // Perform optimization with SH*ADD in the Zba extension.
278   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
279     assert(ActiveFeatures[RISCV::Feature64Bit] &&
280            "Expected RV32 to only need 2 instructions");
281     int64_t Div = 0;
282     unsigned Opc = 0;
283     RISCVMatInt::InstSeq TmpSeq;
284     // Select the opcode and divisor.
285     if ((Val % 3) == 0 && isInt<32>(Val / 3)) {
286       Div = 3;
287       Opc = RISCV::SH1ADD;
288     } else if ((Val % 5) == 0 && isInt<32>(Val / 5)) {
289       Div = 5;
290       Opc = RISCV::SH2ADD;
291     } else if ((Val % 9) == 0 && isInt<32>(Val / 9)) {
292       Div = 9;
293       Opc = RISCV::SH3ADD;
294     }
295     // Build the new instruction sequence.
296     if (Div > 0) {
297       generateInstSeqImpl(Val / Div, ActiveFeatures, TmpSeq);
298       TmpSeq.push_back(RISCVMatInt::Inst(Opc, 0));
299       if (TmpSeq.size() < Res.size())
300         Res = TmpSeq;
301     } else {
302       // Try to use LUI+SH*ADD+ADDI.
303       int64_t Hi52 = ((uint64_t)Val + 0x800ull) & ~0xfffull;
304       int64_t Lo12 = SignExtend64<12>(Val);
305       Div = 0;
306       if (isInt<32>(Hi52 / 3) && (Hi52 % 3) == 0) {
307         Div = 3;
308         Opc = RISCV::SH1ADD;
309       } else if (isInt<32>(Hi52 / 5) && (Hi52 % 5) == 0) {
310         Div = 5;
311         Opc = RISCV::SH2ADD;
312       } else if (isInt<32>(Hi52 / 9) && (Hi52 % 9) == 0) {
313         Div = 9;
314         Opc = RISCV::SH3ADD;
315       }
316       // Build the new instruction sequence.
317       if (Div > 0) {
318         // For Val that has zero Lo12 (implies Val equals to Hi52) should has
319         // already been processed to LUI+SH*ADD by previous optimization.
320         assert(Lo12 != 0 &&
321                "unexpected instruction sequence for immediate materialisation");
322         assert(TmpSeq.empty() && "Expected empty TmpSeq");
323         generateInstSeqImpl(Hi52 / Div, ActiveFeatures, TmpSeq);
324         TmpSeq.push_back(RISCVMatInt::Inst(Opc, 0));
325         TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDI, Lo12));
326         if (TmpSeq.size() < Res.size())
327           Res = TmpSeq;
328       }
329     }
330   }
331 
332   // Perform optimization with rori in the Zbb extension.
333   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbb]) {
334     if (unsigned Rotate = extractRotateInfo(Val)) {
335       RISCVMatInt::InstSeq TmpSeq;
336       uint64_t NegImm12 =
337           ((uint64_t)Val >> (64 - Rotate)) | ((uint64_t)Val << Rotate);
338       assert(isInt<12>(NegImm12));
339       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDI, NegImm12));
340       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::RORI, Rotate));
341       Res = TmpSeq;
342     }
343   }
344   return Res;
345 }
346 
347 int getIntMatCost(const APInt &Val, unsigned Size,
348                   const FeatureBitset &ActiveFeatures, bool CompressionCost) {
349   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
350   bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC];
351   int PlatRegSize = IsRV64 ? 64 : 32;
352 
353   // Split the constant into platform register sized chunks, and calculate cost
354   // of each chunk.
355   int Cost = 0;
356   for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) {
357     APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize);
358     InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures);
359     Cost += getInstSeqCost(MatSeq, HasRVC);
360   }
361   return std::max(1, Cost);
362 }
363 } // namespace RISCVMatInt
364 } // namespace llvm
365