Compiling without AVX instructions

are they reachable at runtime though? the -C target-feature flag set the default target features, but individual functions can overwrite this: as long as the code is not reachable at runtime, it is NOT UB by rust standard. for example:

/// llvm is ALLOWED to generate code using avx instructions for this function
#[target_feature(enable = "avx")]
fn foo() {
    //...
}

/// not annotated, inherit default target features passed to the compiler
fn bar() {
    // calling functions with `#[target_feature]` annotation from functions with different attributes *REQUIRES* unsafe
    if cfg!(target_feature = "avx") {
        // SAFETY: checked `target_feature` cfg flag
        unsafe {
            foo();
        }
    }
}

although in this example, the foo() function is likely removed during control flow analysis, because cfg!(target_feature(...)) evaluates to a compile time constant, but it is also possible for the program to use other means to do "real" runtime check, for example based on CPUID. in such cases, the foo() function will appear in the final binary but it will never get executed if the runtime cpu check was implemented correctly (otherwise, the unsafe block is unsound).

I think you might be confused because target_feature is both an codegen attribute, and a conditional compilation flag. the two can be used together, but they don't have to, for example:

/// this function IS conditional compiled.
/// and since it inherits the default target features, consequently,
/// when the condition is satisfied, the "avx" feature should also be enabled
#[cfg(target_feature = "avx")]
fn bar() {}

/// however, this function is NOT conditionally compiled!
/// the attribute simply enables the "avx" instructions for this individual function
/// calling it without checking is UB, but its existence alone is NOT UB.
#[target_feature(enable = "avx")]
fn foo() {}

also, there are the possibilities the avx instructions come from ffi libraries, which is out of control of the rust compiler. but again, the ffi librarie should implement proper runtime checking.

3 Likes