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 there are trailing zeros, try generating a sign extended constant with 166 // no trailing zeros and use a final SLLI to restore them. 167 if ((Val & 1) == 0 && Res.size() > 2) { 168 unsigned TrailingZeros = countTrailingZeros((uint64_t)Val); 169 int64_t ShiftedVal = Val >> TrailingZeros; 170 RISCVMatInt::InstSeq TmpSeq; 171 generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq); 172 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SLLI, TrailingZeros)); 173 174 // Keep the new sequence if it is an improvement. 175 if (TmpSeq.size() < Res.size()) { 176 Res = TmpSeq; 177 // A 2 instruction sequence is the best we can do. 178 if (Res.size() <= 2) 179 return Res; 180 } 181 } 182 183 // If the constant is positive we might be able to generate a shifted constant 184 // with no leading zeros and use a final SRLI to restore them. 185 if (Val > 0 && Res.size() > 2) { 186 assert(ActiveFeatures[RISCV::Feature64Bit] && 187 "Expected RV32 to only need 2 instructions"); 188 unsigned LeadingZeros = countLeadingZeros((uint64_t)Val); 189 uint64_t ShiftedVal = (uint64_t)Val << LeadingZeros; 190 // Fill in the bits that will be shifted out with 1s. An example where this 191 // helps is trailing one masks with 32 or more ones. This will generate 192 // ADDI -1 and an SRLI. 193 ShiftedVal |= maskTrailingOnes<uint64_t>(LeadingZeros); 194 195 RISCVMatInt::InstSeq TmpSeq; 196 generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq); 197 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros)); 198 199 // Keep the new sequence if it is an improvement. 200 if (TmpSeq.size() < Res.size()) { 201 Res = TmpSeq; 202 // A 2 instruction sequence is the best we can do. 203 if (Res.size() <= 2) 204 return Res; 205 } 206 207 // Some cases can benefit from filling the lower bits with zeros instead. 208 ShiftedVal &= maskTrailingZeros<uint64_t>(LeadingZeros); 209 TmpSeq.clear(); 210 generateInstSeqImpl(ShiftedVal, ActiveFeatures, TmpSeq); 211 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::SRLI, LeadingZeros)); 212 213 // Keep the new sequence if it is an improvement. 214 if (TmpSeq.size() < Res.size()) { 215 Res = TmpSeq; 216 // A 2 instruction sequence is the best we can do. 217 if (Res.size() <= 2) 218 return Res; 219 } 220 221 // If we have exactly 32 leading zeros and Zba, we can try using zext.w at 222 // the end of the sequence. 223 if (LeadingZeros == 32 && ActiveFeatures[RISCV::FeatureStdExtZba]) { 224 // Try replacing upper bits with 1. 225 uint64_t LeadingOnesVal = Val | maskLeadingOnes<uint64_t>(LeadingZeros); 226 TmpSeq.clear(); 227 generateInstSeqImpl(LeadingOnesVal, ActiveFeatures, TmpSeq); 228 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADD_UW, 0)); 229 230 // Keep the new sequence if it is an improvement. 231 if (TmpSeq.size() < Res.size()) { 232 Res = TmpSeq; 233 // A 2 instruction sequence is the best we can do. 234 if (Res.size() <= 2) 235 return Res; 236 } 237 } 238 } 239 240 // Perform optimization with BCLRI/BSETI in the Zbs extension. 241 if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbs]) { 242 assert(ActiveFeatures[RISCV::Feature64Bit] && 243 "Expected RV32 to only need 2 instructions"); 244 245 // 1. For values in range 0xffffffff 7fffffff ~ 0xffffffff 00000000, 246 // call generateInstSeqImpl with Val|0x80000000 (which is expected be 247 // an int32), then emit (BCLRI r, 31). 248 // 2. For values in range 0x80000000 ~ 0xffffffff, call generateInstSeqImpl 249 // with Val&~0x80000000 (which is expected to be an int32), then 250 // emit (BSETI r, 31). 251 int64_t NewVal; 252 unsigned Opc; 253 if (Val < 0) { 254 Opc = RISCV::BCLRI; 255 NewVal = Val | 0x80000000ll; 256 } else { 257 Opc = RISCV::BSETI; 258 NewVal = Val & ~0x80000000ll; 259 } 260 if (isInt<32>(NewVal)) { 261 RISCVMatInt::InstSeq TmpSeq; 262 generateInstSeqImpl(NewVal, ActiveFeatures, TmpSeq); 263 TmpSeq.push_back(RISCVMatInt::Inst(Opc, 31)); 264 if (TmpSeq.size() < Res.size()) 265 Res = TmpSeq; 266 } 267 268 // Try to use BCLRI for upper 32 bits if the original lower 32 bits are 269 // negative int32, or use BSETI for upper 32 bits if the original lower 270 // 32 bits are positive int32. 271 int32_t Lo = Val; 272 uint32_t Hi = Val >> 32; 273 Opc = 0; 274 RISCVMatInt::InstSeq TmpSeq; 275 generateInstSeqImpl(Lo, ActiveFeatures, TmpSeq); 276 // Check if it is profitable to use BCLRI/BSETI. 277 if (Lo > 0 && TmpSeq.size() + countPopulation(Hi) < Res.size()) { 278 Opc = RISCV::BSETI; 279 } else if (Lo < 0 && TmpSeq.size() + countPopulation(~Hi) < Res.size()) { 280 Opc = RISCV::BCLRI; 281 Hi = ~Hi; 282 } 283 // Search for each bit and build corresponding BCLRI/BSETI. 284 if (Opc > 0) { 285 while (Hi != 0) { 286 unsigned Bit = countTrailingZeros(Hi); 287 TmpSeq.push_back(RISCVMatInt::Inst(Opc, Bit + 32)); 288 Hi &= ~(1 << Bit); 289 } 290 if (TmpSeq.size() < Res.size()) 291 Res = TmpSeq; 292 } 293 } 294 295 // Perform optimization with SH*ADD in the Zba extension. 296 if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZba]) { 297 assert(ActiveFeatures[RISCV::Feature64Bit] && 298 "Expected RV32 to only need 2 instructions"); 299 int64_t Div = 0; 300 unsigned Opc = 0; 301 RISCVMatInt::InstSeq TmpSeq; 302 // Select the opcode and divisor. 303 if ((Val % 3) == 0 && isInt<32>(Val / 3)) { 304 Div = 3; 305 Opc = RISCV::SH1ADD; 306 } else if ((Val % 5) == 0 && isInt<32>(Val / 5)) { 307 Div = 5; 308 Opc = RISCV::SH2ADD; 309 } else if ((Val % 9) == 0 && isInt<32>(Val / 9)) { 310 Div = 9; 311 Opc = RISCV::SH3ADD; 312 } 313 // Build the new instruction sequence. 314 if (Div > 0) { 315 generateInstSeqImpl(Val / Div, ActiveFeatures, TmpSeq); 316 TmpSeq.push_back(RISCVMatInt::Inst(Opc, 0)); 317 if (TmpSeq.size() < Res.size()) 318 Res = TmpSeq; 319 } else { 320 // Try to use LUI+SH*ADD+ADDI. 321 int64_t Hi52 = ((uint64_t)Val + 0x800ull) & ~0xfffull; 322 int64_t Lo12 = SignExtend64<12>(Val); 323 Div = 0; 324 if (isInt<32>(Hi52 / 3) && (Hi52 % 3) == 0) { 325 Div = 3; 326 Opc = RISCV::SH1ADD; 327 } else if (isInt<32>(Hi52 / 5) && (Hi52 % 5) == 0) { 328 Div = 5; 329 Opc = RISCV::SH2ADD; 330 } else if (isInt<32>(Hi52 / 9) && (Hi52 % 9) == 0) { 331 Div = 9; 332 Opc = RISCV::SH3ADD; 333 } 334 // Build the new instruction sequence. 335 if (Div > 0) { 336 // For Val that has zero Lo12 (implies Val equals to Hi52) should has 337 // already been processed to LUI+SH*ADD by previous optimization. 338 assert(Lo12 != 0 && 339 "unexpected instruction sequence for immediate materialisation"); 340 assert(TmpSeq.empty() && "Expected empty TmpSeq"); 341 generateInstSeqImpl(Hi52 / Div, ActiveFeatures, TmpSeq); 342 TmpSeq.push_back(RISCVMatInt::Inst(Opc, 0)); 343 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDI, Lo12)); 344 if (TmpSeq.size() < Res.size()) 345 Res = TmpSeq; 346 } 347 } 348 } 349 350 // Perform optimization with rori in the Zbb extension. 351 if (Res.size() > 2 && ActiveFeatures[RISCV::FeatureStdExtZbb]) { 352 if (unsigned Rotate = extractRotateInfo(Val)) { 353 RISCVMatInt::InstSeq TmpSeq; 354 uint64_t NegImm12 = 355 ((uint64_t)Val >> (64 - Rotate)) | ((uint64_t)Val << Rotate); 356 assert(isInt<12>(NegImm12)); 357 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::ADDI, NegImm12)); 358 TmpSeq.push_back(RISCVMatInt::Inst(RISCV::RORI, Rotate)); 359 Res = TmpSeq; 360 } 361 } 362 return Res; 363 } 364 365 int getIntMatCost(const APInt &Val, unsigned Size, 366 const FeatureBitset &ActiveFeatures, bool CompressionCost) { 367 bool IsRV64 = ActiveFeatures[RISCV::Feature64Bit]; 368 bool HasRVC = CompressionCost && ActiveFeatures[RISCV::FeatureStdExtC]; 369 int PlatRegSize = IsRV64 ? 64 : 32; 370 371 // Split the constant into platform register sized chunks, and calculate cost 372 // of each chunk. 373 int Cost = 0; 374 for (unsigned ShiftVal = 0; ShiftVal < Size; ShiftVal += PlatRegSize) { 375 APInt Chunk = Val.ashr(ShiftVal).sextOrTrunc(PlatRegSize); 376 InstSeq MatSeq = generateInstSeq(Chunk.getSExtValue(), ActiveFeatures); 377 Cost += getInstSeqCost(MatSeq, HasRVC); 378 } 379 return std::max(1, Cost); 380 } 381 } // namespace RISCVMatInt 382 } // namespace llvm 383