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 the following optimization with the Zbs extension.
199   // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000,
200   //    call generateInstSeqImpl with Val|0x80000000 (which is expected be
201   //    an int32), then emit (BCLRI r, 31).
202   // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl
203   //    with Val&~0x80000000 (which is expected to be an int32), then
204   //    emit (BSETI r, 31).
205   if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) {
206     assert(ActiveFeatures[RISCV::Feature64Bit] &&
207            "Expected RV32 to only need 2 instructions");
208     int64_t NewVal;
209     unsigned Opc;
210     if (Val < 0) {
211       Opc = RISCV::BCLRI;
212       NewVal = Val | 0x80000000ll;
213     } else {
214       Opc = RISCV::BSETI;
215       NewVal = Val & ~0x80000000ll;
216     }
217     if (isInt<32>(NewVal)) {
218       RISCVMatInt::InstSeq TmpSeq;
219       generateInstSeqImpl(NewVal, ActiveFeatures, TmpSeq);
220       TmpSeq.push_back(RISCVMatInt::Inst(Opc, 31));
221       if (TmpSeq.size() < Res.size())
222         Res = TmpSeq;
223     }
224   }
225 
226   return Res;
227 }
228 
229 int getIntMatCost(const APInt &Val, unsigned Size,
230                   const FeatureBitset &ActiveFeatures,
231                   bool CompressionCost) {
232   bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit];
233   bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC];
234   int PlatRegSize = IsRV64 ? 64 : 32;
235 
236   // Split the constant into platform register sized chunks, and calculate cost
237   // of each chunk.
238   int Cost = 0;
239   for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) {
240     APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize);
241     InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures);
242     Cost += getInstSeqCost(MatSeq, HasRVC);
243   }
244   return std::max(1, Cost);
245 }
246 } // namespace RISCVMatInt
247 } // namespace llvm
248