RFC 2867: instruction_set attribute

lang (target | target_feature | attributes)

Summary

This RFC proposes a new function attribute, #[instruction_set(set)] which allows you to declare the instruction set to be used when compiling the function. It also proposes two initial allowed values for the ARM arch (arm::a32 and arm::t32). Other allowed values could be added to the language later.

Motivation

Starting with ARMv4T, many ARM CPUs support two separate instruction sets. At the time they were called "ARM code" and "Thumb code", but with the development of AArch64, they're now called a32 and t32. Unlike with the x86_64 architecture, where the CPU can run both x86 and x86_64 code, but a single program still uses just one of the two instruction sets, on ARM you can have a single program that intersperses both a32 and t32 code. A particular form of branch instruction allows for the CPU to change between the two modes any time it branches, and so code can be designated as being either a32 or t32 on a per-function basis.

In LLVM, selecting that code should be a32 or t32 is done by either disabling (for a32) or enabling (for t32) the thumb-mode target feature. Previously, Rust was able to do this using the target_feature attribute because it was able to either add or subtract an LLVM target feature during a function. However, when RFC 2045 was accepted, its final form did not allow for the subtraction of target features. Its final form is primarily designed around always opting in to additional features, and it's no longer the correct tool for an "either A or B, but not both" situation like a32/t32 is.

Guide-level explanation

Some platforms support having more than one instruction set used within a single program. Generally, each one will be better for specific parts of a program. Every target has a default instruction set, based on the target triple. If you would like to set a specific function to use an alternate instruction set you use the #[instruction_set(set)] attribute.

Currently this is only of use on ARM family CPUs, which support both the arm::a32 and arm::t32 instruction sets. Targets starting with arm (eg: arm-linux-androideabi) default to arm::a32 and targets starting with thumb (eg: thumbv7neon-linux-androideabi) default to arm::t32.

// this uses the default instruction set for your target
fn add_one(x: i32) -> i32 {
    x + 1
}

// This will compile as `a32` code on both `arm` and thumb` targets
#[instruction_set(arm::a32)]
fn add_five(x: i32) -> i32 {
    x + 5
}

It is a compile time error to specify an instruction set that is not available on the target you're compiling for. Users wishing for their code to be as portable as possible should use cfg_attr to only enable the attribute when using the appropriate targets.

// This will fail to build if `arm::a32` isn't available
#[instruction_set(arm::a32)]
fn add_five(x: i32) -> i32 {
    x + 5
}

// This will build on all platforms, and apply the `instruction_set` attribute
// only on ARM targets.
#[cfg_attr(target_cpu="arm", instruction_set(arm::a32))]
fn add_six(x: i32) -> i32 {
    x + 6
}

As you can see it can get a little verbose, so projects which plan to use the instruction_set attribute might want to consider writing a proc-macro with a shorter name.

The specifics of when you should specify a non-default instruction set on a function are platform specific. Unless a piece of platform documentation has indicated a specific requirement, you do not need to think about adding this attribute at all.

Reference-level explanation

Every target is now considered to have one default instruction set (for functions that lack the instruction_set attribute), as well as possibly supporting specific additional instruction sets:

Where can this attribute be used:

What is a Compile Error:

Guarantees:

ARM

(this portion is a little extra technical, and very platform specific)

On ARM, there are two different instruction encodings. In textual/assembly form, Thumb assembly is written as a subset of ARM assembly, but the actual bit patterns produced when the text is assembled are entirely different. The CPU has a bit within the Program Status Register that indicates if the CPU should read 4 bytes at the Program Counter address and interpret them as an a32 opcode, or if it should read 2 bytes at the Program Counter address and interpret them as a t32 opcode. Because the amount of data read and the interpretation of the data is totally dissimilar, attempting to read one form of code while the CPU's flag is set for the other form of code is Undefined Behavior.

The outside world can tell what type of code a given function is based on the address of the function: a32 code has an even address, and t32 code has an odd address. The Program Counter ignores the actual value of the low bit, so t32 code is still considered to be "aligned to 2". When a branch-exchange (bx) or branch-link-exchange (blx) instruction is used then the target address's lowest bit is used to determine the CPU's new code state. When a branch (b) or branch-link (bl) instruction are used, the CPU's code state is not changed.

Thus, what we have to ensure with a32 and t32 is that the code generated for the marked function has the right encoding and also that the address is correctly even or odd:

Backend support:

Inlining:

Drawbacks

Rationale and alternatives

Rationale

Here's a simple but complete-enough program of how this would be used in practice. In this example, the program is for the Game Boy Advance (GBA). I have attempted to limit it to the essentials, so all the MMIO definitions, as well as the assembly runtime you'd need to boot and call main, are still omitted from the example.

// The GBA's BIOS provides some functionality available via software
// interrupt. We expose them to Rust in our assumed assembly "runtime".
extern "C" fn {
    /// Puts the CPU into a low-power state until a vblank interrupt,
    /// and then returns after the interrupt handler completes.
    VBlankInterWait(isize, isize);
}

// We assume that the MMIO stuff is imported from somewhere.
// The exact addresses and constant values aren't important.
mod all_the_gba_mmio_definitions;
use all_the_gba_mmio_definitions::*;

fn main() {
    // All of the `write_volatile` calls here refer to
    // the method of the `*mut T` type. Proper safe abstractions
    // for all of this would complicate the example, so we
    // simply use raw pointers and one large `unsafe` block.
    unsafe {
        // set the interrupt function to be our handler
        INTR_FN_ADDR.write_volatile(core::transmute(my_inter_fn));

        // enable vblank interrupts
        DISPSTAT.write_volatile(DISPSTAT_VBLANK);
        IME.write_volatile(IME_VBLANK);
        IE.write_volatile(true);
        
        // set the device for a basic display mode.
        DISPCNT.write_volatile(MODE3_BG2);
        let mut x = 0;
        loop {
            // wait in a low-power state for the vertical blank to start.
            VBlankInterWait(0, 0);
            // draw one new red pixel per frame along the top.
            VRAM_MODE3.row(0).col(x).write(RED);
            x += 1;
            // loop our position as necessary so that we don't
            // go out of bounds.
            if x >= VRAM_MODE3::WIDTH { x = 0 }
        }
    }
}

/// Responds to any interrupt by clearing all interrupt flags
/// and then immediately returning with no other effect.
#[instruction_set(arm::a32)]
fn my_inter_fn() {
    INTER_BIOS_FLAGS.write_volatile(ALL_INTER_FLAGS);
    INTER_STANDARD_FLAGS.write_volatile(ALL_INTER_FLAGS);
}
  1. We setup the device with our interrupt handler.
  2. We set the device to have an interrupt every time the vertical blank starts.
  3. We set the display to use a basic bitmap mode and begin our loop.
  4. Each pass of the loop we wait for vertical blank, then draw a single pixel to video memory.

In the case of this particular device, the hardware interrupts go to the device's BIOS, which then calls your interrupt handler function. However, because the BIOS is a32 code and uses a b branch instead of a bx branch-exchange, it jumps to the handler with the CPU in an a32 state. If the handler were written as t32 code it would immediately trigger UB.

Alternatives

Prior art

In C you can use __attribute__((target("arm"))) and __attribute__((target("thumb"))) to access similar functionality. It's a compiler-specific extension, but it's supported by both GCC and Clang (this PR appears to be the one that added this feature to LLVM/clang).

Unresolved questions

Future possibilities