This patch implements the TargetInstrInfo::verifyInstruction hook for RISC-V. Currently the hook verifies the machine instruction's immediate operands, to check if the immediates are within the expected bounds. Without the hook invalid immediates are not detected except when doing assembly parsing, so they are silently emitted (including being truncated when emitting object code).
The bounds information is specified in tablegen by using the OperandType definition, which sets the MCOperandInfo's OperandType field. Several RISC-V-specific immediate operand types were created, which extend the MCInstrDesc's OperandType enum.
To have the hook called with llc pass it the -verify-machineinstrs option. For Clang add the cmake build config -DLLVM_ENABLE_EXPENSIVE_CHECKS=True, or temporarily patch TargetPassConfig::addVerifyPass.
Review concerns:
- The patch adds immediate operand type checks that cover at least the base ISA. There are several other operand types for the C extension and one type for the F/D extensions that were left out of this initial patch because they introduced further design concerns that I felt were best evaluated separately.
- Invalid register classes (e.g. passing a GPR register where a GPRC is expected) are already caught, so were not included.
- This design makes the more abstract MachineInstr verification depend on MC layer definitions, which arguably is not the cleanest design, but is in line with how things are done in other parts of the target and LLVM in general.
- There is some duplication of logic already present in the MCOperandPredicates. Since the MachineInstr and MCInstr notions of immediates are fundamentally different, this is currently necessary.
Combining foreach and an index like this is a bit ugly due to having the counter increment at the end (and it's brittle if someone introduces a continue into the loop for whatever reason). AMDGPU takes the alternate approach of for (int i = 0, e = Desc.getNumOperands(); i != e; ++i); then, the only change you need to the body is unsigned OpType = Desc.OpInfo[i].OperandType. Alternatively you can keep track of the start, current and end iterators, calculating the index by subtracting the current from the start, or just expand out the foreach and include i in the for loop itself.