Miscompile: later `break` overrides an earlier one in an unrolled loop (loop exit structurization)

Abierto
#9,119 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 2 días

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
38/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
cpp
Área
compilers

Línea de trabajo

The bug is in lib/Transforms/Scalar/DxilRemoveUnstructuredLoopExits.cpp, in the guarding logic that uses HasSideEffects(bb) to decide which blocks between an exit and the latch get wrapped. Reproduce with the HLSL in the issue: -O3 gives Out is 2 for In=0, while -Od and -opt-disable structurize-loop-exits-for-unroll give 7. Done means the -O3 output matches -Od for In=0 and 5, and the fix does not break existing loop-exit tests.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug needs-triage

Description

When dxc unrolls a loop that has two breaks nested inside a conditional, a shader invocation that leaves through
the first break gets the value that belongs to the second one. No diagnostic (silent miscompilation) and the generated DXIL passes validation.

-opt-disable structurize-loop-exits-for-unroll gives correct code, and fxc compiles the same source correctly.

Steps to Reproduce

StructuredBuffer<uint>   In  : register(t0);
RWStructuredBuffer<uint> Out : register(u0);

[numthreads(64, 1, 1)]
void main(uint3 dtid : SV_DispatchThreadID)
{
    uint tid = dtid.x;
    uint a = In[tid];
    uint u = In[63];
    uint c = 4u;                          // (c & 3u) < 2u is true on the first iteration
    uint r = 7u;
    [unroll] for (uint i = 0u; i < 3u; ++i) {
        [branch] if (a != 14u) {
            if (a == 0u) { break; }       // exit #1
            r = 2u;                       // not reached when exit #1 is taken
            if ((c & 3u) < 2u) { break; } // exit #2
        }
        c = u;
    }
    Out[tid] = r;
}
dxc -T cs_6_0 -E main repro.hlsl -Fc out.ll

Expected: Out[tid] is 7 when In[tid] is 0 or 14, and 2 otherwise.

Actual Behavior

Out[tid] is 2 when In[tid] is 0. First unrolled iteration of the -O3 DXIL (%5 is In[tid], comments added):

; <label>:9
  %10 = icmp eq i32 %5, 0                      ; exit #1 condition
  br label %11

; <label>:11
  %12 = phi i1 [ true, %9 ], [ false, %0 ]     ; "exit #2 taken"
  %13 = phi i32 [ 2, %9 ], [ 0, %0 ]           ; r at exit #2
  %14 = phi i1 [ %10, %9 ], [ false, %0 ]      ; "exit #1 taken"
  %15 = phi i32 [ 7, %9 ], [ 0, %0 ]           ; r at exit #1
  %17 = or i1 %12, %14
  %18 = select i1 %12, i32 %13, i32 %15        ; exit #2's value wins whenever its flag is set
  br i1 %17, label %40, label %19              ; %40 stores %18 to Out[tid]

Exit #2's flag is set for invocations that already took exit #1, and it is tested first.

Run with In = 0, 5, 0, 5, ...; WARP and an NVIDIA GPU give the same results:

compile In[tid] == 0 In[tid] == 5
-Od 7 2
-O3 (default) 2 2
-O3 -opt-disable structurize-loop-exits-for-unroll 7 2
fxc /T cs_5_0 7 2

It needs all of the following:

  • the loop is unrolled ([unroll], or no attribute; [loop] is correct);
  • both breaks are nested in a conditional (directly in the loop body is correct);
  • no memory access between them (a buffer read in exit #2's condition is correct);
  • both exit conditions are true for the same invocation in the same iteration.

The constants do not matter; run-time values fail the same way. -Od is also wrong when the loop sits in a helper
function. The same function compiles to the same loop logic for ps_6_0, vs_6_0, gs_6_0 and lib_6_3.

Analysis (lib/Transforms/Scalar/DxilRemoveUnstructuredLoopExits.cpp)

When exit #1 is converted to a flag, the blocks between it and the latch are only guarded if HasSideEffects(bb),
which checks mayReadOrWriteMemory(). The block holding exit #2 has no memory access, so it stays unguarded and
invocations whose exit #1 flag is set still run its exit branch. The file header says leaving such code
unconditional "doesn't impact code correctness"; that does not hold when the block is itself an exiting block.
Also guarding a traversed block when L->isLoopExiting(bb) might fix it; I have not tested that.

Environment

  • DXC version: dxcompiler.dll: 1.9(5512-01b62ad4)(1.9.2609.5) - 1.9.2609.5 (01b62ad47); also 1.10.2605.37 and 1.8.2502.11

Found during compiler testing. An AI assistant was used for the reduction, the analysis and for drafting this text;
I reviewed all of it and reproduced the results.

Lenguaje dominante
C++
Estrellas
3.7k
Forks
926
Merge medio
3 d 22 h
PR fusionados (30 d)
45

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de microsoft/DirectXShaderCompiler

Todos los issues de microsoft/DirectXShaderCompiler

Issues similares

Más issues de C++

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.