Skip to content
This repository was archived by the owner on Sep 25, 2026. It is now read-only.

Warning suppressions in compiler generated code - #2075

Merged
vitek-karas merged 8 commits into
dotnet:mainfrom
vitek-karas:CompilerGenerated
Jun 17, 2021
Merged

vitek-karas merged 8 commits into
dotnet:mainfrom
vitek-karas:CompilerGenerated

Conversation

@vitek-karas

@vitek-karas vitek-karas commented Jun 2, 2021 •

Copy link
Copy Markdown
Member

This change implements the following high-level functionality:

  • UnconditionalSuppressMessage applies to the entire method body even for iterators, async methods
  • RequiresUnreferencedCode automatically suppresses trim analysis warnings from entire method body for iterators, async methods

Solution approach:

  • Detect compiler generated code by using the IteratorStateMachineAttribute, AsyncStateMachineAttribute and AyncIteratorStateMachineAttribute.
    • When a method which is compiler generated (detected by looing for < in its name) is processed the original "user method" is determined by looking for a method with the "state machine" attribute pointing to the compiler generated type.
    • This information is cached to avoid duplication of relatively expensive detection logic.
  • Looks for UnconditionalSuppressMessage and RequriesUnreferencedCode in:
    • If the warning origin is not a compiler generated code - simply use the warning origin (method) - existing behavior
    • If the warning origin is compiler generated use both the origin as well as the user defined method (non-compiler-generated) which is the source of the code for the compiler generated origin

This is done by storing additional SuppressionContextMember on MessageOrigin which should always point to non-compiler-generated item.

Added lot of new tests for these scenarios.

This implements warning suppression part of #2001 for state machines.

@sbomer sbomer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice!

case Language.FSharp:
if (memberReference.Name.Contains ('@'))
return true;
break;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have a way to detect VB or compiler-generated code in VB assemblies?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll double check, but my understanding is that the compiler will use the same naming scheme for VB and C#...

Comment thread src/linker/Linker/LinkContext.cs Resolved
Comment thread src/linker/Linker/MessageOrigin.cs Resolved
Comment thread src/linker/Linker/MessageOrigin.cs Resolved
@MichalStrehovsky

MichalStrehovsky commented Jun 3, 2021 •

Copy link
Copy Markdown
Member

Does this work if I nest local functions?

Level1();

static void Level1()
{
    Level2();

    static void Level2()
    {
        Level3();

        static void Level3()
        {

        }
    }
}

I general, I would kind of prefer we do something more conservative, like look for AsyncStateMachineAttribute. I know that wouldn't solve local functions. But it would make the compiler feature request more urgent. If we add a workaround, however miserable it is, it is easy to brush off the compiler feature request with "they're unblocked and shipped this way".

If I understand this correctly - we figure out the "owning user code" by looking at the code that triggered need for the method body we're looking at - I'm a bit worried about whether a situation can occur where a single generated method is referred to from multiple user method bodies - would the annotation propagate from user code we saw first only?

I'm not confident I know all the situations where C# generates these helpers to be able to say these assumptions are safe. And I know nothing about the F# compiler.

@vitek-karas

Copy link
Copy Markdown
Member Author

The intent is definitely for it to work in nested local functions - I just haven't written all the tests yet.

Your other points are all valid:

  • Use more conservative approach - I actually wouldn't mind too much relying on the attributes. But @agocke didn't feel that these are OK to consume outside of the compiler/debugger. Note that it probably would make the compiler support more urgent because we would have a solution for iterators and async (via the attributes) and local functions and lambdas have an easy workaround - add the attribute on the local function - it would not match roslyn/analyzer behavior but it's a workaround just like any other.
  • You are right that this sort of makes the assumption that the compiler generated code is only used from one "user method". If this is not true, we would apply the "first callsite only" rules.
  • I discussed the C# one with @agocke and we're pretty confident that it should work for C#. F# is different and honestly it's more of a best effort (which is not much) currently since trimming F# is something which is already broken in many places anyway.

@MichalStrehovsky

Copy link
Copy Markdown
Member

Will this work if the reason why we're marking the compiler-generated thing is reflection/DynamicDependency/ILLinkTrim?

I'm thinking of scenario where we include an entire type with all its compiler-generated members because it was subject to something like DAMT.All - the reason why we are including it would be whatever brought .All on the type - not the method actually calling into compiler-generated code.

@agocke

agocke commented Jun 3, 2021

Copy link
Copy Markdown
Member

Looking for Async or IteratorStateMachine is fine, but I thought about the attributes-to-local-functions problems -- I don't see how it could work for those cases because there's no type to point to, and the method name might be ambiguous for overloads.

@agocke

agocke commented Jun 3, 2021

Copy link
Copy Markdown
Member

Ah, but if we don't need to identify the caller and only need to know that the method was generated by the compiler, that's different...

We would need a new attribute though, because the CompilerGenerated attribute is used by debuggers for a totally different purpose.

This change implements the following high-level functionality:
* UnconditionalSuppressMessage applies to the entire method body even for iterators, async methods and location functions and lambdas
* RequiresUnreferencedCode automatically suppresses trim analysis warnings from entire method body for iterators, async methods and local functions and lambdas.

