Skip to content

[Fix][Codegen] Avoid extraneous parentheses in if_then_else generated code - #20285

Open
fengz72 wants to merge 1 commit into
apache:mainfrom
fengz72:fix-if-then-else-parens
Open

[Fix][Codegen] Avoid extraneous parentheses in if_then_else generated code#20285
fengz72 wants to merge 1 commit into
apache:mainfrom
fengz72:fix-if-then-else-parens

Conversation

@fengz72

@fengz72 fengz72 commented Sep 7, 2026

Copy link
Copy Markdown

Problem

Since #16242, the if_then_else builtin call is expanded into an if/else statement. When printing the condition, the codegen wraps it in another pair of parentheses even though it is already parenthesized, producing if ((i == 0)).

Impact

The doubled parentheses trigger clang's -Wparentheses-equality warning under -Wall/-Wparentheses, which is noisy for downstream users who compile TVM-generated C sources with strict warning settings. Correctness is not affected — the issue is cosmetic.

Solution

Reuse the same leading/trailing parenthesis check as the existing IfThenElseNode handling in CodeGenC, so a condition that already starts and ends with parentheses is printed as-is. The generated code now reads if (i == 0).

Since CodeGenC is the shared base of all C-style backends (CUDA, Metal, ROCm, Vulkan, WebGPU, Hexagon), this fix covers them all at once.

Testing

  • Added a regression test test_if_then_else_avoids_extraneous_parentheses in tests/python/codegen/test_target_codegen_c_host.py, which asserts the generated C source contains no if (( and validates the runtime result.
  • Ran the full test_target_codegen_c_host.py suite on aarch64 Linux with a local build: 10/10 passed.
  • pre-commit (clang-format, ruff-check, ruff-format) passed on the changed files.

… code

The if_then_else builtin call is expanded into an if/else statement, and the
condition string is wrapped in another pair of parentheses even when it is
already parenthesized, e.g. `if ((i == 0))`. This triggers clang's
-Wparentheses-equality warning on the generated code.

Reuse the same leading/trailing parenthesis check as the IfThenElseNode
handling so the redundant parentheses are not emitted. Add a regression test
asserting the generated C source contains no `if ((` and the runtime result
stays correct.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant