This is an archive of the discontinued LLVM Phabricator instance.

[CGP][RISCV] Teach CodeGenPrepare::optimizeSwitchInst to honor isSExtCheaperThanZExt.
ClosedPublic

Authored by craig.topper on Jun 20 2021, 7:51 PM.

Details

Summary

This optimization pre-promotes the input and constants for a
switch instruction to a legal type so that all the generated compares
share the same extend. Since RISCV prefers sext for i32 to i64
extends, we should honor that to use sext.w instead of a pair
of shifts.

Diff Detail

Event Timeline

craig.topper created this revision.Jun 20 2021, 7:51 PM
craig.topper requested review of this revision.Jun 20 2021, 7:51 PM
Herald added a project: Restricted Project. · View Herald TranscriptJun 20 2021, 7:51 PM
Herald added a subscriber: MaskRay. · View Herald Transcript

Seems reasonable to me but I'll let others take a look

jrtc27 added inline comments.Jun 23 2021, 11:40 AM
llvm/lib/CodeGen/CodeGenPrepare.cpp
7018–7020

Do we not want to avoid this in the case this is a function argument that is already being zero-extended? i.e. something like:

Instruction::CastOps ExtType = Instruction::CastOpsEnd;
if (auto *Arg = dyn_cast<Argument>(Cond)) {
  if (Arg->hasSExtAttr())
    ExtType = Instruction::SExt;
  else if (Arg->hasZExtAttr())
    ExtType = Instruction::ZExt;
}
if (ExtType == Instruction::CastOpsEnd) {
  if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
    ExtType = Instruction::SExt;
  else
    ExtType = Instruction::ZExt;
}

(slightly abusing CastOpsEnd as being one past the last valid op, and thus a sentinel, though you could write it in other ways too if you wanted)

jrtc27 added inline comments.Jun 23 2021, 11:43 AM
llvm/lib/CodeGen/CodeGenPrepare.cpp
7018–7020

Or maybe the fact that sext is cheaper means the saving for each case's extending to match outweighs the cost of having to also extend the argument?

craig.topper added inline comments.Jun 23 2021, 11:58 AM
llvm/lib/CodeGen/CodeGenPrepare.cpp
7018–7020

It's a non-issue for RISCV since I don't think we ever create i32 zext arguments, but it would be more consistent. Could probably just do the isSExtCheaperThanZExt first and then check if it is an Argument after.

jrtc27 added inline comments.Jun 23 2021, 12:00 PM
llvm/lib/CodeGen/CodeGenPrepare.cpp
7018–7020

True, only i16 and i8, and those aren't so cheap to sext. Your suggestion is indeed the cleaner way to express the same thing, not sure how I missed that...

Honor zext function attributes over a preference for sext.

jrtc27 accepted this revision.Jun 23 2021, 12:44 PM
This revision is now accepted and ready to land.Jun 23 2021, 12:44 PM
This revision was landed with ongoing or failed builds.Jun 23 2021, 3:43 PM
This revision was automatically updated to reflect the committed changes.