Solution approach:
* Detect compiler generated code - heuristic for .NET 6
  * If in C# assembly, anything with `<` in its name is compiler generated
  * If in F# assembly, anything with `@` in its name is compiler generated
* Looks for UnconditionalSuppressMessage and RequriesUnreferencedCode in:
  * If the warning origin is not a compiler generated code - simply use the warning origin (method) - existing behavior
  * If the warning origin is compiler generated use both the origin as well as the user defined method (non-compiler-generated) which is the source of the code for the compiler generated origin

This is done by storing additional SuppressionContextMember on MessageOrigin which should always point to non-compiler-generated item. It's propagated using the scope stack in MarkStep and compiler-generated-code inherits the suppression context from its parent on the stack.

Added lot of new tests for these scenarios.
…butes (#10)

Changes the implementation to not use marking stack to deduce suppression context. Instead it relies on state machine attributes (`IteratorStateMachine`, `AsyncStateMachine`, ...) - these are generated by the compiler onto the original user method and point to the state machine type (compiler generated) which implements the body of the method.

This makes the behavior much more robust and predictable. The downside is that suppressions only propagate to iterator and async method bodies, they don't propagate to local functions and lambdas.

The information about the mapping between methods and state machine types is cached to avoid rescans which are relatively expensive.

Adapted the tests to the new behavior.
@vitek-karas
vitek-karas marked this pull request as ready for review June 15, 2021 10:58
@vitek-karas
vitek-karas requested a review from marek-safar as a code owner June 15, 2021 10:58
@vitek-karas

Copy link
Copy Markdown
Member Author

I think this is now ready for final review.

The actually implemented solution is not based on heuristics as that lead to lot of trouble when code is accessed via reflection (in which case we can't rely on mark ordering to determine the "user method").

This now only works on async and iterator method bodies. Lambdas and local functions are not handled.
The mapping is done via the compiler generated attributes IteratorStateMachine and similar. The new implementation is completely independent from mark ordering and works even when the compiler generated code is referenced only via reflection.

Comment thread docs/error-codes.md
Comment on lines +1615 to +1621
class <compiler_generated_state_machine>_type {
void MoveNext ()
{
// This should normally produce IL2026
CallSomethingWhichRequiresUnreferencedCode ();
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is public facing documentation, we should format this the way normal people expect C# code to be formatted.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

argh...

Comment thread src/linker/Linker.Steps/MarkStep.cs Outdated
Comment on lines +2723 to +2732
// Check both the origin's member (the direct method which contains the call to RUC)
// as well as the suppression context member (the "user code" source in case of compiler generated code)
IMemberDefinition suppressionContextMember = currentOrigin.SuppressionContextMember;
if (suppressionContextMember != null &&
Annotations.HasLinkerAttribute<RequiresUnreferencedCodeAttribute> (suppressionContextMember))
return;

IMemberDefinition originMember = currentOrigin.MemberDefinition;
if (suppressionContextMember != originMember && originMember != null &&
Annotations.HasLinkerAttribute<RequiresUnreferencedCodeAttribute> (originMember))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

static bool HasRoslynCompilerGeneratedName (IMemberDefinition member) =>
member.Name.Contains ('<') || member.DeclaringType == null || HasRoslynCompilerGeneratedName (member.DeclaringType);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be changed to take a TypeDefinition I think. Also, I'm not sure I understand the DeclaringType logic - should it be this instead?

Suggested change
member.Name.Contains ('<') || member.DeclaringType == null || HasRoslynCompilerGeneratedName (member.DeclaringType);
member.Name.Contains ('<') || (member.DeclaringType != null && HasRoslynCompilerGeneratedName (member.DeclaringType));

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right on both accounts - fixed.

@vitek-karas
vitek-karas merged commit bee7f73 into dotnet:main Jun 17, 2021
@vitek-karas
vitek-karas deleted the CompilerGenerated branch June 17, 2021 12:04
agocke pushed a commit to dotnet/runtime that referenced this pull request Nov 16, 2022
This change implements the following high-level functionality:
* `UnconditionalSuppressMessage` applies to the entire method body even for iterators, async methods
* `RequiresUnreferencedCode` automatically suppresses trim analysis warnings from entire method body for iterators, async methods

Solution approach:
* Detect compiler generated code by using the `IteratorStateMachineAttribute`, `AsyncStateMachineAttribute` and `AyncIteratorStateMachineAttribute`.
  * When a method which is compiler generated (detected by looing for `<` in its name) is processed the original "user method" is determined by looking for a method with the "state machine" attribute pointing to the compiler generated type.
  * This information is cached to avoid duplication of relatively expensive detection logic.
* Looks for `UnconditionalSuppressMessage` and `RequriesUnreferencedCode` in:
  * If the warning origin is not a compiler generated code - simply use the warning origin (method) - existing behavior
  * If the warning origin is compiler generated use both the origin as well as the user defined method (non-compiler-generated) which is the source of the code for the compiler generated origin

This is done by storing additional `SuppressionContextMember` on `MessageOrigin` which should always point to non-compiler-generated item.

Added lot of new tests for these scenarios.

This implements warning suppression part of dotnet/linker#2001 for state machines.

Commit migrated from dotnet/linker@bee7f73
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants