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     bool Compressed;
22     switch (Instr.Opc) {
23     default: llvm_unreachable("Unexpected opcode");
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     case RISCV::ADDUW:
34       Compressed = false;
35       break;
36     }
37     // Two RVC instructions take the same space as one RVI instruction, but
38     // can take longer to execute than the single RVI instruction. Thus, we
39     // consider that two RVC instruction are slightly more costly than one
40     // RVI instruction. For longer sequences of RVC instructions the space
41     // savings can be worth it, though. The costs below try to model that.
42     if (!Compressed)
43       Cost += 100; // Baseline cost of one RVI instruction: 100%.
44     else
45       Cost += 70; // 70% cost of baseline.
46   }
47   return Cost;
48 }
49 
50 // Recursively generate a sequence for materializing an integer.
51 static void generateInstSeqImpl(int64_t Val,
52                                 const FeatureBitset &ActiveFeatures,
53                                 RISCVMatInt::InstSeq &Res) {
54   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
55 
56   if (isInt<32>(Val)) {
57     // Depending on the active bits in the immediate Value v, the following
58     // instruction sequences are emitted:
59     //
60     // v == 0                        : ADDI
61     // v[0,12) != 0 && v[12,32) == 0 : ADDI
62     // v[0,12) == 0 && v[12,32) != 0 : LUI
63     // v[0,32) != 0                  : LUI+ADDI(W)
64     int64_t Hi20 = ((Val + 0x800) >> 12) & 0xFFFFF;
65     int64_t Lo12 = SignExtend64<12>(Val);
66 
67     if (Hi20)
68       Res.push_back(RISCVMatInt::Inst(RISCV::LUI, Hi20));
69 
70     if (Lo12 || Hi20 == 0) {
71       unsigned AddiOpc = (IsRV64 && Hi20) ? RISCV::ADDIW : RISCV::ADDI;
72       Res.push_back(RISCVMatInt::Inst(AddiOpc, Lo12));
73     }
74     return;
75   }
76 
77   assert(IsRV64 && "Can't emit >32-bit imm for non-RV64 target");
78 
79   // In the worst case, for a full 64-bit constant, a sequence of 8 instructions
80   // (i.e., LUI+ADDIW+SLLI+ADDI+SLLI+ADDI+SLLI+ADDI) has to be emitted. Note
81   // that the first two instructions (LUI+ADDIW) can contribute up to 32 bits
82   // while the following ADDI instructions contribute up to 12 bits each.
83   //
84   // On the first glance, implementing this seems to be possible by simply
85   // emitting the most significant 32 bits (LUI+ADDIW) followed by as many left
86   // shift (SLLI) and immediate additions (ADDI) as needed. However, due to the
87   // fact that ADDI performs a sign extended addition, doing it like that would
88   // only be possible when at most 11 bits of the ADDI instructions are used.
89   // Using all 12 bits of the ADDI instructions, like done by GAS, actually
90   // requires that the constant is processed starting with the least significant
91   // bit.
92   //
93   // In the following, constants are processed from LSB to MSB but instruction
94   // emission is performed from MSB to LSB by recursively calling
95   // generateInstSeq. In each recursion, first the lowest 12 bits are removed
96   // from the constant and the optimal shift amount, which can be greater than
97   // 12 bits if the constant is sparse, is determined. Then, the shifted
98   // remaining constant is processed recursively and gets emitted as soon as it
99   // fits into 32 bits. The emission of the shifts and additions is subsequently
100   // performed when the recursion returns.
101 
102   int64_t Lo12 = SignExtend64<12>(Val);
103   int64_t Hi52 = ((uint64_t)Val + 0x800ull) >> 12;
104   int ShiftAmount = 12 + findFirstSet((uint64_t)Hi52);
105   Hi52 = SignExtend64(Hi52 >> (ShiftAmount - 12), 64 - ShiftAmount);
106 
107   // If the remaining bits don't fit in 12 bits, we might be able to reduce the
108   // shift amount in order to use LUI which will zero the lower 12 bits.
109   bool Unsigned = false;
110   if (ShiftAmount > 12 && !isInt<12>(Hi52)) {
111     if (isInt<32>((uint64_t)Hi52 << 12)) {
112       // Reduce the shift amount and add zeros to the LSBs so it will match LUI.
113       ShiftAmount -= 12;
114       Hi52 = (uint64_t)Hi52 << 12;
115     } else if (isUInt<32>((uint64_t)Hi52 << 12) &&
116                ActiveFeatures[RISCV::FeatureStdExtZba]) {
117       // Reduce the shift amount and add zeros to the LSBs so it will match
118       // LUI, then shift left with SLLI.UW to clear the upper 32 set bits.
119       ShiftAmount -= 12;
120       Hi52 = ((uint64_t)Hi52 << 12) | (0xffffffffull << 32);
121       Unsigned = true;
122     }
123   }
124 
125   generateInstSeqImpl(Hi52, ActiveFeatures, Res);
126 
127   if (Unsigned)
128     Res.push_back(RISCVMatInt::Inst(RISCV::SLLIUW, ShiftAmount));
129   else
130     Res.push_back(RISCVMatInt::Inst(RISCV::SLLI, ShiftAmount));
131   if (Lo12)
132     Res.push_back(RISCVMatInt::Inst(RISCV::ADDI, Lo12));
133 }
134 
135 namespace llvm {
136 namespace RISCVMatInt {
137 InstSeq generateInstSeq(int64_t Val, const FeatureBitset &ActiveFeatures) {
138   RISCVMatInt::InstSeq Res;
139   generateInstSeqImpl(Val, ActiveFeatures, Res);
140 
141   // If the constant is positive we might be able to generate a shifted constant
142   // with no leading zeros and use a final SRLI to restore them.
143   if (Val > 0 && Res.size() > 2) {
144     assert(ActiveFeatures[RISCV::Feature64Bit] &&
145            "Expected RV32 to only need 2 instructions");
146     unsigned LeadingZeros = countLeadingZeros((uint64_t)Val);
147     uint64_t ShiftedVal = (uint64_t)Val << LeadingZeros;
148     // Fill in the bits that will be shifted out with 1s. An example where this
149     // helps is trailing one masks with 32 or more ones. This will generate
150     // ADDI -1 and an SRLI.
151     ShiftedVal |= maskTrailingOnes<uint64_t>(LeadingZeros);
152 
153     RISCVMatInt::InstSeq TmpSeq;
154     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
155     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros));
156 
157     // Keep the new sequence if it is an improvement.
158     if (TmpSeq.size() < Res.size()) {
159       Res = TmpSeq;
160       // A 2 instruction sequence is the best we can do.
161       if (Res.size() <= 2)
162         return Res;
163     }
164 
165     // Some cases can benefit from filling the lower bits with zeros instead.
166     ShiftedVal &= maskTrailingZeros<uint64_t>(LeadingZeros);
167     TmpSeq.clear();
168     generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq);
169     TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros));
170 
171     // Keep the new sequence if it is an improvement.
172     if (TmpSeq.size() < Res.size()) {
173       Res = TmpSeq;
174       // A 2 instruction sequence is the best we can do.
175       if (Res.size() <= 2)
176         return Res;
177     }
178 
179     // If we have exactly 32 leading zeros and Zba, we can try using zext.w at
180     // the end of the sequence.
181     if (LeadingZeros == 32 && ActiveFeatures[RISCV::FeatureStdExtZba]) {
182       // Try replacing upper bits with 1.
183       uint64_t LeadingOnesVal = Val | maskLeadingOnes<uint64_t>(LeadingZeros);
184       TmpSeq.clear();
185       generateInstSeqImpl(LeadingOnesVal, ActiveFeatures, TmpSeq);
186       TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDUW, 0));
187 
188       // Keep the new sequence if it is an improvement.
189       if (TmpSeq.size() < Res.size()) {
190         Res = TmpSeq;
191         // A 2 instruction sequence is the best we can do.
192         if (Res.size() <= 2)
193           return Res;
194       }
195     }
196   }
197 
198   // Perform optimization with BCLRI/BSETI in the Zbs extension.
199   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) {
200     assert(ActiveFeatures[RISCV::Feature64Bit] &&
201            "Expected RV32 to only need 2 instructions");
202 
203     // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000,
204     //    call generateInstSeqImpl with Val|0x80000000 (which is expected be
205     //    an int32), then emit (BCLRI r, 31).
206     // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl
207     //    with Val&~0x80000000 (which is expected to be an int32), then
208     //    emit (BSETI r, 31).
209     int64_t NewVal;
210     unsigned Opc;
211     if (Val < 0) {
212       Opc = RISCV::BCLRI;
213       NewVal = Val | 0x80000000ll;
214     } else {
215       Opc = RISCV::BSETI;
216       NewVal = Val & ~0x80000000ll;
217     }
218     if (isInt<32>(NewVal)) {
219       RISCVMatInt::InstSeq TmpSeq;
220       generateInstSeqImpl(NewVal, ActiveFeatures, TmpSeq);
221       TmpSeq.push_back(RISCVMatInt::Inst(Opc, 31));
222       if (TmpSeq.size() < Res.size())
223         Res = TmpSeq;
224     }
225 
226     // Try to use BCLRI for upper 32 bits if the original lower 32 bits are
227     // negative int32, or use BSETI for upper 32 bits if the original lower
228     // 32 bits are positive int32.
229     int32_t Lo = Val;
230     uint32_t Hi = Val >> 32;
231     Opc = 0;
232     RISCVMatInt::InstSeq TmpSeq;
233     generateInstSeqImpl(Lo, ActiveFeatures, TmpSeq);
234     // Check if it is profitable to use BCLRI/BSETI.
235     if (Lo > 0 && TmpSeq.size() + countPopulation(Hi) < Res.size()) {
236       Opc = RISCV::BSETI;
237     } else if (Lo < 0 && TmpSeq.size() + countPopulation(~Hi) < Res.size()) {
238       Opc = RISCV::BCLRI;
239       Hi = ~Hi;
240     }
241     // Search for each bit and build corresponding BCLRI/BSETI.
242     if (Opc > 0) {
243       while (Hi != 0) {
244         unsigned Bit = countTrailingZeros(Hi);
245         TmpSeq.push_back(RISCVMatInt::Inst(Opc, Bit + 32));
246         Hi &= ~(1 << Bit);
247       }
248       if (TmpSeq.size() < Res.size())
249         Res = TmpSeq;
250     }
251   }
252 
253   return Res;
254 }
255 
256 int getIntMatCost(const APInt &Val, unsigned Size,
257                   const FeatureBitset &ActiveFeatures,
258                   bool CompressionCost) {
259   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
260   bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC];
261   int PlatRegSize = IsRV64 ? 64 : 32;
262 
263   // Split the constant into platform register sized chunks, and calculate cost
264   // of each chunk.
265   int Cost = 0;
266   for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) {
267     APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize);
268     InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures);
269     Cost += getInstSeqCost(MatSeq, HasRVC);
270   }
271   return std::max(1, Cost);
272 }
273 } // namespace RISCVMatInt
274 } // namespace llvm
275