[Mips] Simplify loadImmediate (NFC)
authorKazu Hirata <kazu@google.com>
Thu, 26 Jan 2023 04:54:43 +0000 (20:54 -0800)
committerKazu Hirata <kazu@google.com>
Thu, 26 Jan 2023 04:54:43 +0000 (20:54 -0800)
loadImmediate computes ShiftAmount in an unnecessarily complicated
manner.  We just need to know the minimum right shift amount to bring
the immediate down to an unsigned 16-bit value, so

  unsigned ShiftAmount = llvm::bit_width((uint64_t)ImmValue) - 16;

is sufficient.  In other words, the following are all equivalent:

  unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
  unsigned ShiftAmount = llvm::countr_zero(IV) - (15 - (63 - llvm::countl_zero(IV) - llvm::countr_zero(IV)));
  unsigned ShiftAmount = llvm::countr_zero(IV) - 15 + (63 - llvm::countl_zero(IV) - llvm::countr_zero(IV));
  unsigned ShiftAmount = 48 - llvm::countl_zero(IV);
  unsigned ShiftAmount = 64 - llvm::countl_zero(IV) - 16;
  unsigned ShiftAmount = llvm::bit_width(IV) - 16;

where IV represents (uint64)ImmValue.  I've also checked the
equivalence empirically up to 2u << 32.

llvm/lib/Target/Mips/AsmParser/MipsAsmParser.cpp

index bbfeec9..4f242fa 100644 (file)
@@ -2796,11 +2796,14 @@ bool MipsAsmParser::loadImmediate(int64_t ImmValue, unsigned DstReg,
       return true;
     }
 
+    // We've processed ImmValue satisfying isUInt<16> above, so ImmValue must be
+    // at least 17-bit wide here.
+    unsigned BitWidth = llvm::bit_width((uint64_t)ImmValue);
+    assert(BitWidth >= 17 && "ImmValue must be at least 17-bit wide");
+
     // Traditionally, these immediates are shifted as little as possible and as
     // such we align the most significant bit to bit 15 of our temporary.
-    unsigned FirstSet = findFirstSet((uint64_t)ImmValue);
-    unsigned LastSet = findLastSet((uint64_t)ImmValue);
-    unsigned ShiftAmount = FirstSet - (15 - (LastSet - FirstSet));
+    unsigned ShiftAmount = BitWidth - 16;
     uint16_t Bits = (ImmValue >> ShiftAmount) & 0xffff;
     TOut.emitRRI(Mips::ORi, TmpReg, ZeroReg, Bits, IDLoc, STI);
     TOut.emitRRI(Mips::DSLL, TmpReg, TmpReg, ShiftAmount, IDLoc, STI);