diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs index d00d32c6a1d2f..be1747cebc279 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundExpression.cs @@ -507,14 +507,15 @@ public override Symbol ExpressionSymbol /// /// Build an object creation expression without performing any rewriting /// - internal BoundObjectCreationExpression UpdateArgumentsAndInitializer( + internal BoundObjectCreationExpression Update( + MethodSymbol constructor, ImmutableArray newArguments, ImmutableArray newRefKinds, BoundObjectInitializerExpressionBase? newInitializerExpression, TypeSymbol? changeTypeOpt = null) { return Update( - constructor: Constructor, + constructor: constructor, arguments: newArguments, argumentNamesOpt: default(ImmutableArray), argumentRefKindsOpt: newRefKinds, diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundNode.cs b/src/Compilers/CSharp/Portable/BoundTree/BoundNode.cs index fb3ca40016bc5..a8663d5e35f99 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundNode.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundNode.cs @@ -525,24 +525,31 @@ private void CheckDeclared(LocalSymbol local) public override BoundNode? VisitBlock(BoundBlock node) { - if (node.Instrumentation != null) + var instrumentation = node.Instrumentation; + if (instrumentation != null) { - var added = DeclaredLocals.Add(node.Instrumentation.Local); - Debug.Assert(added); + foreach (var local in instrumentation.Locals) + { + var added = DeclaredLocals.Add(local); + Debug.Assert(added); + } - _ = Visit(node.Instrumentation.Prologue); + _ = Visit(instrumentation.Prologue); } AddAll(node.Locals); base.VisitBlock(node); RemoveAll(node.Locals); - if (node.Instrumentation != null) + if (instrumentation != null) { - _ = Visit(node.Instrumentation.Epilogue); + _ = Visit(instrumentation.Epilogue); - var removed = DeclaredLocals.Remove(node.Instrumentation.Local); - Debug.Assert(removed); + foreach (var local in instrumentation.Locals) + { + var removed = DeclaredLocals.Remove(local); + Debug.Assert(removed); + } } return null; diff --git a/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml b/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml index f4d0d9b9db29c..b33591199ad9b 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml +++ b/src/Compilers/CSharp/Portable/BoundTree/BoundNodes.xml @@ -706,9 +706,15 @@ - - - + + + + + + + + + + + + + + + diff --git a/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs b/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs index f188d21d0876a..a01873aa52b36 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/EmitExpression.cs @@ -238,6 +238,16 @@ private void EmitExpressionCore(BoundExpression expression, bool used) EmitModuleVersionIdStringLoad(); break; + case BoundKind.ThrowIfModuleCancellationRequested: + Debug.Assert(!used); + EmitThrowIfModuleCancellationRequested(expression.Syntax); + break; + + case BoundKind.ModuleCancellationTokenExpression: + Debug.Assert(used); + EmitModuleCancellationTokenLoad(expression.Syntax); + break; + case BoundKind.InstrumentationPayloadRoot: Debug.Assert(used); EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression); @@ -3571,7 +3581,43 @@ private void EmitModuleVersionIdStore(BoundModuleVersionId node) private void EmitModuleVersionIdToken(BoundModuleVersionId node) { - _builder.EmitToken(_module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics.DiagnosticBag), node.Syntax, _diagnostics.DiagnosticBag), node.Syntax, _diagnostics.DiagnosticBag); + _builder.EmitToken( + _module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics.DiagnosticBag), node.Syntax, _diagnostics.DiagnosticBag), + node.Syntax, + _diagnostics.DiagnosticBag); + } + + private void EmitThrowIfModuleCancellationRequested(SyntaxNode syntax) + { + var cancellationTokenType = _module.CommonCompilation.CommonGetWellKnownType(WellKnownType.System_Threading_CancellationToken); + + _builder.EmitOpCode(ILOpCode.Ldsflda); + _builder.EmitToken( + _module.GetModuleCancellationToken(_module.Translate(cancellationTokenType, syntax, _diagnostics.DiagnosticBag), syntax, _diagnostics.DiagnosticBag), + syntax, + _diagnostics.DiagnosticBag); + + var throwMethod = (MethodSymbol)_module.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Threading_CancellationToken__ThrowIfCancellationRequested); + + // BoundThrowIfModuleCancellationRequested should not be created if the method doesn't exist. + Debug.Assert(throwMethod != null); + + _builder.EmitOpCode(ILOpCode.Call, -1); + _builder.EmitToken( + _module.Translate(throwMethod, syntax, _diagnostics.DiagnosticBag), + syntax, + _diagnostics.DiagnosticBag); + } + + private void EmitModuleCancellationTokenLoad(SyntaxNode syntax) + { + var cancellationTokenType = _module.CommonCompilation.CommonGetWellKnownType(WellKnownType.System_Threading_CancellationToken); + + _builder.EmitOpCode(ILOpCode.Ldsfld); + _builder.EmitToken( + _module.GetModuleCancellationToken(_module.Translate(cancellationTokenType, syntax, _diagnostics.DiagnosticBag), syntax, _diagnostics.DiagnosticBag), + syntax, + _diagnostics.DiagnosticBag); } private void EmitModuleVersionIdStringLoad() diff --git a/src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs b/src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs index c336e8c170a1c..107a8f02f2481 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs @@ -677,38 +677,63 @@ private void EmitBlock(BoundBlock block) private void EmitInstrumentedBlock(BoundBlockInstrumentation instrumentation, BoundBlock block) { - _builder.OpenLocalScope(); - DefineLocal(instrumentation.Local, block.Syntax); - - if (_emitPdbSequencePoints) + if (!instrumentation.Locals.IsEmpty) { - EmitHiddenSequencePoint(); + _builder.OpenLocalScope(); + + foreach (var local in instrumentation.Locals) + { + DefineLocal(local, block.Syntax); + } } - EmitStatement(instrumentation.Prologue); + if (instrumentation.Prologue != null) + { + if (_emitPdbSequencePoints) + { + EmitHiddenSequencePoint(); + } + + EmitStatement(instrumentation.Prologue); + } _builder.AssertStackEmpty(); - _builder.OpenLocalScope(ScopeType.TryCatchFinally); + if (instrumentation.Epilogue != null) + { + _builder.OpenLocalScope(ScopeType.TryCatchFinally); - _builder.OpenLocalScope(ScopeType.Try); - EmitUninstrumentedBlock(block); - _builder.CloseLocalScope(); // try + _builder.OpenLocalScope(ScopeType.Try); + + EmitUninstrumentedBlock(block); + _builder.CloseLocalScope(); // try - _builder.OpenLocalScope(ScopeType.Finally); + _builder.OpenLocalScope(ScopeType.Finally); - if (_emitPdbSequencePoints) + if (_emitPdbSequencePoints) + { + EmitHiddenSequencePoint(); + } + + EmitStatement(instrumentation.Epilogue); + _builder.CloseLocalScope(); // finally + + _builder.CloseLocalScope(); // try-finally + } + else { - EmitHiddenSequencePoint(); + EmitUninstrumentedBlock(block); } - EmitStatement(instrumentation.Epilogue); - _builder.CloseLocalScope(); // finally - - _builder.CloseLocalScope(); // try-finally + if (!instrumentation.Locals.IsEmpty) + { + foreach (var local in instrumentation.Locals) + { + FreeLocal(local); + } - FreeLocal(instrumentation.Local); - _builder.CloseLocalScope(); + _builder.CloseLocalScope(); + } } private void EmitUninstrumentedBlock(BoundBlock block) diff --git a/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs b/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs index 99e004078d094..a704cc630aa4e 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs @@ -616,12 +616,13 @@ public override BoundNode VisitBlock(BoundBlock node) if (node.Instrumentation != null) { - DeclareLocal(node.Instrumentation.Local, stack: 0); + foreach (var local in node.Instrumentation.Locals) + DeclareLocal(local, stack: 0); } // normally we would not allow stack locals // when evaluation stack is not empty. - DeclareLocals(node.Locals, 0); + DeclareLocals(node.Locals, stack: 0); return base.VisitBlock(node); } diff --git a/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs b/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs index e0d28008cd0e0..2efcfc528e4fc 100644 --- a/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs +++ b/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs @@ -1018,7 +1018,9 @@ private void CompileMethod( ((methodSymbol.ContainingType.IsStructType() && !methodSymbol.IsImplicitConstructor) || methodSymbol is SynthesizedPrimaryConstructor || instrumentation.Kinds.Contains(InstrumentationKind.TestCoverage) || - instrumentation.Kinds.Contains(InstrumentationKindExtensions.LocalStateTracing))) + instrumentation.Kinds.Contains(InstrumentationKindExtensions.LocalStateTracing) || + instrumentation.Kinds.Contains(InstrumentationKind.StackOverflowProbing) || + instrumentation.Kinds.Contains(InstrumentationKind.ModuleCancellation))) { if (methodSymbol.IsImplicitConstructor && (instrumentation.Kinds.Contains(InstrumentationKind.TestCoverage) || instrumentation.Kinds.Contains(InstrumentationKindExtensions.LocalStateTracing))) diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs index 61fb94f56681f..97542180356ed 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/AbstractFlowPass.cs @@ -1662,6 +1662,11 @@ public override BoundNode VisitInstrumentationPayloadRoot(BoundInstrumentationPa return null; } + public override BoundNode VisitThrowIfModuleCancellationRequested(BoundThrowIfModuleCancellationRequested node) + { + return null; + } + public override BoundNode VisitSourceDocumentIndex(BoundSourceDocumentIndex node) { return null; diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs index 90abbd1cc148c..fb7e7fe234c61 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.cs @@ -2075,13 +2075,18 @@ void assignPatternVariablesAndMarkReadFields(BoundPattern pattern, bool definite } } } - - public override BoundNode VisitBlock(BoundBlock node) +#nullable enable + public override BoundNode? VisitBlock(BoundBlock node) { - if (node.Instrumentation != null) + var instrumentation = node.Instrumentation; + if (instrumentation != null) { - DeclareVariable(node.Instrumentation.Local); - Visit(node.Instrumentation.Prologue); + DeclareVariables(instrumentation.Locals); + + if (instrumentation.Prologue != null) + { + Visit(instrumentation.Prologue); + } } DeclareVariables(node.Locals); @@ -2100,14 +2105,14 @@ public override BoundNode VisitBlock(BoundBlock node) ReportUnusedVariables(node.Locals); ReportUnusedVariables(node.LocalFunctions); - if (node.Instrumentation != null) + if (instrumentation?.Epilogue != null) { - Visit(node.Instrumentation.Epilogue); + Visit(instrumentation.Epilogue); } return null; } - +#nullable disable private void VisitStatementsWithLocalFunctions(BoundBlock block) { if (!TrackingRegions && !block.LocalFunctions.IsDefaultOrEmpty) @@ -2243,6 +2248,14 @@ private void DeclareVariables(ImmutableArray locals) } } + private void DeclareVariables(OneOrMany locals) + { + foreach (var symbol in locals) + { + DeclareVariable(symbol); + } + } + private void DeclareVariable(LocalSymbol symbol) { var initiallyAssigned = diff --git a/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs b/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs index 34f286a111b2d..4339618945b4f 100644 --- a/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs +++ b/src/Compilers/CSharp/Portable/Generated/BoundNodes.xml.Generated.cs @@ -80,6 +80,8 @@ internal enum BoundKind : byte StateMachineInstanceId, MaximumMethodDefIndex, InstrumentationPayloadRoot, + ThrowIfModuleCancellationRequested, + ModuleCancellationTokenExpression, ModuleVersionId, ModuleVersionIdString, SourceDocumentIndex, @@ -2225,31 +2227,29 @@ public BoundTypeOfOperator Update(BoundTypeExpression sourceType, MethodSymbol? internal sealed partial class BoundBlockInstrumentation : BoundNode { - public BoundBlockInstrumentation(SyntaxNode syntax, LocalSymbol local, BoundStatement prologue, BoundStatement epilogue, bool hasErrors = false) + public BoundBlockInstrumentation(SyntaxNode syntax, OneOrMany locals, BoundStatement? prologue, BoundStatement? epilogue, bool hasErrors = false) : base(BoundKind.BlockInstrumentation, syntax, hasErrors || prologue.HasErrors() || epilogue.HasErrors()) { - RoslynDebug.Assert(local is object, "Field 'local' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); - RoslynDebug.Assert(prologue is object, "Field 'prologue' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); - RoslynDebug.Assert(epilogue is object, "Field 'epilogue' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); + RoslynDebug.Assert(!locals.IsDefault, "Field 'locals' cannot be null (use Null=\"allow\" in BoundNodes.xml to remove this check)"); - this.Local = local; + this.Locals = locals; this.Prologue = prologue; this.Epilogue = epilogue; } - public LocalSymbol Local { get; } - public BoundStatement Prologue { get; } - public BoundStatement Epilogue { get; } + public OneOrMany Locals { get; } + public BoundStatement? Prologue { get; } + public BoundStatement? Epilogue { get; } [DebuggerStepThrough] public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitBlockInstrumentation(this); - public BoundBlockInstrumentation Update(LocalSymbol local, BoundStatement prologue, BoundStatement epilogue) + public BoundBlockInstrumentation Update(OneOrMany locals, BoundStatement? prologue, BoundStatement? epilogue) { - if (!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals(local, this.Local) || prologue != this.Prologue || epilogue != this.Epilogue) + if (!locals.SequenceEqual(Locals) || prologue != this.Prologue || epilogue != this.Epilogue) { - var result = new BoundBlockInstrumentation(this.Syntax, local, prologue, epilogue, this.HasErrors); + var result = new BoundBlockInstrumentation(this.Syntax, locals, prologue, epilogue, this.HasErrors); result.CopyAttributes(this); return result; } @@ -2491,6 +2491,76 @@ public BoundInstrumentationPayloadRoot Update(int analysisKind, TypeSymbol type) } } + internal sealed partial class BoundThrowIfModuleCancellationRequested : BoundExpression + { + public BoundThrowIfModuleCancellationRequested(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ThrowIfModuleCancellationRequested, syntax, type, hasErrors) + { + + RoslynDebug.Assert(type is object, "Field 'type' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); + + } + + public BoundThrowIfModuleCancellationRequested(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ThrowIfModuleCancellationRequested, syntax, type) + { + + RoslynDebug.Assert(type is object, "Field 'type' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); + + } + + public new TypeSymbol Type => base.Type!; + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitThrowIfModuleCancellationRequested(this); + + public BoundThrowIfModuleCancellationRequested Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + { + var result = new BoundThrowIfModuleCancellationRequested(this.Syntax, type, this.HasErrors); + result.CopyAttributes(this); + return result; + } + return this; + } + } + + internal sealed partial class ModuleCancellationTokenExpression : BoundExpression + { + public ModuleCancellationTokenExpression(SyntaxNode syntax, TypeSymbol type, bool hasErrors) + : base(BoundKind.ModuleCancellationTokenExpression, syntax, type, hasErrors) + { + + RoslynDebug.Assert(type is object, "Field 'type' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); + + } + + public ModuleCancellationTokenExpression(SyntaxNode syntax, TypeSymbol type) + : base(BoundKind.ModuleCancellationTokenExpression, syntax, type) + { + + RoslynDebug.Assert(type is object, "Field 'type' cannot be null (make the type nullable in BoundNodes.xml to remove this check)"); + + } + + public new TypeSymbol Type => base.Type!; + + [DebuggerStepThrough] + public override BoundNode? Accept(BoundTreeVisitor visitor) => visitor.VisitModuleCancellationTokenExpression(this); + + public ModuleCancellationTokenExpression Update(TypeSymbol type) + { + if (!TypeSymbol.Equals(type, this.Type, TypeCompareKind.ConsiderEverything)) + { + var result = new ModuleCancellationTokenExpression(this.Syntax, type, this.HasErrors); + result.CopyAttributes(this); + return result; + } + return this; + } + } + internal sealed partial class BoundModuleVersionId : BoundExpression { public BoundModuleVersionId(SyntaxNode syntax, TypeSymbol type, bool hasErrors) @@ -8839,6 +8909,10 @@ internal R VisitInternal(BoundNode node, A arg) return VisitMaximumMethodDefIndex((BoundMaximumMethodDefIndex)node, arg); case BoundKind.InstrumentationPayloadRoot: return VisitInstrumentationPayloadRoot((BoundInstrumentationPayloadRoot)node, arg); + case BoundKind.ThrowIfModuleCancellationRequested: + return VisitThrowIfModuleCancellationRequested((BoundThrowIfModuleCancellationRequested)node, arg); + case BoundKind.ModuleCancellationTokenExpression: + return VisitModuleCancellationTokenExpression((ModuleCancellationTokenExpression)node, arg); case BoundKind.ModuleVersionId: return VisitModuleVersionId((BoundModuleVersionId)node, arg); case BoundKind.ModuleVersionIdString: @@ -9245,6 +9319,8 @@ internal abstract partial class BoundTreeVisitor public virtual R VisitStateMachineInstanceId(BoundStateMachineInstanceId node, A arg) => this.DefaultVisit(node, arg); public virtual R VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node, A arg) => this.DefaultVisit(node, arg); public virtual R VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node, A arg) => this.DefaultVisit(node, arg); + public virtual R VisitThrowIfModuleCancellationRequested(BoundThrowIfModuleCancellationRequested node, A arg) => this.DefaultVisit(node, arg); + public virtual R VisitModuleCancellationTokenExpression(ModuleCancellationTokenExpression node, A arg) => this.DefaultVisit(node, arg); public virtual R VisitModuleVersionId(BoundModuleVersionId node, A arg) => this.DefaultVisit(node, arg); public virtual R VisitModuleVersionIdString(BoundModuleVersionIdString node, A arg) => this.DefaultVisit(node, arg); public virtual R VisitSourceDocumentIndex(BoundSourceDocumentIndex node, A arg) => this.DefaultVisit(node, arg); @@ -9478,6 +9554,8 @@ internal abstract partial class BoundTreeVisitor public virtual BoundNode? VisitStateMachineInstanceId(BoundStateMachineInstanceId node) => this.DefaultVisit(node); public virtual BoundNode? VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) => this.DefaultVisit(node); public virtual BoundNode? VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) => this.DefaultVisit(node); + public virtual BoundNode? VisitThrowIfModuleCancellationRequested(BoundThrowIfModuleCancellationRequested node) => this.DefaultVisit(node); + public virtual BoundNode? VisitModuleCancellationTokenExpression(ModuleCancellationTokenExpression node) => this.DefaultVisit(node); public virtual BoundNode? VisitModuleVersionId(BoundModuleVersionId node) => this.DefaultVisit(node); public virtual BoundNode? VisitModuleVersionIdString(BoundModuleVersionIdString node) => this.DefaultVisit(node); public virtual BoundNode? VisitSourceDocumentIndex(BoundSourceDocumentIndex node) => this.DefaultVisit(node); @@ -9883,6 +9961,8 @@ internal abstract partial class BoundTreeWalker : BoundTreeVisitor public override BoundNode? VisitStateMachineInstanceId(BoundStateMachineInstanceId node) => null; public override BoundNode? VisitMaximumMethodDefIndex(BoundMaximumMethodDefIndex node) => null; public override BoundNode? VisitInstrumentationPayloadRoot(BoundInstrumentationPayloadRoot node) => null; + public override BoundNode? VisitThrowIfModuleCancellationRequested(BoundThrowIfModuleCancellationRequested node) => null; + public override BoundNode? VisitModuleCancellationTokenExpression(ModuleCancellationTokenExpression node) => null; public override BoundNode? VisitModuleVersionId(BoundModuleVersionId node) => null; public override BoundNode? VisitModuleVersionIdString(BoundModuleVersionIdString node) => null; public override BoundNode? VisitSourceDocumentIndex(BoundSourceDocumentIndex node) => null; @@ -10998,9 +11078,9 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor } public override BoundNode? VisitBlockInstrumentation(BoundBlockInstrumentation node) { - BoundStatement prologue = (BoundStatement)this.Visit(node.Prologue); - BoundStatement epilogue = (BoundStatement)this.Visit(node.Epilogue); - return node.Update(node.Local, prologue, epilogue); + BoundStatement? prologue = (BoundStatement?)this.Visit(node.Prologue); + BoundStatement? epilogue = (BoundStatement?)this.Visit(node.Epilogue); + return node.Update(node.Locals, prologue, epilogue); } public override BoundNode? VisitMethodDefIndex(BoundMethodDefIndex node) { @@ -11032,6 +11112,16 @@ internal abstract partial class BoundTreeRewriter : BoundTreeVisitor TypeSymbol? type = this.VisitType(node.Type); return node.Update(node.AnalysisKind, type); } + public override BoundNode? VisitThrowIfModuleCancellationRequested(BoundThrowIfModuleCancellationRequested node) + { + TypeSymbol? type = this.VisitType(node.Type); + return node.Update(type); + } + public override BoundNode? VisitModuleCancellationTokenExpression(ModuleCancellationTokenExpression node) + { + TypeSymbol? type = this.VisitType(node.Type); + return node.Update(type); + } public override BoundNode? VisitModuleVersionId(BoundModuleVersionId node) { TypeSymbol? type = this.VisitType(node.Type); @@ -12830,14 +12920,6 @@ public NullabilityRewriter(ImmutableDictionary new TreeDumperNode("blockInstrumentation", null, new TreeDumperNode[] { - new TreeDumperNode("local", node.Local, null), + new TreeDumperNode("locals", node.Locals, null), new TreeDumperNode("prologue", null, new TreeDumperNode[] { Visit(node.Prologue, null) }), new TreeDumperNode("epilogue", null, new TreeDumperNode[] { Visit(node.Epilogue, null) }), new TreeDumperNode("hasErrors", node.HasErrors, null) @@ -15332,6 +15438,20 @@ private BoundTreeDumperNodeProducer() new TreeDumperNode("hasErrors", node.HasErrors, null) } ); + public override TreeDumperNode VisitThrowIfModuleCancellationRequested(BoundThrowIfModuleCancellationRequested node, object? arg) => new TreeDumperNode("throwIfModuleCancellationRequested", null, new TreeDumperNode[] + { + new TreeDumperNode("type", node.Type, null), + new TreeDumperNode("isSuppressed", node.IsSuppressed, null), + new TreeDumperNode("hasErrors", node.HasErrors, null) + } + ); + public override TreeDumperNode VisitModuleCancellationTokenExpression(ModuleCancellationTokenExpression node, object? arg) => new TreeDumperNode("moduleCancellationTokenExpression", null, new TreeDumperNode[] + { + new TreeDumperNode("type", node.Type, null), + new TreeDumperNode("isSuppressed", node.IsSuppressed, null), + new TreeDumperNode("hasErrors", node.HasErrors, null) + } + ); public override TreeDumperNode VisitModuleVersionId(BoundModuleVersionId node, object? arg) => new TreeDumperNode("moduleVersionId", null, new TreeDumperNode[] { new TreeDumperNode("type", node.Type, null), diff --git a/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs index d5d42d092c859..a81f70357653c 100644 --- a/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; @@ -203,13 +202,7 @@ internal void GenerateMoveNext(BoundStatement body, MethodSymbol moveNextMethod) newBody = MakeStateMachineScope(rootScopeHoistedLocals, newBody); } - if (instrumentation != null) - { - newBody = F.Block( - ImmutableArray.Create(instrumentation.Local), - instrumentation.Prologue, - F.Try(F.Block(newBody), ImmutableArray.Empty, F.Block(instrumentation.Epilogue))); - } + newBody = F.Instrument(newBody, instrumentation); F.CloseMethod(newBody); } diff --git a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs index 9b8ef08daff9e..800a97a466638 100644 --- a/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs +++ b/src/Compilers/CSharp/Portable/Lowering/ClosureConversion/ClosureConversion.cs @@ -1181,7 +1181,7 @@ private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder p { var newPrologue = (BoundStatement)Visit(newInstrumentation.Prologue); var newEpilogue = (BoundStatement)Visit(newInstrumentation.Epilogue); - newInstrumentation = newInstrumentation.Update(newInstrumentation.Local, newPrologue, newEpilogue); + newInstrumentation = newInstrumentation.Update(newInstrumentation.Locals, newPrologue, newEpilogue); } // TODO: we may not need to update if there was nothing to rewrite. diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs index 54033c05e80a9..82f5dda4cb4b9 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/CompoundInstrumenter.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections.Immutable; using System.Diagnostics; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Collections; @@ -159,6 +161,15 @@ public override BoundExpression InstrumentCall(BoundCall original, BoundExpressi return Previous.InstrumentCall(original, rewritten); } + public override void InterceptCallAndAdjustArguments( + ref MethodSymbol method, + ref BoundExpression? receiver, + ref ImmutableArray arguments, + ref ImmutableArray argumentRefKindsOpt) + { + Previous.InterceptCallAndAdjustArguments(ref method, ref receiver, ref arguments, ref argumentRefKindsOpt); + } + public override BoundExpression InstrumentObjectCreationExpression(BoundObjectCreationExpression original, BoundExpression rewritten) { return Previous.InstrumentObjectCreationExpression(original, rewritten); diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs index f9b1e9c63fcfd..561559771f6c2 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Collections; +using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp { @@ -228,6 +229,20 @@ public virtual BoundExpression InstrumentCall(BoundCall original, BoundExpressio return rewritten; } + /// + /// Similarly to an interceptor, gives the instrumenter an opportunity to adjust call target, receiver and arguments. + /// + /// + /// Unlike interceptors, called also for constructor calls (with being null). + /// + public virtual void InterceptCallAndAdjustArguments( + ref MethodSymbol method, + ref BoundExpression? receiver, + ref ImmutableArray arguments, + ref ImmutableArray argumentRefKindsOpt) + { + } + public virtual BoundExpression InstrumentObjectCreationExpression(BoundObjectCreationExpression original, BoundExpression rewritten) { return rewritten; diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs index b4f37d88e1d07..2cb55cea8027a 100644 --- a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/LocalStateTracingInstrumenter.cs @@ -343,14 +343,7 @@ public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter var instrumentationEpilogue = (returnLogger != null) ? _factory.ExpressionStatement(_factory.Call(receiver: _factory.Local(_scope.ContextVariable), returnLogger)) : _factory.NoOp(NoOpStatementFlavor.Default); - // currently don't need to compose multiple instrumentations - Debug.Assert(instrumentation is null); - - instrumentation = new BoundBlockInstrumentation( - _factory.Syntax, - _scope.ContextVariable, - instrumentationPrologue, - instrumentationEpilogue); + instrumentation = _factory.CombineInstrumentation(instrumentation, _scope.ContextVariable, instrumentationPrologue, instrumentationEpilogue); _scope.Close(isMethodBody); } diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs new file mode 100644 index 0000000000000..a99b700defbf9 --- /dev/null +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/ModuleCancellationInstrumenter.cs @@ -0,0 +1,222 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Immutable; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Shared.Collections; + +namespace Microsoft.CodeAnalysis.CSharp; + +/// +/// Implements instrumentation for . +/// +/// +/// - Adds a static writable field of type to PrivateImplementationDetails. The host can set this token via Reflection before executing the compiled code. +/// - Inserts calls to on the host token into each method, loop or goto. +/// - Replaces any tokens passed as arguments with the host token. +/// - Replaces calls to methods that do not take as the last parameter with matching overloads that do and passes it the host token. +/// +internal sealed class ModuleCancellationInstrumenter( + MethodSymbol throwMethod, + SyntheticBoundNodeFactory factory, + Instrumenter previous) + : CompoundInstrumenter(previous) +{ + private readonly MethodSymbol _throwMethod = throwMethod; + private readonly SyntheticBoundNodeFactory _factory = factory; + + protected override CompoundInstrumenter WithPreviousImpl(Instrumenter previous) + => new ModuleCancellationInstrumenter( + _throwMethod, + _factory, + previous); + + public static bool TryCreate( + MethodSymbol method, + SyntheticBoundNodeFactory factory, + Instrumenter previous, + [NotNullWhen(true)] out ModuleCancellationInstrumenter? instrumenter) + { + instrumenter = null; + + // Do not instrument implicitly-declared methods or methods without bodies, except for constructors. + // Instrument implicit constructors in order to cancel execution of member initializers. + if (method.MethodKind is not (MethodKind.Constructor or MethodKind.StaticConstructor) && + (method is { IsImplicitlyDeclared: true } || + method is SourceMemberMethodSymbol { Bodies: { arrowBody: null, blockBody: null } } and not SynthesizedSimpleProgramEntryPointSymbol)) + { + return false; + } + + var throwMethod = factory.WellKnownMethod(WellKnownMember.System_Threading_CancellationToken__ThrowIfCancellationRequested, isOptional: true); + if (throwMethod is null) + { + return false; + } + + instrumenter = new ModuleCancellationInstrumenter(throwMethod, factory, previous); + return true; + } + + public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + base.InstrumentBlock(original, rewriter, ref additionalLocals, out prologue, out epilogue, out instrumentation); + + var isMethodBody = rewriter.CurrentMethodBody == original; + var isLambdaBody = rewriter.CurrentLambdaBody == original; + + // Don't instrument blocks that are not a method or lambda body + if (!isMethodBody && !isLambdaBody) + { + return; + } + + Debug.Assert(_factory.TopLevelMethod is not null); + Debug.Assert(_factory.CurrentFunction is not null); + + // static constructors can only be invoked once, so there is no need to probe: + if (isMethodBody && _factory.TopLevelMethod.MethodKind == MethodKind.StaticConstructor) + { + return; + } + + instrumentation = _factory.CombineInstrumentation( + instrumentation, + prologue: _factory.ExpressionStatement(_factory.ThrowIfModuleCancellationRequested())); + } + + private BoundExpression InstrumentExpression(BoundExpression expression) + => _factory.Sequence([], [_factory.ThrowIfModuleCancellationRequested()], expression); + + private BoundStatement InstrumentStatement(BoundStatement statement) + => _factory.StatementList(_factory.ExpressionStatement(_factory.ThrowIfModuleCancellationRequested()), statement); + + public override BoundExpression InstrumentWhileStatementCondition(BoundWhileStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + => InstrumentExpression(base.InstrumentWhileStatementCondition(original, rewrittenCondition, factory)); + + public override BoundExpression InstrumentDoStatementCondition(BoundDoStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + => InstrumentExpression(base.InstrumentDoStatementCondition(original, rewrittenCondition, factory)); + + public override BoundExpression InstrumentForStatementCondition(BoundForStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) + => InstrumentExpression(base.InstrumentForStatementCondition(original, rewrittenCondition, factory)); + + public override BoundStatement InstrumentForStatementConditionalGotoStartOrBreak(BoundForStatement original, BoundStatement branchBack) + => InstrumentStatement(base.InstrumentForStatementConditionalGotoStartOrBreak(original, branchBack)); + + public override BoundStatement InstrumentForEachStatementConditionalGotoStart(BoundForEachStatement original, BoundStatement branchBack) + => InstrumentStatement(base.InstrumentForEachStatementConditionalGotoStart(original, branchBack)); + + public override BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) + => InstrumentStatement(base.InstrumentGotoStatement(original, rewritten)); + + public override void InterceptCallAndAdjustArguments( + ref MethodSymbol method, + ref BoundExpression? receiver, + ref ImmutableArray arguments, + ref ImmutableArray argumentRefKindsOpt) + { + Previous.InterceptCallAndAdjustArguments(ref method, ref receiver, ref arguments, ref argumentRefKindsOpt); + + // If the target method is defined within this module it is already being instrumented to be cancellable. + // However, if we are calling Invoke method of a delegate or a virtual/interface method we can't determine whether + // or not the target is in the current module. Hence we replace the cancellation token for all calls. + + if (arguments is [.., { Type: { } lastArgumentType } lastArgument] && + (argumentRefKindsOpt.IsDefault || argumentRefKindsOpt is [.., RefKind.None]) && + lastArgumentType.Equals(_throwMethod.ContainingType, TypeCompareKind.ConsiderEverything)) + { + // The last argument is a CancellationToken. Replace it with the module-level token. + // Keep the previous expression so that side-effects are preserved. + + arguments = [.. arguments[0..^1], _factory.Sequence([lastArgument], _factory.ModuleCancellationToken())]; + } + else if (FindOverloadWithCancellationToken(method) is { } cancellableOverload) + { + // The method being invoked does not have a CancellationToken as the last parameter, but there is an overload that does. + // Invoke the other overload instead and pass in module-level token. + method = cancellableOverload; + arguments = [.. arguments, _factory.ModuleCancellationToken()]; + argumentRefKindsOpt = argumentRefKindsOpt.IsDefault ? default : [.. argumentRefKindsOpt, RefKind.None]; + } + } + + /// + /// Find an overload whose last parameter is and + /// the parameter types and ref kinds of all other parameters match those of . + /// + private MethodSymbol? FindOverloadWithCancellationToken(MethodSymbol method) + { + // Switching to a cancellable overload only applies to ordinary methods and constructors. + if (method.MethodKind is not (MethodKind.Ordinary or MethodKind.Constructor)) + { + return null; + } + + // Look for an overload of the definition with no type parameter substitutions. + var methodDefinition = method.OriginalDefinition; + + var methodsSetsRequiredMembers = methodDefinition.HasSetsRequiredMembers; + + foreach (var member in methodDefinition.ContainingType.GetMembers(method.Name)) + { + // If the member is the method being compiled, calling it could result in a recursion not present in the code previously. + // We can't guarantee the instrumentation won't result in infinite recursion, but we can avoid the trivial case. + if (member == _factory.TopLevelMethod?.OriginalDefinition) + { + continue; + } + + // It's unlikely that real-world APIs have overloads that differ in dynamic, + // but if they do avoid selecting them since their intended use might differ. + // + // Similarly, we also only consider overloads with the same visibility. + // We could potentially allow the visibility to differ, + // but we'd need to check if the overload is accessible at the call site. + + const TypeCompareKind TypeComparisonKind = TypeCompareKind.CLRSignatureCompareOptions & ~TypeCompareKind.IgnoreDynamic; + + if (member.IsStatic == methodDefinition.IsStatic && + member.MetadataVisibility == methodDefinition.MetadataVisibility && + member is MethodSymbol { Parameters: [.., { RefKind: RefKind.None, Type: { } lastParamType }] parametersWithCancellationToken } overload && + overload.Arity == methodDefinition.Arity && + methodDefinition.MethodKind == overload.MethodKind && + methodDefinition.Parameters.Length == parametersWithCancellationToken.Length - 1 && + lastParamType.Equals(_throwMethod.ContainingType, TypeCompareKind.ConsiderEverything) && + (!methodsSetsRequiredMembers || overload.HasSetsRequiredMembers)) + { + var typeMap = (methodDefinition.Arity > 0) ? new TypeMap(overload.TypeParameters, methodDefinition.TypeParameters) : null; + + if (MemberSignatureComparer.HaveSameParameterTypes( + methodDefinition.Parameters.AsSpan(), + typeMap1: null, + parametersWithCancellationToken.AsSpan(0, methodDefinition.Parameters.Length), + typeMap, + MemberSignatureComparer.RefKindCompareMode.ConsiderDifferences, + TypeComparisonKind) && + MemberSignatureComparer.HaveSameReturnTypes( + methodDefinition, + typeMap1: null, + overload, + typeMap, + TypeComparisonKind) && + MemberSignatureComparer.HaveSameConstraints( + methodDefinition.TypeParameters, + typeMap1: null, + overload.TypeParameters, + typeMap)) + { + var result = overload.AsMember(method.ContainingType); + return (result.Arity > 0) ? result.Construct(method.TypeArgumentsWithAnnotations) : result; + } + } + } + + return null; + } +} diff --git a/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs new file mode 100644 index 0000000000000..fc0ae9f838722 --- /dev/null +++ b/src/Compilers/CSharp/Portable/Lowering/Instrumentation/StackOverflowProbingInstrumenter.cs @@ -0,0 +1,83 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Symbols; +using Microsoft.CodeAnalysis.Shared.Collections; + +namespace Microsoft.CodeAnalysis.CSharp; + +/// +/// Implements instrumentation for . +/// +internal sealed class StackOverflowProbingInstrumenter( + MethodSymbol ensureStackMethod, + SyntheticBoundNodeFactory factory, + Instrumenter previous) + : CompoundInstrumenter(previous) +{ + private readonly MethodSymbol _ensureStackMethod = ensureStackMethod; + private readonly SyntheticBoundNodeFactory _factory = factory; + + protected override CompoundInstrumenter WithPreviousImpl(Instrumenter previous) + => new StackOverflowProbingInstrumenter( + _ensureStackMethod, + _factory, + previous); + + public static bool TryCreate( + MethodSymbol method, + SyntheticBoundNodeFactory factory, + Instrumenter previous, + [NotNullWhen(true)] out StackOverflowProbingInstrumenter? instrumenter) + { + instrumenter = null; + + // Do not instrument implicitly-declared methods or methods without bodies, except for constructors. + // Instrument implicit constructors in order to prevent stack overflow caused by member initializers. + if (method.MethodKind is not (MethodKind.Constructor or MethodKind.StaticConstructor) && + (method is { IsImplicitlyDeclared: true } || + method is SourceMemberMethodSymbol { Bodies: { arrowBody: null, blockBody: null } } and not SynthesizedSimpleProgramEntryPointSymbol)) + { + return false; + } + + var ensureStackMethod = factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack, isOptional: true); + if (ensureStackMethod is null) + { + return false; + } + + instrumenter = new StackOverflowProbingInstrumenter(ensureStackMethod, factory, previous); + return true; + } + + public override void InstrumentBlock(BoundBlock original, LocalRewriter rewriter, ref TemporaryArray additionalLocals, out BoundStatement? prologue, out BoundStatement? epilogue, out BoundBlockInstrumentation? instrumentation) + { + base.InstrumentBlock(original, rewriter, ref additionalLocals, out prologue, out epilogue, out instrumentation); + + var isMethodBody = rewriter.CurrentMethodBody == original; + var isLambdaBody = rewriter.CurrentLambdaBody == original; + + // Don't instrument blocks that are not a method or lambda body + if (!isMethodBody && !isLambdaBody) + { + return; + } + + Debug.Assert(_factory.TopLevelMethod is not null); + Debug.Assert(_factory.CurrentFunction is not null); + + // static constructors can only be invoked once, so there is no need to probe: + if (isMethodBody && _factory.TopLevelMethod.MethodKind == MethodKind.StaticConstructor) + { + return; + } + + instrumentation = _factory.CombineInstrumentation( + instrumentation, + prologue: _factory.ExpressionStatement(_factory.Call(receiver: null, _ensureStackMethod))); + } +} diff --git a/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorMethodToStateMachineRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorMethodToStateMachineRewriter.cs index 6b4d5e646a5e0..c753767d55e29 100644 --- a/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorMethodToStateMachineRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/IteratorRewriter/IteratorMethodToStateMachineRewriter.cs @@ -146,15 +146,7 @@ internal void GenerateMoveNextAndDispose(BoundStatement body, SynthesizedImpleme newBody = F.Fault((BoundBlock)newBody, faultBlock); } - newBody = F.SequencePoint(body.Syntax, HandleReturn(newBody)); - - if (instrumentation != null) - { - newBody = F.Block( - ImmutableArray.Create(instrumentation.Local), - instrumentation.Prologue, - F.Try(F.Block(newBody), ImmutableArray.Empty, F.Block(instrumentation.Epilogue))); - } + newBody = F.Instrument(F.SequencePoint(body.Syntax, HandleReturn(newBody)), instrumentation); F.CloseMethod(newBody); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs index c7fda547b4e9b..3cdb744a7fbec 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs @@ -123,6 +123,20 @@ public static BoundStatement Rewrite( instrumenter = codeCoverageInstrumenter; } + StackOverflowProbingInstrumenter? stackOverflowProbingInstrumenter = null; + if (instrumentation.Kinds.Contains(InstrumentationKind.StackOverflowProbing) && + StackOverflowProbingInstrumenter.TryCreate(method, factory, instrumenter, out stackOverflowProbingInstrumenter)) + { + instrumenter = stackOverflowProbingInstrumenter; + } + + ModuleCancellationInstrumenter? moduleCancellationInstrumenter = null; + if (instrumentation.Kinds.Contains(InstrumentationKind.ModuleCancellation) && + ModuleCancellationInstrumenter.TryCreate(method, factory, instrumenter, out moduleCancellationInstrumenter)) + { + instrumenter = moduleCancellationInstrumenter; + } + instrumentationState.Instrumenter = DebugInfoInjector.Create(instrumenter); // We don't want IL to differ based upon whether we write the PDB to a file/stream or not. diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs index 7d39d3d00df62..309da545ab19d 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Call.cs @@ -404,6 +404,12 @@ BoundExpression visitArgumentsAndFinishRewrite(BoundCall node, BoundExpression? invokedAsExtensionMethod); InterceptCallAndAdjustArguments(ref method, ref rewrittenReceiver, ref rewrittenArguments, ref argRefKindsOpt, invokedAsExtensionMethod, node.InterceptableNameSyntax); + + if (Instrument) + { + Instrumenter.InterceptCallAndAdjustArguments(ref method, ref rewrittenReceiver, ref rewrittenArguments, ref argRefKindsOpt); + } + var rewrittenCall = MakeCall(node, node.Syntax, rewrittenReceiver, method, rewrittenArguments, argRefKindsOpt, node.ResultKind, node.Type, temps.ToImmutableAndFree()); if (Instrument) diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs index 402d11f4a08a6..13f59f7b5e44a 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectCreationExpression.cs @@ -32,6 +32,8 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre { Debug.Assert(node != null); + var constructor = node.Constructor; + // Rewrite the arguments. // NOTE: We may need additional argument rewriting such as // re-ordering arguments based on argsToParamsOpt map, etc. @@ -44,7 +46,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre ref receiverDiscard, captureReceiverMode: ReceiverCaptureMode.Default, node.Arguments, - node.Constructor, + constructor, node.ArgsToParamsOpt, argumentRefKindsOpt, storesOpt: null, @@ -56,7 +58,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre // such as re-ordering arguments based on argsToParamsOpt map, etc. rewrittenArguments = MakeArguments( rewrittenArguments, - node.Constructor, + constructor, node.Expanded, node.ArgsToParamsOpt, ref argumentRefKindsOpt, @@ -72,7 +74,7 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre throw ExceptionUtilities.UnexpectedValue(temps.Length); } - rewrittenObjectCreation = node.UpdateArgumentsAndInitializer(rewrittenArguments, argumentRefKindsOpt, MakeObjectCreationInitializerForExpressionTree(node.InitializerExpressionOpt), changeTypeOpt: node.Constructor.ContainingType); + rewrittenObjectCreation = node.Update(constructor, rewrittenArguments, argumentRefKindsOpt, MakeObjectCreationInitializerForExpressionTree(node.InitializerExpressionOpt), changeTypeOpt: constructor.ContainingType); if (node.Type.IsInterfaceType()) { @@ -83,10 +85,16 @@ public override BoundNode VisitObjectCreationExpression(BoundObjectCreationExpre return rewrittenObjectCreation; } - rewrittenObjectCreation = node.UpdateArgumentsAndInitializer(rewrittenArguments, argumentRefKindsOpt, newInitializerExpression: null, changeTypeOpt: node.Constructor.ContainingType); + if (Instrument) + { + BoundExpression? receiver = null; + Instrumenter.InterceptCallAndAdjustArguments(ref constructor, ref receiver, ref rewrittenArguments, ref argumentRefKindsOpt); + } + + rewrittenObjectCreation = node.Update(constructor, rewrittenArguments, argumentRefKindsOpt, newInitializerExpression: null, changeTypeOpt: constructor.ContainingType); // replace "new S()" with a default struct ctor with "default(S)" - if (node.Constructor.IsDefaultValueTypeConstructor()) + if (constructor.IsDefaultValueTypeConstructor()) { rewrittenObjectCreation = new BoundDefaultExpression(rewrittenObjectCreation.Syntax, rewrittenObjectCreation.Type!); } diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs index 1fe7f82f684bd..29a8bf696e4a3 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_ObjectOrCollectionInitializerExpression.cs @@ -201,6 +201,11 @@ private BoundExpression MakeDynamicCollectionInitializer(BoundExpression rewritt return initializer.Update(addMethod, rewrittenArguments, rewrittenReceiver, expanded: false, argsToParamsOpt: default, defaultArguments: default, invokedAsExtensionMethod: false, initializer.ResultKind, rewrittenType); } + if (Instrument) + { + Instrumenter.InterceptCallAndAdjustArguments(ref addMethod, ref rewrittenReceiver, ref rewrittenArguments, ref argumentRefKindsOpt); + } + return MakeCall(null, syntax, rewrittenReceiver, addMethod, rewrittenArguments, argumentRefKindsOpt, initializer.ResultKind, addMethod.ReturnType, temps.ToImmutableAndFree()); } diff --git a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs index 63ca71c9390ef..bcb6ad11205ea 100644 --- a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs +++ b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; @@ -13,6 +14,7 @@ using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; +using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; @@ -508,6 +510,51 @@ public BoundStatementList StatementList(BoundStatement first, BoundStatement sec return new BoundStatementList(Syntax, ImmutableArray.Create(first, second)) { WasCompilerGenerated = true }; } + [return: NotNullIfNotNull(nameof(first)), NotNullIfNotNull(nameof(second))] + public BoundStatement? Concat(BoundStatement? first, BoundStatement? second) + => (first == null) ? second : (second == null) ? first : StatementList(first, second); + + public BoundBlockInstrumentation CombineInstrumentation(BoundBlockInstrumentation? innerInstrumentation = null, LocalSymbol? local = null, BoundStatement? prologue = null, BoundStatement? epilogue = null) + { + return (innerInstrumentation != null) + ? new BoundBlockInstrumentation( + innerInstrumentation.Syntax, + (local != null) ? innerInstrumentation.Locals.Add(local) : innerInstrumentation.Locals, + (prologue != null) ? Concat(prologue, innerInstrumentation.Prologue) : innerInstrumentation.Prologue, + (epilogue != null) ? Concat(innerInstrumentation.Epilogue, epilogue) : innerInstrumentation.Epilogue) + : new BoundBlockInstrumentation( + Syntax, + OneOrMany.OneOrNone(local), + prologue, + epilogue); + } + + public BoundStatement Instrument(BoundStatement statement, BoundBlockInstrumentation? instrumentation) + { + if (instrumentation == null) + { + return statement; + } + + var statements = new TemporaryArray(); + + if (instrumentation.Prologue != null) + { + statements.Add(instrumentation.Prologue); + } + + if (instrumentation.Epilogue != null) + { + statements.Add(Try(Block(statement), ImmutableArray.Empty, Block(instrumentation.Epilogue))); + } + else + { + statements.Add(statement); + } + + return Block(instrumentation.Locals.ToImmutable(), statements.ToImmutableAndClear()); + } + public BoundReturnStatement Return(BoundExpression? expression = null) { Debug.Assert(CurrentFunction is { }); @@ -1304,6 +1351,12 @@ public BoundExpression InstrumentationPayloadRoot(int analysisKind, TypeSymbol p return new BoundInstrumentationPayloadRoot(Syntax, analysisKind, payloadType) { WasCompilerGenerated = true }; } + public BoundExpression ThrowIfModuleCancellationRequested() + => new BoundThrowIfModuleCancellationRequested(Syntax, SpecialType(CodeAnalysis.SpecialType.System_Void)) { WasCompilerGenerated = true }; + + public BoundExpression ModuleCancellationToken() + => new ModuleCancellationTokenExpression(Syntax, WellKnownType(CodeAnalysis.WellKnownType.System_Threading_CancellationToken)) { WasCompilerGenerated = true }; + public BoundExpression MaximumMethodDefIndex() { return new BoundMaximumMethodDefIndex( diff --git a/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs b/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs index 934982a741776..e0e96d43a6888 100644 --- a/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs +++ b/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs @@ -2,8 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#nullable disable - using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -411,14 +409,14 @@ private MemberSignatureComparer( #region IEqualityComparer Members - public bool Equals(Symbol member1, Symbol member2) + public bool Equals(Symbol? member1, Symbol? member2) { if (ReferenceEquals(member1, member2)) { return true; } - if ((object)member1 == null || (object)member2 == null || member1.Kind != member2.Kind) + if (member1 is null || member2 is null || member1.Kind != member2.Kind) { return false; } @@ -452,15 +450,15 @@ public bool Equals(Symbol member1, Symbol member2) return false; } - TypeMap typeMap1 = GetTypeMap(member1); - TypeMap typeMap2 = GetTypeMap(member2); + TypeMap? typeMap1 = GetTypeMap(member1); + TypeMap? typeMap2 = GetTypeMap(member2); if (_considerReturnType && !HaveSameReturnTypes(member1, typeMap1, member2, typeMap2, _typeComparison)) { return false; } - if (member1.GetParameterCount() > 0 && !HaveSameParameterTypes(member1.GetParameters(), typeMap1, member2.GetParameters(), typeMap2, + if (member1.GetParameterCount() > 0 && !HaveSameParameterTypes(member1.GetParameters().AsSpan(), typeMap1, member2.GetParameters().AsSpan(), typeMap2, _refKindCompareMode, _typeComparison)) { return false; @@ -524,10 +522,10 @@ public bool Equals(Symbol member1, Symbol member2) return !_considerTypeConstraints || HaveSameConstraints(member1, typeMap1, member2, typeMap2); } - public int GetHashCode(Symbol member) + public int GetHashCode(Symbol? member) { int hash = 1; - if ((object)member != null) + if (member is not null) { hash = Hash.Combine((int)member.Kind, hash); @@ -556,7 +554,7 @@ public int GetHashCode(Symbol member) #endregion - private static bool HaveSameReturnTypes(Symbol member1, TypeMap typeMap1, Symbol member2, TypeMap typeMap2, TypeCompareKind typeComparison) + public static bool HaveSameReturnTypes(Symbol member1, TypeMap? typeMap1, Symbol member2, TypeMap? typeMap2, TypeCompareKind typeComparison) { RefKind refKind1; TypeWithAnnotations unsubstitutedReturnType1; @@ -607,7 +605,7 @@ private static bool HaveSameReturnTypes(Symbol member1, TypeMap typeMap1, Symbol return true; } - private static TypeMap GetTypeMap(Symbol member) + private static TypeMap? GetTypeMap(Symbol member) { var typeParameters = member.GetMemberTypeParameters(); return typeParameters.IsEmpty ? @@ -618,7 +616,7 @@ private static TypeMap GetTypeMap(Symbol member) true); } - private static bool HaveSameConstraints(Symbol member1, TypeMap typeMap1, Symbol member2, TypeMap typeMap2) + private static bool HaveSameConstraints(Symbol member1, TypeMap? typeMap1, Symbol member2, TypeMap? typeMap2) { Debug.Assert(member1.GetMemberArity() == member2.GetMemberArity()); @@ -633,7 +631,7 @@ private static bool HaveSameConstraints(Symbol member1, TypeMap typeMap1, Symbol return HaveSameConstraints(typeParameters1, typeMap1, typeParameters2, typeMap2); } - public static bool HaveSameConstraints(ImmutableArray typeParameters1, TypeMap typeMap1, ImmutableArray typeParameters2, TypeMap typeMap2) + public static bool HaveSameConstraints(ImmutableArray typeParameters1, TypeMap? typeMap1, ImmutableArray typeParameters2, TypeMap? typeMap2) { Debug.Assert(typeParameters1.Length == typeParameters2.Length); @@ -649,7 +647,7 @@ public static bool HaveSameConstraints(ImmutableArray typeP return true; } - public static bool HaveSameConstraints(TypeParameterSymbol typeParameter1, TypeMap typeMap1, TypeParameterSymbol typeParameter2, TypeMap typeMap2) + public static bool HaveSameConstraints(TypeParameterSymbol typeParameter1, TypeMap? typeMap1, TypeParameterSymbol typeParameter2, TypeMap? typeMap2) { // Spec 13.4.3: Implementation of generic methods. @@ -665,7 +663,7 @@ public static bool HaveSameConstraints(TypeParameterSymbol typeParameter1, TypeM return HaveSameTypeConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2, SymbolEqualityComparer.IgnoringDynamicTupleNamesAndNullability); } - private static bool HaveSameTypeConstraints(TypeParameterSymbol typeParameter1, TypeMap typeMap1, TypeParameterSymbol typeParameter2, TypeMap typeMap2, IEqualityComparer comparer) + private static bool HaveSameTypeConstraints(TypeParameterSymbol typeParameter1, TypeMap? typeMap1, TypeParameterSymbol typeParameter2, TypeMap? typeMap2, IEqualityComparer comparer) { // Check that constraintTypes1 is a subset of constraintTypes2 and // also that constraintTypes2 is a subset of constraintTypes1 @@ -742,16 +740,21 @@ private static bool AreConstraintTypesSubset(HashSet constraintTypes return true; } - private static void SubstituteConstraintTypes(ImmutableArray types, TypeMap typeMap, HashSet result) + private static void SubstituteConstraintTypes(ImmutableArray types, TypeMap? typeMap, HashSet result) { foreach (var type in types) { - result.Add(typeMap.SubstituteType(type).Type); + result.Add(SubstituteType(typeMap, type).Type); } } - private static bool HaveSameParameterTypes(ImmutableArray params1, TypeMap typeMap1, ImmutableArray params2, TypeMap typeMap2, - RefKindCompareMode refKindCompareMode, TypeCompareKind typeComparison) + internal static bool HaveSameParameterTypes( + ReadOnlySpan params1, + TypeMap? typeMap1, + ReadOnlySpan params2, + TypeMap? typeMap2, + RefKindCompareMode refKindCompareMode, + TypeCompareKind typeComparison) { Debug.Assert(params1.Length == params2.Length); @@ -814,18 +817,18 @@ static bool areRefKindsCompatible(RefKindCompareMode refKindCompareMode, RefKind } } - private static TypeWithAnnotations SubstituteType(TypeMap typeMap, TypeWithAnnotations typeSymbol) + private static TypeWithAnnotations SubstituteType(TypeMap? typeMap, TypeWithAnnotations typeSymbol) { return typeMap == null ? typeSymbol : typeSymbol.SubstituteType(typeMap); } - private static bool HaveSameCustomModifiers(ImmutableArray customModifiers1, TypeMap typeMap1, ImmutableArray customModifiers2, TypeMap typeMap2) + private static bool HaveSameCustomModifiers(ImmutableArray customModifiers1, TypeMap? typeMap1, ImmutableArray customModifiers2, TypeMap? typeMap2) { // the runtime compares custom modifiers using (effectively) SequenceEqual return SubstituteModifiers(typeMap1, customModifiers1).SequenceEqual(SubstituteModifiers(typeMap2, customModifiers2)); } - private static ImmutableArray SubstituteModifiers(TypeMap typeMap, ImmutableArray customModifiers) + private static ImmutableArray SubstituteModifiers(TypeMap? typeMap, ImmutableArray customModifiers) { return typeMap == null ? customModifiers : typeMap.SubstituteCustomModifiers(customModifiers); } @@ -869,7 +872,7 @@ internal static bool ConsideringTupleNamesCreatesDifference(Symbol member1, Symb } [Flags] - private enum RefKindCompareMode + internal enum RefKindCompareMode { /// /// Ref parameter modifiers are ignored. diff --git a/src/Compilers/CSharp/Test/Emit2/Emit/LocalStateTracing/LocalStateTracingTests.cs b/src/Compilers/CSharp/Test/Emit2/Emit/LocalStateTracing/LocalStateTracingTests.cs index b7561d7939aaa..4315771543ce5 100644 --- a/src/Compilers/CSharp/Test/Emit2/Emit/LocalStateTracing/LocalStateTracingTests.cs +++ b/src/Compilers/CSharp/Test/Emit2/Emit/LocalStateTracing/LocalStateTracingTests.cs @@ -25,6 +25,7 @@ public class LocalStateTracingTests : CSharpTestBase // arrays (stloc, stelem), // collections, anonymous types, tuples // LogLocalStoreUnmanaged with local/parameter typed to a generic parameter + // Primary constructor with field initializers private static readonly EmitOptions s_emitOptions = GetEmitOptions(InstrumentationKindExtensions.LocalStateTracing); @@ -211,7 +212,7 @@ private static void AssertInstrumented(CompilationVerifier verifier, string qual } [Fact] - public void Composition_LocalStateTracing_TestCoverage() + public void Composition_AllInstrumentations() { var source = WithHelpers(@" class C @@ -227,93 +228,111 @@ static void Main(string[] p) var verifier = CompileAndVerify( source, options: TestOptions.UnsafeDebugExe, - emitOptions: GetEmitOptions(InstrumentationKindExtensions.LocalStateTracing, InstrumentationKind.TestCoverage), + emitOptions: GetEmitOptions( + InstrumentationKindExtensions.LocalStateTracing, + InstrumentationKind.TestCoverage, + InstrumentationKind.ModuleCancellation, + InstrumentationKind.StackOverflowProbing), verify: s_verification with { - ILVerifyMessage = s_verification.ILVerifyMessage + Environment.NewLine + """ - [CreatePayload]: Expected numeric type on the stack. { Offset = 0xf, Found = address of '[System.Runtime]System.Guid' } - [CreatePayload]: Expected numeric type on the stack. { Offset = 0xf, Found = address of '[System.Runtime]System.Guid' } + ILVerifyMessage = """ + [LogMethodEntry]: Return type is ByRef, TypedReference, ArgHandle, or ArgIterator. { Offset = 0x19 } + [LogLambdaEntry]: Return type is ByRef, TypedReference, ArgHandle, or ArgIterator. { Offset = 0x19 } + [LogStateMachineMethodEntry]: Return type is ByRef, TypedReference, ArgHandle, or ArgIterator. { Offset = 0x18 } + [LogStateMachineLambdaEntry]: Return type is ByRef, TypedReference, ArgHandle, or ArgIterator. { Offset = 0x18 } + [Entry]: Return type is ByRef, TypedReference, ArgHandle, or ArgIterator. { Offset = 0xcc } + [MemoryToString]: Unmanaged pointers are not a verifiable type. { Offset = 0x15 } + [LogLocalStore]: Unmanaged pointers are not a verifiable type. { Offset = 0x11 } + [LogLocalStoreUnmanaged]: Unmanaged pointers are not a verifiable type. { Offset = 0x11 } + [LogParameterStore]: Unmanaged pointers are not a verifiable type. { Offset = 0x11 } + [LogParameterStoreUnmanaged]: Unmanaged pointers are not a verifiable type. { Offset = 0x11 } + [CreatePayload]: Expected numeric type on the stack. { Offset = 0x1f, Found = address of '[System.Runtime]System.Guid' } + [CreatePayload]: Expected numeric type on the stack. { Offset = 0x1f, Found = address of '[System.Runtime]System.Guid' } """ }, targetFramework: s_targetFramework); verifier.VerifyMethodBody("C.Main", @" { - // Code size 128 (0x80) + // Code size 144 (0x90) .maxstack 5 .locals init (Microsoft.CodeAnalysis.Runtime.LocalStoreTracker V_0, string[] V_1, //a bool[] V_2) // sequence point: - IL_0000: ldtoken ""void C.Main(string[])"" - IL_0005: call ""Microsoft.CodeAnalysis.Runtime.LocalStoreTracker Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogMethodEntry(int)"" - IL_000a: stloc.0 + IL_0000: ldsflda ""System.Threading.CancellationToken .ModuleCancellationToken"" + IL_0005: call ""void System.Threading.CancellationToken.ThrowIfCancellationRequested()"" + IL_000a: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" + IL_000f: nop + IL_0010: ldtoken ""void C.Main(string[])"" + IL_0015: call ""Microsoft.CodeAnalysis.Runtime.LocalStoreTracker Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogMethodEntry(int)"" + IL_001a: stloc.0 .try { // sequence point: { - IL_000b: ldsfld ""bool[][] .PayloadRoot0"" - IL_0010: ldtoken ""void C.Main(string[])"" - IL_0015: ldelem.ref - IL_0016: stloc.2 - IL_0017: ldloc.2 - IL_0018: brtrue.s IL_003f - IL_001a: ldsfld ""System.Guid .MVID"" - IL_001f: ldtoken ""void C.Main(string[])"" - IL_0024: ldtoken Source Document 0 - IL_0029: ldsfld ""bool[][] .PayloadRoot0"" - IL_002e: ldtoken ""void C.Main(string[])"" - IL_0033: ldelema ""bool[]"" - IL_0038: ldc.i4.3 - IL_0039: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" - IL_003e: stloc.2 - IL_003f: ldloc.2 - IL_0040: ldc.i4.0 - IL_0041: ldc.i4.1 - IL_0042: stelem.i1 - IL_0043: ldloca.s V_0 - IL_0045: ldarg.0 - IL_0046: ldc.i4.0 - IL_0047: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogParameterStore(object, int)"" - IL_004c: nop - // sequence point: string[] a = p = null; - IL_004d: ldloc.2 - IL_004e: ldc.i4.1 - IL_004f: ldc.i4.1 - IL_0050: stelem.i1 - IL_0051: ldloca.s V_0 + IL_001b: ldsfld ""bool[][] .PayloadRoot0"" + IL_0020: ldtoken ""void C.Main(string[])"" + IL_0025: ldelem.ref + IL_0026: stloc.2 + IL_0027: ldloc.2 + IL_0028: brtrue.s IL_004f + IL_002a: ldsfld ""System.Guid .MVID"" + IL_002f: ldtoken ""void C.Main(string[])"" + IL_0034: ldtoken Source Document 0 + IL_0039: ldsfld ""bool[][] .PayloadRoot0"" + IL_003e: ldtoken ""void C.Main(string[])"" + IL_0043: ldelema ""bool[]"" + IL_0048: ldc.i4.3 + IL_0049: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" + IL_004e: stloc.2 + IL_004f: ldloc.2 + IL_0050: ldc.i4.0 + IL_0051: ldc.i4.1 + IL_0052: stelem.i1 IL_0053: ldloca.s V_0 - IL_0055: ldnull - IL_0056: dup - IL_0057: starg.s V_0 - IL_0059: ldc.i4.0 - IL_005a: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogParameterStore(object, int)"" - IL_005f: nop - IL_0060: ldarg.0 - IL_0061: dup - IL_0062: stloc.1 - IL_0063: ldc.i4.1 - IL_0064: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogLocalStore(object, int)"" - IL_0069: nop + IL_0055: ldarg.0 + IL_0056: ldc.i4.0 + IL_0057: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogParameterStore(object, int)"" + IL_005c: nop + // sequence point: string[] a = p = null; + IL_005d: ldloc.2 + IL_005e: ldc.i4.1 + IL_005f: ldc.i4.1 + IL_0060: stelem.i1 + IL_0061: ldloca.s V_0 + IL_0063: ldloca.s V_0 + IL_0065: ldnull + IL_0066: dup + IL_0067: starg.s V_0 + IL_0069: ldc.i4.0 + IL_006a: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogParameterStore(object, int)"" + IL_006f: nop + IL_0070: ldarg.0 + IL_0071: dup + IL_0072: stloc.1 + IL_0073: ldc.i4.1 + IL_0074: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogLocalStore(object, int)"" + IL_0079: nop // sequence point: Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); - IL_006a: ldloc.2 - IL_006b: ldc.i4.2 - IL_006c: ldc.i4.1 - IL_006d: stelem.i1 - IL_006e: call ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" - IL_0073: nop + IL_007a: ldloc.2 + IL_007b: ldc.i4.2 + IL_007c: ldc.i4.1 + IL_007d: stelem.i1 + IL_007e: call ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" + IL_0083: nop // sequence point: } - IL_0074: leave.s IL_007f + IL_0084: leave.s IL_008f } finally { // sequence point: - IL_0076: ldloca.s V_0 - IL_0078: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogReturn()"" - IL_007d: nop - IL_007e: endfinally + IL_0086: ldloca.s V_0 + IL_0088: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogReturn()"" + IL_008d: nop + IL_008e: endfinally } // sequence point: } - IL_007f: ret + IL_008f: ret } "); } @@ -2925,7 +2944,7 @@ .locals init (Microsoft.CodeAnalysis.Runtime.LocalStoreTracker V_0, } [Fact] - public void Initializers() + public void Initializers_NoConstructorBody_Static() { var source = WithHelpers(@" C.F(out var _); @@ -3111,6 +3130,81 @@ .locals init (Microsoft.CodeAnalysis.Runtime.LocalStoreTracker V_0, "); } + [Fact] + public void Initializers_NoContructorBody() + { + var source = WithHelpers(@" +var _ = new C(); + +class C +{ + int A = F(out var x) + (x = 2); + + public static int F(out int a) => a = 1; +} +"); + var verifier = CompileAndVerify(source, expectedOutput: @" +
$: Entered +
$: P'args'[0] = System.String[] +.ctor: Entered +F: Entered +F: P'a'[0] = 1 +F: Returned +.ctor: L1 = 1 +.ctor: L1 = 2 +.ctor: Returned +
$: L1 = C +
$: Returned +"); + verifier.VerifyMethodBody("C..ctor", @" +{ + // Code size 67 (0x43) + .maxstack 5 + .locals init (Microsoft.CodeAnalysis.Runtime.LocalStoreTracker V_0, + int V_1) //x + // sequence point: + IL_0000: ldtoken ""C..ctor()"" + IL_0005: call ""Microsoft.CodeAnalysis.Runtime.LocalStoreTracker Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogMethodEntry(int)"" + IL_000a: stloc.0 + .try + { + // sequence point: int A = F(out var x) + (x = 2); + IL_000b: ldarg.0 + IL_000c: ldloca.s V_1 + IL_000e: call ""int C.F(out int)"" + IL_0013: ldloca.s V_0 + IL_0015: ldloc.1 + IL_0016: ldc.i4.1 + IL_0017: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogLocalStore(uint, int)"" + IL_001c: nop + IL_001d: ldloca.s V_0 + IL_001f: ldc.i4.2 + IL_0020: dup + IL_0021: stloc.1 + IL_0022: ldc.i4.1 + IL_0023: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogLocalStore(uint, int)"" + IL_0028: nop + IL_0029: ldloc.1 + IL_002a: add + IL_002b: stfld ""int C.A"" + IL_0030: ldarg.0 + IL_0031: call ""object..ctor()"" + IL_0036: nop + IL_0037: leave.s IL_0042 + } + finally + { + // sequence point: + IL_0039: ldloca.s V_0 + IL_003b: call ""void Microsoft.CodeAnalysis.Runtime.LocalStoreTracker.LogReturn()"" + IL_0040: nop + IL_0041: endfinally + } + // sequence point: + IL_0042: ret +}"); + } + [Fact] public void Constructors() { diff --git a/src/Compilers/CSharp/Test/Emit2/Emit/RuntimeProbing/ModuleCancellationTests.cs b/src/Compilers/CSharp/Test/Emit2/Emit/RuntimeProbing/ModuleCancellationTests.cs new file mode 100644 index 0000000000000..26c01cb91bcdd --- /dev/null +++ b/src/Compilers/CSharp/Test/Emit2/Emit/RuntimeProbing/ModuleCancellationTests.cs @@ -0,0 +1,2786 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.CSharp.UnitTests; + +public sealed class ModuleCancellationTests : CSharpTestBase +{ +#if NET + const string NativeIntDisplay = "nint"; +#else + const string NativeIntDisplay = "System.IntPtr"; +#endif + + private static readonly EmitOptions s_emitOptions = EmitOptions.Default.WithInstrumentationKinds([InstrumentationKind.ModuleCancellation]); + + private CompilationVerifier CompileAndVerify(string source, string? expectedOutput = null, CSharpCompilationOptions? options = null, Verification? verification = null) + => CompileAndVerify( + source, + options: options ?? (expectedOutput != null ? TestOptions.UnsafeDebugExe : TestOptions.UnsafeDebugDll), + emitOptions: s_emitOptions, + verify: verification ?? Verification.Passes, + targetFramework: TargetFramework.NetLatest, + expectedOutput: expectedOutput); + + private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName) + => AssertNotInstrumented(verifier, qualifiedMethodName, ".ModuleCancellationToken"); + + private static void AssertNotInstrumentedWithTokenLoad(CompilationVerifier verifier, string qualifiedMethodName) + => AssertNotInstrumented(verifier, qualifiedMethodName, @"ldsfld ""System.Threading.CancellationToken .ModuleCancellationToken"""); + + private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName, string instrumentationIndicator) + { + var il = verifier.VisualizeIL(qualifiedMethodName); + var isInstrumented = string.Join(" ", il.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Contains(instrumentationIndicator); + + Assert.False(isInstrumented, + $"Method '{qualifiedMethodName}' should not be instrumented with '{instrumentationIndicator}'. Actual IL:{Environment.NewLine}{il}"); + } + + [Fact] + public void LambdaAndLocalFunction() + { + var source = """ + using System; + + class C + { + public void F(Func a) + { + void L() + { + L(); + } + + F(() => 1); + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 51 (0x33) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + IL_000b: nop + // sequence point: F(() => 1); + IL_000c: ldarg.0 + IL_000d: ldsfld "System.Func C.<>c.<>9__0_1" + IL_0012: dup + IL_0013: brtrue.s IL_002c + IL_0015: pop + IL_0016: ldsfld "C.<>c C.<>c.<>9" + IL_001b: ldftn "int C.<>c.b__0_1()" + IL_0021: newobj "System.Func..ctor(object, {{NativeIntDisplay}})" + IL_0026: dup + IL_0027: stsfld "System.Func C.<>c.<>9__0_1" + IL_002c: call "void C.F(System.Func)" + IL_0031: nop + // sequence point: } + IL_0032: ret + } + """); + + verifier.VerifyMethodBody("C.g__L|0_0", """ + { + // Code size 18 (0x12) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: L(); + IL_000b: call "void C.g__L|0_0()" + IL_0010: nop + // sequence point: } + IL_0011: ret + } + """); + + verifier.VerifyMethodBody("C.<>c.b__0_1", """ + { + // Code size 12 (0xc) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: 1 + IL_000a: ldc.i4.1 + IL_000b: ret + } + """); + } + + [Fact] + public void LambdaAndLocalFunction_TopLevel() + { + var source = """ + using System; + + var b = true; + for(;b;) F(); + + void F() + { + while(b) { } + } + """; + + var verifier = CompileAndVerify(source, options: TestOptions.DebugExe); + + verifier.VerifyMethodBody("", """ + { + // Code size 60 (0x3c) + .maxstack 2 + .locals init (Program.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 + bool V_1) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: var b = true; + IL_000a: ldloca.s V_0 + IL_000c: ldc.i4.1 + IL_000d: stfld "bool Program.<>c__DisplayClass0_0.b" + // sequence point: + IL_0012: br.s IL_001c + // sequence point: F(); + IL_0014: ldloca.s V_0 + IL_0016: call "void Program.<
$>g__F|0_0(ref Program.<>c__DisplayClass0_0)" + IL_001b: nop + // sequence point: b + IL_001c: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0021: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0026: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_002b: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0030: ldloc.0 + IL_0031: ldfld "bool Program.<>c__DisplayClass0_0.b" + IL_0036: stloc.1 + // sequence point: + IL_0037: ldloc.1 + IL_0038: brtrue.s IL_0014 + IL_003a: nop + IL_003b: ret + } + """); + + verifier.VerifyMethodBody("Program.<
$>g__F|0_0", """ + { + // Code size 36 (0x24) + .maxstack 1 + .locals init (bool V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: + IL_000b: br.s IL_000f + // sequence point: { + IL_000d: nop + // sequence point: } + IL_000e: nop + // sequence point: while(b) + IL_000f: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0014: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0019: ldarg.0 + IL_001a: ldfld "bool Program.<>c__DisplayClass0_0.b" + IL_001f: stloc.0 + // sequence point: + IL_0020: ldloc.0 + IL_0021: brtrue.s IL_000d + // sequence point: } + IL_0023: ret + } + """); + } + + [Fact] + public void StaticConstructor_Explicit() + { + var source = """ + using System; + + class C + { + static bool b = true; + + static C() + { + while (b) + { + } + } + } + """; + + var verifier = CompileAndVerify(source); + + // no preamble but while loop is instrumented: + verifier.VerifyMethodBody("C..cctor", """ + { + // Code size 31 (0x1f) + .maxstack 1 + .locals init (bool V_0) + // sequence point: { + IL_0000: nop + // sequence point: static bool b = true; + IL_0001: ldc.i4.1 + IL_0002: stsfld "bool C.b" + // sequence point: + IL_0007: br.s IL_000b + // sequence point: { + IL_0009: nop + // sequence point: } + IL_000a: nop + // sequence point: while (b) + IL_000b: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0010: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0015: ldsfld "bool C.b" + IL_001a: stloc.0 + // sequence point: + IL_001b: ldloc.0 + IL_001c: brtrue.s IL_0009 + // sequence point: } + IL_001e: ret + } + """); + } + + [Fact] + public void StaticConstructor_Implicit() + { + var source = """ + using System; + + class C + { + static Action s_f = b => { while (b) {} }; + } + """; + + var verifier = CompileAndVerify(source); + + // no probe since static constructor can only be invoked once: + AssertNotInstrumented(verifier, "C..cctor"); + + // lambda should be instrumented + verifier.VerifyMethodBody("C.<>c.<.cctor>b__2_0", """ + { + // Code size 31 (0x1f) + .maxstack 1 + .locals init (bool V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: + IL_000b: br.s IL_000f + // sequence point: { + IL_000d: nop + // sequence point: } + IL_000e: nop + // sequence point: while (b) + IL_000f: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0014: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0019: ldarg.1 + IL_001a: stloc.0 + // sequence point: + IL_001b: ldloc.0 + IL_001c: brtrue.s IL_000d + // sequence point: } + IL_001e: ret + } + """); + } + + [Fact] + public void InstanceConstructor_Implicit() + { + var source = """ + class B + { + C C = new(); + } + + class C : B + { + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("B..ctor", """ + { + // Code size 29 (0x1d) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: C C = new(); + IL_000a: ldarg.0 + IL_000b: newobj "C..ctor()" + IL_0010: stfld "C B.C" + IL_0015: ldarg.0 + IL_0016: call "object..ctor()" + IL_001b: nop + IL_001c: ret + } + """); + + verifier.VerifyMethodBody("C..ctor", """ + { + // Code size 18 (0x12) + .maxstack 1 + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_000a: ldarg.0 + IL_000b: call "B..ctor()" + IL_0010: nop + IL_0011: ret + } + """); + } + + [Fact] + public void InstanceConstructors_Explicit() + { + var source = """ + class B(int a) + { + } + + class C(int a) : B(a) + { + C c = new C(1); + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("B..ctor", """ + { + // Code size 18 (0x12) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: B(int a) + IL_000a: ldarg.0 + IL_000b: call "object..ctor()" + IL_0010: nop + IL_0011: ret + } + """); + + verifier.VerifyMethodBody("C..ctor", """ + { + // Code size 31 (0x1f) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: C c = new C(1); + IL_000a: ldarg.0 + IL_000b: ldc.i4.1 + IL_000c: newobj "C..ctor(int)" + IL_0011: stfld "C C.c" + // sequence point: B(a) + IL_0016: ldarg.0 + IL_0017: ldarg.1 + IL_0018: call "B..ctor(int)" + IL_001d: nop + IL_001e: ret + } + """); + } + + [Fact] + public void PropertyAccessors_Auto() + { + var source = """ + class C + { + int P { get; set; } + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.P.get"); + AssertNotInstrumented(verifier, "C.P.set"); + } + + [Fact] + public void PropertyAccessors_Explicit() + { + var source = """ + class C + { + int P { get { return P; } set { P = value; } } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.P.get", """ + { + // Code size 22 (0x16) + .maxstack 1 + .locals init (int V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: return P; + IL_000b: ldarg.0 + IL_000c: call "int C.P.get" + IL_0011: stloc.0 + IL_0012: br.s IL_0014 + // sequence point: } + IL_0014: ldloc.0 + IL_0015: ret + } + """); + + verifier.VerifyMethodBody("C.P.set", """ + { + // Code size 20 (0x14) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: P = value; + IL_000b: ldarg.0 + IL_000c: ldarg.1 + IL_000d: call "void C.P.set" + IL_0012: nop + // sequence point: } + IL_0013: ret + } + """); + } + + [Fact] + public void EventAccessors_Field() + { + var source = """ + using System; + class C + { + event Action E + { + add { } + remove { } + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.E.add", """ + { + // Code size 12 (0xc) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: } + IL_000b: ret + } + """); + + verifier.VerifyMethodBody("C.E.remove", """ + { + // Code size 12 (0xc) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: } + IL_000b: ret + } + """); + } + + [Fact] + public void EventAccessors_Explicit() + { + var source = """ + using System; + class C + { + event Action E; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.E.add"); + AssertNotInstrumented(verifier, "C.E.remove"); + } + + [Fact] + public void StateMachine_Iterator() + { + var source = """ + using System.Collections.Generic; + + class C + { + public IEnumerable F() + { + while (true) + { + yield return 1; + } + } + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.F"); + AssertNotInstrumented(verifier, "C.d__0..ctor"); + AssertNotInstrumented(verifier, "C.d__0.System.IDisposable.Dispose"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.IEnumerator.get_Current"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.IEnumerator.Reset"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.IEnumerable.GetEnumerator"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.Generic.IEnumerator.get_Current"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.Generic.IEnumerable.GetEnumerator"); + + verifier.VerifyMethodBody("C.d__0.System.Collections.IEnumerator.MoveNext", """ + { + // Code size 86 (0x56) + .maxstack 2 + .locals init (int V_0, + bool V_1) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: + IL_000a: ldarg.0 + IL_000b: ldfld "int C.d__0.<>1__state" + IL_0010: stloc.0 + IL_0011: ldloc.0 + IL_0012: brfalse.s IL_001c + IL_0014: br.s IL_0016 + IL_0016: ldloc.0 + IL_0017: ldc.i4.1 + IL_0018: beq.s IL_001e + IL_001a: br.s IL_0020 + IL_001c: br.s IL_0022 + IL_001e: br.s IL_003d + IL_0020: ldc.i4.0 + IL_0021: ret + IL_0022: ldarg.0 + IL_0023: ldc.i4.m1 + IL_0024: stfld "int C.d__0.<>1__state" + // sequence point: { + IL_0029: nop + // sequence point: + IL_002a: br.s IL_0045 + // sequence point: { + IL_002c: nop + // sequence point: yield return 1; + IL_002d: ldarg.0 + IL_002e: ldc.i4.1 + IL_002f: stfld "int C.d__0.<>2__current" + IL_0034: ldarg.0 + IL_0035: ldc.i4.1 + IL_0036: stfld "int C.d__0.<>1__state" + IL_003b: ldc.i4.1 + IL_003c: ret + // sequence point: + IL_003d: ldarg.0 + IL_003e: ldc.i4.m1 + IL_003f: stfld "int C.d__0.<>1__state" + // sequence point: } + IL_0044: nop + // sequence point: while (true) + IL_0045: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_004a: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_004f: ldc.i4.1 + IL_0050: stloc.1 + // sequence point: + IL_0051: ldloc.1 + IL_0052: brtrue.s IL_002c + IL_0054: ldc.i4.0 + IL_0055: ret + } + """); + } + + [Fact] + public void StateMachine_Async() + { + var source = """ + using System.Threading.Tasks; + + class C + { + static async Task F() + { + while (true) + { + await Task.FromResult(2); + } + } + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.F"); + AssertNotInstrumented(verifier, "C.d__0..ctor"); + AssertNotInstrumented(verifier, "C.d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine"); + + verifier.VerifyMethodBody("C.d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", """ + { + // Code size 186 (0xba) + .maxstack 3 + .locals init (int V_0, + System.Runtime.CompilerServices.TaskAwaiter V_1, + C.d__0 V_2, + bool V_3, + System.Exception V_4) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: + IL_000a: ldarg.0 + IL_000b: ldfld "int C.d__0.<>1__state" + IL_0010: stloc.0 + .try + { + // sequence point: + IL_0011: ldloc.0 + IL_0012: brfalse.s IL_0016 + IL_0014: br.s IL_0018 + IL_0016: br.s IL_0055 + // sequence point: { + IL_0018: nop + // sequence point: + IL_0019: br.s IL_007a + // sequence point: { + IL_001b: nop + // sequence point: await Task.FromResult(2); + IL_001c: ldc.i4.2 + IL_001d: call "System.Threading.Tasks.Task System.Threading.Tasks.Task.FromResult(int)" + IL_0022: callvirt "System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()" + IL_0027: stloc.1 + // sequence point: + IL_0028: ldloca.s V_1 + IL_002a: call "bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get" + IL_002f: brtrue.s IL_0071 + IL_0031: ldarg.0 + IL_0032: ldc.i4.0 + IL_0033: dup + IL_0034: stloc.0 + IL_0035: stfld "int C.d__0.<>1__state" + // async: yield + IL_003a: ldarg.0 + IL_003b: ldloc.1 + IL_003c: stfld "System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__1" + IL_0041: ldarg.0 + IL_0042: stloc.2 + IL_0043: ldarg.0 + IL_0044: ldflda "System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.d__0.<>t__builder" + IL_0049: ldloca.s V_1 + IL_004b: ldloca.s V_2 + IL_004d: call "void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted, C.d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.d__0)" + IL_0052: nop + IL_0053: leave.s IL_00b9 + // async: resume + IL_0055: ldarg.0 + IL_0056: ldfld "System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__1" + IL_005b: stloc.1 + IL_005c: ldarg.0 + IL_005d: ldflda "System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__1" + IL_0062: initobj "System.Runtime.CompilerServices.TaskAwaiter" + IL_0068: ldarg.0 + IL_0069: ldc.i4.m1 + IL_006a: dup + IL_006b: stloc.0 + IL_006c: stfld "int C.d__0.<>1__state" + IL_0071: ldloca.s V_1 + IL_0073: call "int System.Runtime.CompilerServices.TaskAwaiter.GetResult()" + IL_0078: pop + // sequence point: } + IL_0079: nop + // sequence point: while (true) + IL_007a: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_007f: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_0084: ldc.i4.1 + IL_0085: stloc.3 + // sequence point: + IL_0086: ldloc.3 + IL_0087: brtrue.s IL_001b + IL_0089: leave.s IL_00a5 + } + catch System.Exception + { + // sequence point: + IL_008b: stloc.s V_4 + IL_008d: ldarg.0 + IL_008e: ldc.i4.s -2 + IL_0090: stfld "int C.d__0.<>1__state" + IL_0095: ldarg.0 + IL_0096: ldflda "System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.d__0.<>t__builder" + IL_009b: ldloc.s V_4 + IL_009d: call "void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)" + IL_00a2: nop + IL_00a3: leave.s IL_00b9 + } + // sequence point: } + IL_00a5: ldarg.0 + IL_00a6: ldc.i4.s -2 + IL_00a8: stfld "int C.d__0.<>1__state" + // sequence point: + IL_00ad: ldarg.0 + IL_00ae: ldflda "System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.d__0.<>t__builder" + IL_00b3: call "void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()" + IL_00b8: nop + IL_00b9: ret + } + """); + } + + [Fact] + public void Records() + { + var source = """ + using System.Text; + record class R(int P) + { + protected virtual bool PrintMembers(StringBuilder builder) + { + builder.Append("x"); + return true; + } + } + """ + IsExternalInitTypeDefinition; + + var verifier = CompileAndVerify(source, verification: Verification.FailsPEVerify); + + AssertNotInstrumented(verifier, "R.P.get"); + AssertNotInstrumented(verifier, "R.P.init"); + AssertNotInstrumented(verifier, "R.$()"); + AssertNotInstrumented(verifier, "R.Deconstruct(out int)"); + AssertNotInstrumented(verifier, "R.Equals(object)"); + AssertNotInstrumented(verifier, "R.Equals(R)"); + AssertNotInstrumented(verifier, "R.GetHashCode()"); + AssertNotInstrumented(verifier, "R.EqualityContract.get"); + AssertNotInstrumented(verifier, "R.ToString()"); + AssertNotInstrumented(verifier, "bool R.op_Equality(R, R)"); + AssertNotInstrumented(verifier, "bool R.op_Inequality(R, R)"); + + verifier.VerifyMethodBody("R.PrintMembers(System.Text.StringBuilder)", """ + { + // Code size 29 (0x1d) + .maxstack 2 + .locals init (bool V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: builder.Append("x"); + IL_000b: ldarg.1 + IL_000c: ldstr "x" + IL_0011: callvirt "System.Text.StringBuilder System.Text.StringBuilder.Append(string)" + IL_0016: pop + // sequence point: return true; + IL_0017: ldc.i4.1 + IL_0018: stloc.0 + IL_0019: br.s IL_001b + // sequence point: } + IL_001b: ldloc.0 + IL_001c: ret + } + """); + + // We instrument the copy constructor for simplicity, even though it does not contain any user code. + verifier.VerifyMethodBody("R..ctor(R)", """ + { + // Code size 31 (0x1f) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_000a: ldarg.0 + IL_000b: call "object..ctor()" + IL_0010: nop + IL_0011: ldarg.0 + IL_0012: ldarg.1 + IL_0013: ldfld "int R.

k__BackingField" + IL_0018: stfld "int R.

k__BackingField" + // sequence point: R + IL_001d: nop + IL_001e: ret + } + """); + + // We instrument the primary constructor for simplicity, even though it does not contain any user code. + verifier.VerifyMethodBody("R..ctor(int)", """ + { + // Code size 25 (0x19) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: + IL_000a: ldarg.0 + IL_000b: ldarg.1 + IL_000c: stfld "int R.

k__BackingField" + // sequence point: R(int P) + IL_0011: ldarg.0 + IL_0012: call "object..ctor()" + IL_0017: nop + IL_0018: ret + } + """); + } + + [Fact] + public void While() + { + var source = """ + using System; + + class C + { + void F(bool b) + { + while(b) { Console.WriteLine(); } + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 37 (0x25) + .maxstack 1 + .locals init (bool V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: + IL_000b: br.s IL_0015 + // sequence point: { + IL_000d: nop + // sequence point: Console.WriteLine(); + IL_000e: call "void System.Console.WriteLine()" + IL_0013: nop + // sequence point: } + IL_0014: nop + // sequence point: while(b) + IL_0015: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001a: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_001f: ldarg.1 + IL_0020: stloc.0 + // sequence point: + IL_0021: ldloc.0 + IL_0022: brtrue.s IL_000d + // sequence point: } + IL_0024: ret + } + """); + } + + [Fact] + public void DoWhile() + { + var source = """ + using System; + + class C + { + void F(bool b) + { + do { Console.WriteLine(); } while (b); + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 35 (0x23) + .maxstack 1 + .locals init (bool V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: { + IL_000b: nop + // sequence point: Console.WriteLine(); + IL_000c: call "void System.Console.WriteLine()" + IL_0011: nop + // sequence point: } + IL_0012: nop + // sequence point: while (b); + IL_0013: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0018: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_001d: ldarg.1 + IL_001e: stloc.0 + // sequence point: + IL_001f: ldloc.0 + IL_0020: brtrue.s IL_000b + // sequence point: } + IL_0022: ret + } + """); + } + + [Fact] + public void For() + { + var source = """ + using System; + + class C + { + void F() + { + for (;;) { Console.WriteLine(); } + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 33 (0x21) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: + IL_000b: br.s IL_0015 + // sequence point: { + IL_000d: nop + // sequence point: Console.WriteLine(); + IL_000e: call "void System.Console.WriteLine()" + IL_0013: nop + // sequence point: } + IL_0014: nop + // sequence point: + IL_0015: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001a: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_001f: br.s IL_000d + } + """); + } + + [Fact] + public void ForEach_Array() + { + var source = """ + using System; + + class C + { + void F(int[] items) + { + foreach (var item in items) { Console.WriteLine(item); } + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 52 (0x34) + .maxstack 2 + .locals init (int[] V_0, + int V_1, + int V_2) //item + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: foreach + IL_000b: nop + // sequence point: items + IL_000c: ldarg.1 + IL_000d: stloc.0 + IL_000e: ldc.i4.0 + IL_000f: stloc.1 + // sequence point: + IL_0010: br.s IL_0023 + // sequence point: var item + IL_0012: ldloc.0 + IL_0013: ldloc.1 + IL_0014: ldelem.i4 + IL_0015: stloc.2 + // sequence point: { + IL_0016: nop + // sequence point: Console.WriteLine(item); + IL_0017: ldloc.2 + IL_0018: call "void System.Console.WriteLine(int)" + IL_001d: nop + // sequence point: } + IL_001e: nop + // sequence point: + IL_001f: ldloc.1 + IL_0020: ldc.i4.1 + IL_0021: add + IL_0022: stloc.1 + // sequence point: in + IL_0023: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0028: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_002d: ldloc.1 + IL_002e: ldloc.0 + IL_002f: ldlen + IL_0030: conv.i4 + IL_0031: blt.s IL_0012 + // sequence point: } + IL_0033: ret + } + """); + } + + [Fact] + public void ForEach_Enumerable() + { + var source = """ + using System; + using System.Collections.Generic; + + class C + { + void F(IEnumerable items) + { + foreach (var item in items) { Console.WriteLine(item); } + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 69 (0x45) + .maxstack 1 + .locals init (System.Collections.Generic.IEnumerator V_0, + int V_1) //item + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: foreach + IL_000b: nop + // sequence point: items + IL_000c: ldarg.1 + IL_000d: callvirt "System.Collections.Generic.IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator()" + IL_0012: stloc.0 + .try + { + // sequence point: + IL_0013: br.s IL_0025 + // sequence point: var item + IL_0015: ldloc.0 + IL_0016: callvirt "int System.Collections.Generic.IEnumerator.Current.get" + IL_001b: stloc.1 + // sequence point: { + IL_001c: nop + // sequence point: Console.WriteLine(item); + IL_001d: ldloc.1 + IL_001e: call "void System.Console.WriteLine(int)" + IL_0023: nop + // sequence point: } + IL_0024: nop + // sequence point: in + IL_0025: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_002a: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_002f: ldloc.0 + IL_0030: callvirt "bool System.Collections.IEnumerator.MoveNext()" + IL_0035: brtrue.s IL_0015 + IL_0037: leave.s IL_0044 + } + finally + { + // sequence point: + IL_0039: ldloc.0 + IL_003a: brfalse.s IL_0043 + IL_003c: ldloc.0 + IL_003d: callvirt "void System.IDisposable.Dispose()" + IL_0042: nop + // sequence point: + IL_0043: endfinally + } + // sequence point: } + IL_0044: ret + } + """); + } + + [Fact] + public void GoTo() + { + var source = """ + using System; + + class C + { + void F() + { + label: + Console.WriteLine(); + goto label; + } + } + """; + + var verifier = CompileAndVerify(source); + + // TODO: odd sequence point // sequence point: { ... } + verifier.VerifyMethodBody("C.F", """ + { + // Code size 30 (0x1e) + .maxstack 1 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: label: + IL_000b: nop + // sequence point: Console.WriteLine(); + IL_000c: call "void System.Console.WriteLine()" + IL_0011: nop + // sequence point: { ... } + IL_0012: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0017: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_001c: br.s IL_000b + } + """); + } + + [Fact] + public void GoToCase() + { + var source = """ + using System; + + class C + { + void F(int x) + { + switch (x) + { + case 1: Console.WriteLine(1); goto case 2; + case 2: Console.WriteLine(2); goto case 1; + } + } + } + """; + + var verifier = CompileAndVerify(source); + + // TODO: odd sequence points: // sequence point: case 1: Console.WriteLine(1); goto case 2; + verifier.VerifyMethodBody("C.F", """ + { + // Code size 66 (0x42) + .maxstack 2 + .locals init (int V_0, + int V_1) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: switch (x) + IL_000b: ldarg.1 + IL_000c: stloc.1 + // sequence point: + IL_000d: ldloc.1 + IL_000e: stloc.0 + // sequence point: + IL_000f: ldloc.0 + IL_0010: ldc.i4.1 + IL_0011: beq.s IL_001b + IL_0013: br.s IL_0015 + IL_0015: ldloc.0 + IL_0016: ldc.i4.2 + IL_0017: beq.s IL_002e + IL_0019: br.s IL_0041 + // sequence point: Console.WriteLine(1); + IL_001b: ldc.i4.1 + IL_001c: call "void System.Console.WriteLine(int)" + IL_0021: nop + // sequence point: case 1: Console.WriteLine(1); goto case 2; + IL_0022: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0027: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_002c: br.s IL_002e + // sequence point: Console.WriteLine(2); + IL_002e: ldc.i4.2 + IL_002f: call "void System.Console.WriteLine(int)" + IL_0034: nop + // sequence point: case 2: Console.WriteLine(2); goto case 1; + IL_0035: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_003a: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + IL_003f: br.s IL_001b + // sequence point: } + IL_0041: ret + } + """); + } + + [Fact] + public void ArgumentReplacement_SourceVsLibrary() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(token); + var _ = Task.FromCanceled(token); + } + + void G(CancellationToken token) + { + } + } + """; + + var verifier = CompileAndVerify(source); + + // Replace token regardless of whether the target method is from source or defined externally. + // Allows us to be consistent when the target method is invoked indirectly via a delegate. + // In that case we wouldn't know where it's defined. + verifier.VerifyMethodBody("C.F", """ + { + // Code size 35 (0x23) + .maxstack 2 + .locals init (System.Threading.Tasks.Task V_0) //_ + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(token); + IL_000b: ldarg.0 + IL_000c: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0011: call "void C.G(System.Threading.CancellationToken)" + IL_0016: nop + // sequence point: var _ = Task.FromCanceled(token); + IL_0017: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001c: call "System.Threading.Tasks.Task System.Threading.Tasks.Task.FromCanceled(System.Threading.CancellationToken)" + IL_0021: stloc.0 + // sequence point: } + IL_0022: ret + } + """); + } + + [Theory] + [InlineData("ref")] + [InlineData("out")] + [InlineData("in")] + public void ArgumentReplacement_RefKinds(string refKind) + { + var source = $$""" + using System.Threading; + + class C + { + void F(CancellationToken token) + { + G({{refKind}} token); + } + + void G({{refKind}} CancellationToken token) + { + throw null; + } + } + """; + + var verifier = CompileAndVerify(source); + + // Doesn't force module-level cancellation token to ref/in/out parameters as these are not commonly used in cancellable APIs. + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 21 (0x15) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G({{refKind}} token); + IL_000b: ldarg.0 + IL_000c: ldarga.s V_1 + IL_000e: call "void C.G({{refKind}} System.Threading.CancellationToken)" + IL_0013: nop + // sequence point: } + IL_0014: ret + } + """); + } + + [Fact] + public void ArgumentReplacement_Named() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(token: token, a: 1); + } + + void G(int a, CancellationToken token) + { + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 25 (0x19) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(token: token, a: 1); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0012: call "void C.G(int, System.Threading.CancellationToken)" + IL_0017: nop + // sequence point: } + IL_0018: ret + } + """); + } + + [Fact] + public void ArgumentReplacement_Optional() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(int a, CancellationToken token = default) + { + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 25 (0x19) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(1); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0012: call "void C.G(int, System.Threading.CancellationToken)" + IL_0017: nop + // sequence point: } + IL_0018: ret + } + """); + } + + [Fact] + public void ArgumentReplacement_IndirectCall_Positional() + { + var source = """ + using System; + using System.Threading; + + class C + { + void F(CancellationToken token) + { + var g = new Action(G); + g(token); + } + + void G(CancellationToken token) + { + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 37 (0x25) + .maxstack 2 + .locals init (System.Action V_0) //g + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: var g = new Action(G); + IL_000b: ldarg.0 + IL_000c: ldftn "void C.G(System.Threading.CancellationToken)" + IL_0012: newobj "System.Action..ctor(object, {{NativeIntDisplay}})" + IL_0017: stloc.0 + // sequence point: g(token); + IL_0018: ldloc.0 + IL_0019: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001e: callvirt "void System.Action.Invoke(System.Threading.CancellationToken)" + IL_0023: nop + // sequence point: } + IL_0024: ret + } + """); + } + + [Theory] + [InlineData("ref")] + [InlineData("out")] + [InlineData("in")] + public void ArgumentReplacement_IndirectCall_RefKinds(string refKind) + { + var source = $$""" + using System.Threading; + + delegate void D({{refKind}} CancellationToken token); + + class C + { + void F(CancellationToken token) + { + var g = new D(G); + g({{refKind}} token); + } + + void G({{refKind}} CancellationToken token) + { + throw null; + } + } + """; + + var verifier = CompileAndVerify(source); + + // Doesn't force module-level cancellation token to ref/in/out parameters as these are not commonly used in cancellable APIs. + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void ArgumentReplacement_IndirectCall_Named() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + delegate void D(int a, CancellationToken token); + + class C + { + void F(CancellationToken token) + { + var g = new D(G); + g(token: token, a: 1); + } + + void G(int a, CancellationToken token) + { + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 38 (0x26) + .maxstack 3 + .locals init (D V_0) //g + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: var g = new D(G); + IL_000b: ldarg.0 + IL_000c: ldftn "void C.G(int, System.Threading.CancellationToken)" + IL_0012: newobj "D..ctor(object, {{NativeIntDisplay}})" + IL_0017: stloc.0 + // sequence point: g(token: token, a: 1); + IL_0018: ldloc.0 + IL_0019: ldc.i4.1 + IL_001a: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001f: callvirt "void D.Invoke(int, System.Threading.CancellationToken)" + IL_0024: nop + // sequence point: } + IL_0025: ret + } + """); + } + + [Fact] + public void ArgumentReplacement_IndirectCall_Optional() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + delegate void D(int a, CancellationToken token = default); + + class C + { + void F(CancellationToken token) + { + var g = new D(G); + g(1); + } + + void G(int a, CancellationToken token) + { + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 38 (0x26) + .maxstack 3 + .locals init (D V_0) //g + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: var g = new D(G); + IL_000b: ldarg.0 + IL_000c: ldftn "void C.G(int, System.Threading.CancellationToken)" + IL_0012: newobj "D..ctor(object, {{NativeIntDisplay}})" + IL_0017: stloc.0 + // sequence point: g(1); + IL_0018: ldloc.0 + IL_0019: ldc.i4.1 + IL_001a: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001f: callvirt "void D.Invoke(int, System.Threading.CancellationToken)" + IL_0024: nop + // sequence point: } + IL_0025: ret + } + """); + } + + [Fact] + public void ArgumentReplacement_DynamicCall() + { + var source = """ + using System.Threading; + + class C + { + void F(CancellationToken token) + { + dynamic d = new C(); + d.G("str"); + } + + void G(string s) => throw null; + void G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_Matching() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(int a) + { + } + + void G(out int a, CancellationToken token) => throw null; + void G(long a, CancellationToken token) => throw null; + void G(CancellationToken token) => throw null; + void G(int a, CancellationToken token) => throw null; + void G(CancellationToken token, int a) => throw null; + void G(int a, int b, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 25 (0x19) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(1); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0012: call "void C.G(int, System.Threading.CancellationToken)" + IL_0017: nop + // sequence point: } + IL_0018: ret + } + """); + } + + [Fact] + public void CancellableOverload_ObjectVsDynamic_Arg() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(object a) => throw null; + void G(dynamic a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_ObjectToDynamic_Return() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + var x = G(1); + var y = x.ToString(); + } + + object G(int a) => throw null; + dynamic G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_DynamicToObject_Return() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + var x = G(1); + var y = x.ToString(); + } + + dynamic G(int a) => throw null; + object G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_ArgumentNames() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G((1, 1)); + } + + (int u, int v) G((int x, int y) a) => throw null; + (int u, int w) G((int z, int y) b, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 31 (0x1f) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G((1, 1)); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldc.i4.1 + IL_000e: newobj "System.ValueTuple..ctor(int, int)" + IL_0013: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0018: call "System.ValueTuple C.G(System.ValueTuple, System.Threading.CancellationToken)" + IL_001d: pop + // sequence point: } + IL_001e: ret + } + """); + } + + [Fact] + public void CancellableOverload_InstanceConstructor_BaseCall() + { + var source = """ + using System.Threading; + + class B + { + public B(int a) {} + public B(int a, CancellationToken token) {} + } + + class C() : B(1) + { + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C..ctor", """ + { + // Code size 24 (0x18) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: B(1) + IL_000a: ldarg.0 + IL_000b: ldc.i4.1 + IL_000c: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0011: call "B..ctor(int, System.Threading.CancellationToken)" + IL_0016: nop + IL_0017: ret + } + """); + } + + [Fact] + public void CancellableOverload_InstanceConstructor_ThisCall() + { + var source = """ + using System.Threading; + + class C + { + public C() : this(1) {} + public C(int a) {} + public C(int a, CancellationToken token) {} + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C..ctor()", """ + { + // Code size 25 (0x19) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: this(1) + IL_000a: ldarg.0 + IL_000b: ldc.i4.1 + IL_000c: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0011: call "C..ctor(int, System.Threading.CancellationToken)" + IL_0016: nop + // sequence point: { + IL_0017: nop + // sequence point: } + IL_0018: ret + } + """); + } + + [Fact] + public void CancellableOverload_InstanceConstructor_ObjectCreation() + { + var source = """ + using System.Threading; + + class C + { + C(int a) {} + C(int a, CancellationToken token) {} + + void F() + { + var c = new C(1); + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 24 (0x18) + .maxstack 2 + .locals init (C V_0) //c + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: var c = new C(1); + IL_000b: ldc.i4.1 + IL_000c: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0011: newobj "C..ctor(int, System.Threading.CancellationToken)" + IL_0016: stloc.0 + // sequence point: } + IL_0017: ret + } + """); + } + + [Fact] + public void CancellableOverload_InstanceConstructor_CollectionInitializers() + { + var source = """ + using System.Collections; + using System.Collections.Generic; + using System.Threading; + + class C : IEnumerable + { + void F() + { + var c = new C() + { + 1, 2 + }; + } + + public void Add(int x) {} + public void Add(int x, CancellationToken token) {} + + public IEnumerator GetEnumerator() => throw null; + IEnumerator IEnumerable.GetEnumerator() => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 44 (0x2c) + .maxstack 4 + .locals init (C V_0) //c + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: var c = new ... }; + IL_000b: newobj "C..ctor()" + IL_0010: dup + IL_0011: ldc.i4.1 + IL_0012: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0017: callvirt "void C.Add(int, System.Threading.CancellationToken)" + IL_001c: nop + IL_001d: dup + IL_001e: ldc.i4.2 + IL_001f: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0024: callvirt "void C.Add(int, System.Threading.CancellationToken)" + IL_0029: nop + IL_002a: stloc.0 + // sequence point: } + IL_002b: ret + } + """); + } + + [Fact] + public void CancellableOverload_InstanceConstructor_SetsRequiredMembers_NotCompatible() + { + var source = """ + using System.Threading; + using System.Diagnostics.CodeAnalysis; + + class B + { + [SetsRequiredMembers] + public B(int a) {} + + public B(int a, CancellationToken token) {} + } + + [method: SetsRequiredMembers] + class C() : B(1) + { + } + """ + SetsRequiredMembersAttribute; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C..ctor"); + } + + [Theory] + [InlineData("")] + [InlineData("[SetsRequiredMembers]")] + public void CancellableOverload_InstanceConstructor_SetsRequiredMembers_Compatible(string attributes) + { + var source = $$""" + using System.Threading; + using System.Diagnostics.CodeAnalysis; + + class B + { + {{attributes}} + public B(int a) {} + + [SetsRequiredMembers] + public B(int a, CancellationToken token) {} + } + + [method: SetsRequiredMembers] + class C() : B(1) + { + } + """ + SetsRequiredMembersAttribute; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C..ctor", """ + { + // Code size 24 (0x18) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: B(1) + IL_000a: ldarg.0 + IL_000b: ldc.i4.1 + IL_000c: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0011: call "B..ctor(int, System.Threading.CancellationToken)" + IL_0016: nop + IL_0017: ret + } + """); + } + + [Fact] + public void CancellableOverload_ExplicitInterfaceImpl() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + interface I + { + void G(int a); + void G(int a, CancellationToken token); + } + + class C : I + { + void F(CancellationToken token) + { + ((I)this).G(1, token); + ((I)this).G(1); + } + + void I.G(int a) => throw null; + void I.G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 38 (0x26) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: ((I)this).G(1, token); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0012: callvirt "void I.G(int, System.Threading.CancellationToken)" + IL_0017: nop + // sequence point: ((I)this).G(1); + IL_0018: ldarg.0 + IL_0019: ldc.i4.1 + IL_001a: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001f: callvirt "void I.G(int, System.Threading.CancellationToken)" + IL_0024: nop + // sequence point: } + IL_0025: ret + } + """); + } + + [Fact] + public void CancellableOverload_SpecializedCancellable_SameArity() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(0, 1); + } + + void G(T a, T b) => throw null; + void G(int a, T b, CancellationToken token) => throw null; + void G(bool a, T b, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_SpecializedCancellable_DifferentArity() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1, true); + } + + void G(S a, T b) => throw null; + void G(int a, T b, CancellationToken token) => throw null; + void G(bool a, T b, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_GenericCancellable_SameArity() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(0, 1); + } + + void G(int a, T b) => throw null; + void G(T a, T b, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_GenericCancellable_DifferentArity() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1, true); + } + + void G(int a, T b) => throw null; + void G(S a, T b, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_GenericContainingType() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(default); + G(default, token); + } + + void G(T a) + { + } + + void G(T a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 54 (0x36) + .maxstack 3 + .locals init (T V_0) + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(default); + IL_000b: ldarg.0 + IL_000c: ldloca.s V_0 + IL_000e: initobj "T" + IL_0014: ldloc.0 + IL_0015: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_001a: call "void C.G(T, System.Threading.CancellationToken)" + IL_001f: nop + // sequence point: G(default, token); + IL_0020: ldarg.0 + IL_0021: ldloca.s V_0 + IL_0023: initobj "T" + IL_0029: ldloc.0 + IL_002a: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_002f: call "void C.G(T, System.Threading.CancellationToken)" + IL_0034: nop + // sequence point: } + IL_0035: ret + } + """); + } + + [Fact] + public void CancellableOverload_GenericContainingType2() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F() + { + G(default); + } + + void G(S a) + { + } + + void G(T a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_GenericContainingType_Specialized() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class D + { + public static void G(T a) {} + public static void G(int a, CancellationToken token) {} + } + + class C + { + void F(CancellationToken token) + { + D.G(1); + } + } + + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_GenericContainingType_Specialized_Generic() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class D + { + public static void G(T a) {} + public static void G(S a, CancellationToken token) {} + } + + class C + { + void F(CancellationToken token) + { + D.G(1); + } + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_GenericContainingType_Generalized() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class D + { + public static void G(int a) {} + public static void G(T a, CancellationToken token) {} + } + + class C + { + void F(CancellationToken token) + { + D.G(1); + } + } + + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_Generic_MatchingConstraint() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(T a) where T : struct => throw null; + void G(T a, CancellationToken token) where T : struct => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 25 (0x19) + .maxstack 3 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(1); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0012: call "void C.G(int, System.Threading.CancellationToken)" + IL_0017: nop + // sequence point: } + IL_0018: ret + } + """); + } + + [Fact] + public void CancellableOverload_Generic_MatchingConstraint_TypeParameterNamesDiffer() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1, true); + } + + void G(S a, T b) where T : struct => throw null; + void G(T a, S b, CancellationToken token) where S : struct => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", """ + { + // Code size 26 (0x1a) + .maxstack 4 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(1, true); + IL_000b: ldarg.0 + IL_000c: ldc.i4.1 + IL_000d: ldc.i4.1 + IL_000e: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0013: call "void C.G(int, bool, System.Threading.CancellationToken)" + IL_0018: nop + // sequence point: } + IL_0019: ret + } + """); + } + + [Fact] + public void CancellableOverload_Generic_CompatibleButNotSameConstraint() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(int a) => throw null; + void G(int a, CancellationToken token) where T : struct => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_Generic_IncompatibleConstraint() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(int a) => throw null; + void G(int a, CancellationToken token) where T : class => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_NoMatching() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(int a) + { + } + + int G(int a, CancellationToken token) => throw null; + void G(out int a, CancellationToken token) => throw null; + void G(long a, CancellationToken token) => throw null; + void G(CancellationToken token) => throw null; + void G(CancellationToken token, int a) => throw null; + void G(int a, int b, CancellationToken token) => throw null; + void G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Theory] + [InlineData("ref", "")] + [InlineData("", "ref")] + [InlineData("ref readonly", "")] + [InlineData("", "ref readonly")] + [InlineData("ref", "ref readonly")] + [InlineData("ref readonly", "ref")] + public void CancellableOverload_ReturnType(string modifiers1, string modifiers2) + { + var source = $$""" + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + {{modifiers1}} int G(int a) => throw null; + {{modifiers2}} int G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_InstanceToStatic() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + void G(int a) + { + } + + static void G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_StaticToInstance() + { + var source = """ + using System.Threading; + using System.Threading.Tasks; + + class C + { + void F(CancellationToken token) + { + G(1); + } + + static void G(int a) + { + } + + void G(int a, CancellationToken token) => throw null; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Theory] + [CombinatorialData] + public void CancellableOverload_NonMatchingVisibility( + [CombinatorialValues("protected", "internal", "private protected", "internal protected")] string modifier1, + [CombinatorialValues("private", "protected", "internal", "private protected", "internal protected")] string modifier2) + { + var source = $$""" + using System.Threading; + using System.Threading.Tasks; + + class B + { + {{modifier1}} static void G(int a) => throw null; + {{modifier2}} static void G(int a, CancellationToken token) => throw null; + } + + class C : B + { + void F(CancellationToken token) + { + G(1); + } + } + """; + + var verifier = CompileAndVerify(source); + + if (modifier1 == modifier2) + { + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 24 (0x18) + .maxstack 2 + // sequence point: + IL_0000: ldsflda "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0005: call "void System.Threading.CancellationToken.ThrowIfCancellationRequested()" + // sequence point: { + IL_000a: nop + // sequence point: G(1); + IL_000b: ldc.i4.1 + IL_000c: ldsfld "System.Threading.CancellationToken .ModuleCancellationToken" + IL_0011: call "void B.G(int, System.Threading.CancellationToken)" + IL_0016: nop + // sequence point: } + IL_0017: ret + } + """); + } + else + { + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + } + + [Fact] + public void CancellableOverload_Indexer() + { + var source = """ + using System.Threading; + + class C + { + int this[int x] => 0; + int this[int x, CancellationToken token] => 0; + + void F() + { + var _ = this[1]; + } + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_IndexerAndMethod() + { + var source = """ + using System.Threading; + + class C + { + int get_Item() => 0; + int this[CancellationToken token] => 0; + + void F() + { + var _ = get_Item(); + } + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_PropertyAndMethod() + { + var source = """ + using System.Threading; + + class C + { + void set_P() {} + CancellationToken P { get; set; } + + void F() + { + set_P(); + } + } + """; + + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_RecordPropertyAndMethod() + { + var source = """ + using System.Threading; + + record C(CancellationToken P) + { + void set_P() {} + + void F() + { + set_P(); + } + } + """ + IsExternalInitTypeDefinition; + + var verifier = CompileAndVerify(source, verification: Verification.FailsPEVerify); + AssertNotInstrumentedWithTokenLoad(verifier, "C.F"); + } + + [Fact] + public void CancellableOverload_InfiniteRecursionAvoidance() + { + var source = """ + using System.Threading; + + class C + { + void G(T a, S b, CancellationToken token) => G(default, default); + void G(T a, S b) {} + } + """; + + // Avoid instrumentation that would trivially cause infinite recursion. + var verifier = CompileAndVerify(source); + AssertNotInstrumentedWithTokenLoad(verifier, "C.G(T, S, System.Threading.CancellationToken)"); + } +} diff --git a/src/Compilers/CSharp/Test/Emit2/Emit/RuntimeProbing/StackOverflowProbingTests.cs b/src/Compilers/CSharp/Test/Emit2/Emit/RuntimeProbing/StackOverflowProbingTests.cs new file mode 100644 index 0000000000000..be082643a0e46 --- /dev/null +++ b/src/Compilers/CSharp/Test/Emit2/Emit/RuntimeProbing/StackOverflowProbingTests.cs @@ -0,0 +1,773 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using Microsoft.CodeAnalysis.CSharp.Test.Utilities; +using Microsoft.CodeAnalysis.Emit; +using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.CSharp.UnitTests; + +public sealed class StackOverflowProbingTests : CSharpTestBase +{ +#if NET + const string NativeIntDisplay = "nint"; +#else + const string NativeIntDisplay = "System.IntPtr"; +#endif + + private static readonly EmitOptions s_emitOptions = EmitOptions.Default.WithInstrumentationKinds([InstrumentationKind.StackOverflowProbing]); + + private CompilationVerifier CompileAndVerify(string source, string? expectedOutput = null, CSharpCompilationOptions? options = null, Verification? verification = null) + => CompileAndVerify( + source, + options: options ?? (expectedOutput != null ? TestOptions.UnsafeDebugExe : TestOptions.UnsafeDebugDll), + emitOptions: s_emitOptions, + verify: verification ?? Verification.Passes, + targetFramework: TargetFramework.NetLatest, + expectedOutput: expectedOutput); + + private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName) + { + var il = verifier.VisualizeIL(qualifiedMethodName); + var isInstrumented = il.Contains("System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack"); + + Assert.False(isInstrumented, + $"Method '{qualifiedMethodName}' should not be instrumented. Actual IL:{Environment.NewLine}{il}"); + } + + [Fact] + public void LambdaAndLocalFunction() + { + var source = """ + using System; + + class C + { + public void F(Func a) + { + void L() + { + L(); + } + + F(() => 1); + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.F", $$""" + { + // Code size 47 (0x2f) + .maxstack 3 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + IL_0007: nop + // sequence point: F(() => 1); + IL_0008: ldarg.0 + IL_0009: ldsfld "System.Func C.<>c.<>9__0_1" + IL_000e: dup + IL_000f: brtrue.s IL_0028 + IL_0011: pop + IL_0012: ldsfld "C.<>c C.<>c.<>9" + IL_0017: ldftn "int C.<>c.b__0_1()" + IL_001d: newobj "System.Func..ctor(object, {{NativeIntDisplay}})" + IL_0022: dup + IL_0023: stsfld "System.Func C.<>c.<>9__0_1" + IL_0028: call "void C.F(System.Func)" + IL_002d: nop + // sequence point: } + IL_002e: ret + } + """); + + verifier.VerifyMethodBody("C.g__L|0_0", """ + { + // Code size 14 (0xe) + .maxstack 0 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: L(); + IL_0007: call "void C.g__L|0_0()" + IL_000c: nop + // sequence point: } + IL_000d: ret + } + """); + + verifier.VerifyMethodBody("C.<>c.b__0_1", """ + { + // Code size 8 (0x8) + .maxstack 1 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: 1 + IL_0006: ldc.i4.1 + IL_0007: ret + } + """); + } + + [Fact] + public void LambdaAndLocalFunction_TopLevel() + { + var source = """ + F(); + + void F() + { + F(); + } + """; + + var verifier = CompileAndVerify(source, options: TestOptions.DebugExe); + + verifier.VerifyMethodBody("", """ + { + // Code size 14 (0xe) + .maxstack 0 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: F(); + IL_0006: call "void Program.<

$>g__F|0_0()" + IL_000b: nop + IL_000c: nop + IL_000d: ret + } + """); + + verifier.VerifyMethodBody("Program.<
$>g__F|0_0", """ + { + // Code size 14 (0xe) + .maxstack 0 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: F(); + IL_0007: call "void Program.<
$>g__F|0_0()" + IL_000c: nop + // sequence point: } + IL_000d: ret + } + """); + } + + [Fact] + public void StaticConstructor_Explicit() + { + var source = """ + using System; + + class C + { + static Func s_f = () => s_f(); + + static C() + { + Console.WriteLine(123); + } + } + """; + + var verifier = CompileAndVerify(source); + + // no probe since static constructor can only be invoked once: + AssertNotInstrumented(verifier, "C..cctor"); + + // lambda should be instrumented + verifier.VerifyMethodBody("C.<>c.<.cctor>b__1_0", """ + { + // Code size 17 (0x11) + .maxstack 1 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: s_f() + IL_0006: ldsfld "System.Func C.s_f" + IL_000b: callvirt "int System.Func.Invoke()" + IL_0010: ret + } + """); + } + + [Fact] + public void StaticConstructor_Implicit() + { + var source = """ + using System; + + class C + { + static Func s_f = () => s_f(); + } + """; + + var verifier = CompileAndVerify(source); + + // no probe since static constructor can only be invoked once: + AssertNotInstrumented(verifier, "C..cctor"); + + // lambda should be instrumented + verifier.VerifyMethodBody("C.<>c.<.cctor>b__2_0", """ + { + // Code size 17 (0x11) + .maxstack 1 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: s_f() + IL_0006: ldsfld "System.Func C.s_f" + IL_000b: callvirt "int System.Func.Invoke()" + IL_0010: ret + } + """); + } + + [Fact] + public void InstanceConstructor_Implicit() + { + var source = """ + class B + { + C C = new(); + } + + class C : B + { + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("B..ctor", """ + { + // Code size 25 (0x19) + .maxstack 2 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: C C = new(); + IL_0006: ldarg.0 + IL_0007: newobj "C..ctor()" + IL_000c: stfld "C B.C" + IL_0011: ldarg.0 + IL_0012: call "object..ctor()" + IL_0017: nop + IL_0018: ret + } + """); + + verifier.VerifyMethodBody("C..ctor", """ + { + // Code size 14 (0xe) + .maxstack 1 + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + IL_0006: ldarg.0 + IL_0007: call "B..ctor()" + IL_000c: nop + IL_000d: ret + } + """); + } + + [Fact] + public void InstanceConstructors_Explicit() + { + var source = """ + class B(int a) + { + } + + class C(int a) : B(a) + { + C c = new C(1); + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("B..ctor", """ + { + // Code size 14 (0xe) + .maxstack 1 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: B(int a) + IL_0006: ldarg.0 + IL_0007: call "object..ctor()" + IL_000c: nop + IL_000d: ret + } + """); + + verifier.VerifyMethodBody("C..ctor", """ + { + // Code size 27 (0x1b) + .maxstack 2 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: C c = new C(1); + IL_0006: ldarg.0 + IL_0007: ldc.i4.1 + IL_0008: newobj "C..ctor(int)" + IL_000d: stfld "C C.c" + // sequence point: B(a) + IL_0012: ldarg.0 + IL_0013: ldarg.1 + IL_0014: call "B..ctor(int)" + IL_0019: nop + IL_001a: ret + } + """); + } + + [Fact] + public void PropertyAccessors_Auto() + { + var source = """ + class C + { + int P { get; set; } + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.P.get"); + AssertNotInstrumented(verifier, "C.P.set"); + } + + [Fact] + public void PropertyAccessors_Explicit() + { + var source = """ + class C + { + int P { get { return P; } set { P = value; } } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.P.get", """ + { + // Code size 18 (0x12) + .maxstack 1 + .locals init (int V_0) + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: return P; + IL_0007: ldarg.0 + IL_0008: call "int C.P.get" + IL_000d: stloc.0 + IL_000e: br.s IL_0010 + // sequence point: } + IL_0010: ldloc.0 + IL_0011: ret + } + """); + + verifier.VerifyMethodBody("C.P.set", """ + { + // Code size 16 (0x10) + .maxstack 2 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: P = value; + IL_0007: ldarg.0 + IL_0008: ldarg.1 + IL_0009: call "void C.P.set" + IL_000e: nop + // sequence point: } + IL_000f: ret + } + """); + } + + [Fact] + public void EventAccessors_Field() + { + var source = """ + using System; + class C + { + event Action E; + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.E.add"); + AssertNotInstrumented(verifier, "C.E.remove"); + } + + [Fact] + public void EventAccessors_Explicit() + { + var source = """ + using System; + class C + { + event Action E + { + add { } + remove { } + } + } + """; + + var verifier = CompileAndVerify(source); + + verifier.VerifyMethodBody("C.E.add", """ + { + // Code size 8 (0x8) + .maxstack 0 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: } + IL_0007: ret + } + """); + + verifier.VerifyMethodBody("C.E.remove", """ + { + // Code size 8 (0x8) + .maxstack 0 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: } + IL_0007: ret + } + """); + } + + [Fact] + public void StateMachine_Iterator() + { + var source = """ + using System.Collections.Generic; + + class C + { + public IEnumerable F() + { + yield return 1; + yield return 2; + } + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.F"); + AssertNotInstrumented(verifier, "C.d__0..ctor"); + AssertNotInstrumented(verifier, "C.d__0.System.IDisposable.Dispose"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.IEnumerator.get_Current"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.IEnumerator.Reset"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.IEnumerable.GetEnumerator"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.Generic.IEnumerator.get_Current"); + AssertNotInstrumented(verifier, "C.d__0.System.Collections.Generic.IEnumerable.GetEnumerator"); + + verifier.VerifyMethodBody("C.d__0.System.Collections.IEnumerator.MoveNext", """ + { + // Code size 97 (0x61) + .maxstack 2 + .locals init (int V_0) + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: + IL_0006: ldarg.0 + IL_0007: ldfld "int C.d__0.<>1__state" + IL_000c: stloc.0 + IL_000d: ldloc.0 + IL_000e: switch ( + IL_0021, + IL_0023, + IL_0025) + IL_001f: br.s IL_0027 + IL_0021: br.s IL_0029 + IL_0023: br.s IL_0041 + IL_0025: br.s IL_0058 + IL_0027: ldc.i4.0 + IL_0028: ret + IL_0029: ldarg.0 + IL_002a: ldc.i4.m1 + IL_002b: stfld "int C.d__0.<>1__state" + // sequence point: { + IL_0030: nop + // sequence point: yield return 1; + IL_0031: ldarg.0 + IL_0032: ldc.i4.1 + IL_0033: stfld "int C.d__0.<>2__current" + IL_0038: ldarg.0 + IL_0039: ldc.i4.1 + IL_003a: stfld "int C.d__0.<>1__state" + IL_003f: ldc.i4.1 + IL_0040: ret + // sequence point: + IL_0041: ldarg.0 + IL_0042: ldc.i4.m1 + IL_0043: stfld "int C.d__0.<>1__state" + // sequence point: yield return 2; + IL_0048: ldarg.0 + IL_0049: ldc.i4.2 + IL_004a: stfld "int C.d__0.<>2__current" + IL_004f: ldarg.0 + IL_0050: ldc.i4.2 + IL_0051: stfld "int C.d__0.<>1__state" + IL_0056: ldc.i4.1 + IL_0057: ret + // sequence point: + IL_0058: ldarg.0 + IL_0059: ldc.i4.m1 + IL_005a: stfld "int C.d__0.<>1__state" + // sequence point: } + IL_005f: ldc.i4.0 + IL_0060: ret + } + """); + } + + [Fact] + public void StateMachine_Async() + { + var source = """ + using System.Threading.Tasks; + + class C + { + static async Task F() + { + await F(); + } + } + """; + + var verifier = CompileAndVerify(source); + + AssertNotInstrumented(verifier, "C.F"); + AssertNotInstrumented(verifier, "C.d__0..ctor"); + AssertNotInstrumented(verifier, "C.d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine"); + + verifier.VerifyMethodBody("C.d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", """ + { + // Code size 160 (0xa0) + .maxstack 3 + .locals init (int V_0, + System.Runtime.CompilerServices.TaskAwaiter V_1, + C.d__0 V_2, + System.Exception V_3) + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: + IL_0006: ldarg.0 + IL_0007: ldfld "int C.d__0.<>1__state" + IL_000c: stloc.0 + .try + { + // sequence point: + IL_000d: ldloc.0 + IL_000e: brfalse.s IL_0012 + IL_0010: br.s IL_0014 + IL_0012: br.s IL_004d + // sequence point: { + IL_0014: nop + // sequence point: await F(); + IL_0015: call "System.Threading.Tasks.Task C.F()" + IL_001a: callvirt "System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()" + IL_001f: stloc.1 + // sequence point: + IL_0020: ldloca.s V_1 + IL_0022: call "bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get" + IL_0027: brtrue.s IL_0069 + IL_0029: ldarg.0 + IL_002a: ldc.i4.0 + IL_002b: dup + IL_002c: stloc.0 + IL_002d: stfld "int C.d__0.<>1__state" + // async: yield + IL_0032: ldarg.0 + IL_0033: ldloc.1 + IL_0034: stfld "System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__1" + IL_0039: ldarg.0 + IL_003a: stloc.2 + IL_003b: ldarg.0 + IL_003c: ldflda "System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.d__0.<>t__builder" + IL_0041: ldloca.s V_1 + IL_0043: ldloca.s V_2 + IL_0045: call "void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompletedd__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.d__0)" + IL_004a: nop + IL_004b: leave.s IL_009f + // async: resume + IL_004d: ldarg.0 + IL_004e: ldfld "System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__1" + IL_0053: stloc.1 + IL_0054: ldarg.0 + IL_0055: ldflda "System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__1" + IL_005a: initobj "System.Runtime.CompilerServices.TaskAwaiter" + IL_0060: ldarg.0 + IL_0061: ldc.i4.m1 + IL_0062: dup + IL_0063: stloc.0 + IL_0064: stfld "int C.d__0.<>1__state" + IL_0069: ldloca.s V_1 + IL_006b: call "void System.Runtime.CompilerServices.TaskAwaiter.GetResult()" + IL_0070: nop + IL_0071: leave.s IL_008b + } + catch System.Exception + { + // sequence point: + IL_0073: stloc.3 + IL_0074: ldarg.0 + IL_0075: ldc.i4.s -2 + IL_0077: stfld "int C.d__0.<>1__state" + IL_007c: ldarg.0 + IL_007d: ldflda "System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.d__0.<>t__builder" + IL_0082: ldloc.3 + IL_0083: call "void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)" + IL_0088: nop + IL_0089: leave.s IL_009f + } + // sequence point: } + IL_008b: ldarg.0 + IL_008c: ldc.i4.s -2 + IL_008e: stfld "int C.d__0.<>1__state" + // sequence point: + IL_0093: ldarg.0 + IL_0094: ldflda "System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.d__0.<>t__builder" + IL_0099: call "void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()" + IL_009e: nop + IL_009f: ret + } + """); + } + + [Fact] + public void Records() + { + var source = """ + using System.Text; + record class R(int P) + { + protected virtual bool PrintMembers(StringBuilder builder) + { + builder.Append("x"); + return true; + } + } + """ + IsExternalInitTypeDefinition; + + var verifier = CompileAndVerify(source, verification: Verification.FailsPEVerify); + + AssertNotInstrumented(verifier, "R.P.get"); + AssertNotInstrumented(verifier, "R.P.init"); + AssertNotInstrumented(verifier, "R.$()"); + AssertNotInstrumented(verifier, "R.Deconstruct(out int)"); + AssertNotInstrumented(verifier, "R.Equals(object)"); + AssertNotInstrumented(verifier, "R.Equals(R)"); + AssertNotInstrumented(verifier, "R.GetHashCode()"); + AssertNotInstrumented(verifier, "R.EqualityContract.get"); + AssertNotInstrumented(verifier, "R.ToString()"); + AssertNotInstrumented(verifier, "bool R.op_Equality(R, R)"); + AssertNotInstrumented(verifier, "bool R.op_Inequality(R, R)"); + + verifier.VerifyMethodBody("R.PrintMembers(System.Text.StringBuilder)", """ + { + // Code size 25 (0x19) + .maxstack 2 + .locals init (bool V_0) + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: { + IL_0006: nop + // sequence point: builder.Append("x"); + IL_0007: ldarg.1 + IL_0008: ldstr "x" + IL_000d: callvirt "System.Text.StringBuilder System.Text.StringBuilder.Append(string)" + IL_0012: pop + // sequence point: return true; + IL_0013: ldc.i4.1 + IL_0014: stloc.0 + IL_0015: br.s IL_0017 + // sequence point: } + IL_0017: ldloc.0 + IL_0018: ret + } + """); + + // We instrument the copy constructor for simplicity, even though it does not contain any user code. + verifier.VerifyMethodBody("R..ctor(R)", """ + { + // Code size 27 (0x1b) + .maxstack 2 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + IL_0006: ldarg.0 + IL_0007: call "object..ctor()" + IL_000c: nop + IL_000d: ldarg.0 + IL_000e: ldarg.1 + IL_000f: ldfld "int R.

k__BackingField" + IL_0014: stfld "int R.

k__BackingField" + // sequence point: R + IL_0019: nop + IL_001a: ret + } + """); + + // We instrument the primary constructor for simplicity, even though it does not contain any user code. + verifier.VerifyMethodBody("R..ctor(int)", """ + { + // Code size 21 (0x15) + .maxstack 2 + // sequence point: + IL_0000: call "void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()" + IL_0005: nop + // sequence point: + IL_0006: ldarg.0 + IL_0007: ldarg.1 + IL_0008: stfld "int R.

k__BackingField" + // sequence point: R(int P) + IL_000d: ldarg.0 + IL_000e: call "object..ctor()" + IL_0013: nop + IL_0014: ret + } + """); + } +} diff --git a/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs b/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs index 47eacd49e8823..0e33de83c40d4 100644 --- a/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs +++ b/src/Compilers/Core/Portable/CodeGen/PrivateImplementationDetails.cs @@ -76,6 +76,8 @@ internal sealed class PrivateImplementationDetails : DefaultTypeDef, Cci.INamesp new ConcurrentDictionary<(ImmutableArray Constants, ushort ElementType), CachedArrayField>(ConstantValueAndUShortEqualityComparer.Instance); private ModuleVersionIdField? _mvidField; + private ModuleCancellationTokenField? _moduleCancellationTokenField; + // Dictionary that maps from analysis kind to instrumentation payload field. private readonly ConcurrentDictionary _instrumentationPayloadRootFields = new ConcurrentDictionary(); @@ -156,10 +158,13 @@ internal void Freeze() fieldsBuilder.AddRange(_mappedFields.Values); fieldsBuilder.AddRange(_cachedArrayFields.Values); fieldsBuilder.AddRange(_cachedArrayFieldsForConstants.Values); + if (_mvidField != null) - { fieldsBuilder.Add(_mvidField); - } + + if (_moduleCancellationTokenField != null) + fieldsBuilder.Add(_moduleCancellationTokenField); + fieldsBuilder.AddRange(_instrumentationPayloadRootFields.Values); fieldsBuilder.Sort(FieldComparer.Instance); _orderedSynthesizedFields = fieldsBuilder.ToImmutableAndFree(); @@ -303,6 +308,18 @@ internal Cci.IFieldReference GetModuleVersionId(Cci.ITypeReference mvidType) return _mvidField; } + internal Cci.IFieldReference GetModuleCancellationToken(Cci.ITypeReference cancellationTokenType) + { + if (_moduleCancellationTokenField == null) + { + Debug.Assert(!IsFrozen); + Interlocked.CompareExchange(ref _moduleCancellationTokenField, new ModuleCancellationTokenField(this, cancellationTokenType), null); + } + + Debug.Assert(_moduleCancellationTokenField.Type == cancellationTokenType); + return _moduleCancellationTokenField; + } + internal Cci.IFieldReference GetOrAddInstrumentationPayloadRoot(int analysisKind, Cci.ITypeReference payloadRootType) { InstrumentationPayloadRootField? payloadRootField; @@ -709,6 +726,16 @@ internal ModuleVersionIdField(Cci.INamedTypeDefinition containingType, Cci.IType public override bool IsReadOnly => true; } + ///

+ /// Synthesized by instrumentation. + /// + internal sealed class ModuleCancellationTokenField(Cci.INamedTypeDefinition containingType, Cci.ITypeReference type) + : SynthesizedStaticField("ModuleCancellationToken", containingType, type) + { + public override ImmutableArray MappedData => default; + public override bool IsReadOnly => false; + } + internal sealed class InstrumentationPayloadRootField : SynthesizedStaticField { internal InstrumentationPayloadRootField(Cci.INamedTypeDefinition containingType, int analysisIndex, Cci.ITypeReference payloadType) diff --git a/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs b/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs index 341eb711be926..1bc7079e2a2d8 100644 --- a/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs +++ b/src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs @@ -747,6 +747,9 @@ internal Cci.IFieldReference GetModuleVersionId(Cci.ITypeReference mvidType, TSy return details.GetModuleVersionId(mvidType); } + internal Cci.IFieldReference GetModuleCancellationToken(Cci.ITypeReference cancellationTokenType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) + => GetPrivateImplClass(syntaxOpt, diagnostics).GetModuleCancellationToken(cancellationTokenType); + internal Cci.IFieldReference GetInstrumentationPayloadRoot(int analysisKind, Cci.ITypeReference payloadType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); diff --git a/src/Compilers/Core/Portable/Emit/InstrumentationKind.cs b/src/Compilers/Core/Portable/Emit/InstrumentationKind.cs index 2109be815a0af..a62ddb2846149 100644 --- a/src/Compilers/Core/Portable/Emit/InstrumentationKind.cs +++ b/src/Compilers/Core/Portable/Emit/InstrumentationKind.cs @@ -2,6 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Runtime.CompilerServices; +using System.Threading; + namespace Microsoft.CodeAnalysis.Emit { /// @@ -18,6 +21,21 @@ public enum InstrumentationKind /// Instruments the code to add test coverage. /// TestCoverage = 1, + + /// + /// Instruments all methods, local functions and lambdas in the code with calls to , + /// to guard against accidental stack overflow. + /// + StackOverflowProbing = 2, + + /// + /// Instruments code with calls to on a module-level defined + /// to enable cancellation of code that hasn't necessarily been written as cancellable. + /// + /// + /// The is emitted to a static field <PrivateImplementationDetails>.ModuleCancellationToken. + /// + ModuleCancellation = 3 } internal static class InstrumentationKindExtensions @@ -25,8 +43,6 @@ internal static class InstrumentationKindExtensions internal const InstrumentationKind LocalStateTracing = (InstrumentationKind)(-1); internal static bool IsValid(this InstrumentationKind value) - { - return value >= InstrumentationKind.None && value <= InstrumentationKind.TestCoverage; - } + => value is >= InstrumentationKind.None and <= InstrumentationKind.ModuleCancellation; } } diff --git a/src/Compilers/Core/Portable/InternalUtilities/OneOrMany.cs b/src/Compilers/Core/Portable/InternalUtilities/OneOrMany.cs index 10c7ac2543e5f..c13134228e584 100644 --- a/src/Compilers/Core/Portable/InternalUtilities/OneOrMany.cs +++ b/src/Compilers/Core/Portable/InternalUtilities/OneOrMany.cs @@ -60,6 +60,9 @@ public OneOrMany(ImmutableArray many) private bool HasOneItem => _many.IsDefault; + public bool IsDefault + => _one == null && _many.IsDefault; + public T this[int index] { get diff --git a/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt b/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt index 373c14b5b527a..8a821d34a1286 100644 --- a/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt @@ -1,4 +1,6 @@ Microsoft.CodeAnalysis.Diagnostics.SuppressionInfo.ProgrammaticSuppressions.get -> System.Collections.Immutable.ImmutableArray +Microsoft.CodeAnalysis.Emit.InstrumentationKind.ModuleCancellation = 3 -> Microsoft.CodeAnalysis.Emit.InstrumentationKind +Microsoft.CodeAnalysis.Emit.InstrumentationKind.StackOverflowProbing = 2 -> Microsoft.CodeAnalysis.Emit.InstrumentationKind Microsoft.CodeAnalysis.OperationKind.CollectionExpression = 127 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.Spread = 128 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.Operations.ICollectionExpressionOperation.ConstructMethod.get -> Microsoft.CodeAnalysis.IMethodSymbol? diff --git a/src/Compilers/Core/Portable/WellKnownMember.cs b/src/Compilers/Core/Portable/WellKnownMember.cs index ef6a97c70ddd5..3c0d1b6f2ea47 100644 --- a/src/Compilers/Core/Portable/WellKnownMember.cs +++ b/src/Compilers/Core/Portable/WellKnownMember.cs @@ -559,6 +559,7 @@ internal enum WellKnownMember System_Runtime_CompilerServices_SwitchExpressionException__ctorObject, System_Threading_CancellationToken__Equals, + System_Threading_CancellationToken__ThrowIfCancellationRequested, System_Threading_CancellationTokenSource__CreateLinkedTokenSource, System_Threading_CancellationTokenSource__Token, System_Threading_CancellationTokenSource__Dispose, diff --git a/src/Compilers/Core/Portable/WellKnownMembers.cs b/src/Compilers/Core/Portable/WellKnownMembers.cs index 94c6193207800..47de306044238 100644 --- a/src/Compilers/Core/Portable/WellKnownMembers.cs +++ b/src/Compilers/Core/Portable/WellKnownMembers.cs @@ -3886,6 +3886,13 @@ static WellKnownMembers() 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // Argument: CancellationToken + + // System_Threading_CancellationToken__ThrowIfCancellationRequested + (byte)MemberFlags.Method, // Flags + (byte)WellKnownType.ExtSentinel, (byte)(WellKnownType.System_Threading_CancellationToken - WellKnownType.ExtSentinel), // DeclaringTypeId + 0, // Arity + 0, // Method Signature + (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type // System_Threading_CancellationTokenSource__CreateLinkedTokenSource (byte)(MemberFlags.Method | MemberFlags.Static), // Flags @@ -4941,6 +4948,7 @@ static WellKnownMembers() ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctor ".ctor", // System_Runtime_CompilerServices_SwitchExpressionException__ctorObject "Equals", // System_Threading_CancellationToken__Equals + "ThrowIfCancellationRequested", // System_Threading_CancellationToken__ThrowIfCancellationRequested "CreateLinkedTokenSource", // System_Threading_CancellationTokenSource__CreateLinkedTokenSource "Token", // System_Threading_CancellationTokenSource__Token "Dispose", // System_Threading_CancellationTokenSource__Dispose diff --git a/src/Tools/Source/CompilerGeneratorTools/Source/BoundTreeGenerator/BoundNodeClassWriter.cs b/src/Tools/Source/CompilerGeneratorTools/Source/BoundTreeGenerator/BoundNodeClassWriter.cs index f1318b02d65cd..6fe668757a224 100644 --- a/src/Tools/Source/CompilerGeneratorTools/Source/BoundTreeGenerator/BoundNodeClassWriter.cs +++ b/src/Tools/Source/CompilerGeneratorTools/Source/BoundTreeGenerator/BoundNodeClassWriter.cs @@ -667,18 +667,18 @@ private void WriteNullChecks(TreeType node) foreach (Field field in nullCheckFields) { - bool isROArray = (GetGenericType(field.Type) == "ImmutableArray"); + bool useIsDefaultProperty = GetGenericType(field.Type) is "ImmutableArray" or "OneOrMany"; switch (_targetLang) { case TargetLanguage.CSharp: - if (isROArray) + if (useIsDefaultProperty) WriteLine("RoslynDebug.Assert(!{0}.IsDefault, \"Field '{0}' cannot be null (use Null=\\\"allow\\\" in BoundNodes.xml to remove this check)\");", ToCamelCase(field.Name)); else WriteLine("RoslynDebug.Assert({0} is object, \"Field '{0}' cannot be null (make the type nullable in BoundNodes.xml to remove this check)\");", ToCamelCase(field.Name)); break; case TargetLanguage.VB: - if (isROArray) + if (useIsDefaultProperty) WriteLine("Debug.Assert(Not ({0}.IsDefault), \"Field '{0}' cannot be null (use Null=\"\"allow\"\" in BoundNodes.xml to remove this check)\")", ToCamelCase(field.Name)); else WriteLine("Debug.Assert({0} IsNot Nothing, \"Field '{0}' cannot be null (use Null=\"\"allow\"\" in BoundNodes.xml to remove this check)\")", ToCamelCase(field.Name)); @@ -928,91 +928,114 @@ private void WriteUpdateMethod(Node node) { if (!AllFields(node).Any()) return; - bool emitNew = (!Fields(node).Any()) && BaseType(node) is Node; + bool emitNew = (!Fields(node).Any()) && BaseType(node) is Node; switch (_targetLang) { case TargetLanguage.CSharp: - { - Blank(); - Write("public{1} {0} Update", node.Name, emitNew ? " new" : ""); - Paren(); - Comma(AllSpecifiableFields(node), field => string.Format("{0} {1}", GetField(node, field.Name).Type, ToCamelCase(field.Name))); - UnParen(); - Blank(); - Brace(); - if (AllSpecifiableFields(node).Any()) - { - Write("if "); - Paren(); - Or(AllSpecifiableFields(node), - field => wasUpdatedCheck(field)); - UnParen(); - Blank(); - Brace(); - Write("var result = new {0}", node.Name); - var fields = new[] { "this.Syntax" }.Concat(AllSpecifiableFields(node).Select(f => ToCamelCase(f.Name))).Concat(new[] { "this.HasErrors" }); - ParenList(fields); - WriteLine(";"); - WriteLine("result.CopyAttributes(this);"); - WriteLine("return result;"); - Unbrace(); - } - WriteLine("return this;"); - Unbrace(); - break; - } + WriteUpdatedMethodCSharp(node, emitNew); + break; case TargetLanguage.VB: - { - Blank(); - Write("Public{0} Function Update", emitNew ? " Shadows" : ""); - Paren(); - Comma(AllSpecifiableFields(node), field => string.Format("{1} As {0}", field.Type, ToCamelCase(field.Name))); - UnParen(); - WriteLine(" As {0}", node.Name); - Indent(); - - if (AllSpecifiableFields(node).Any()) - { - Write("If "); - Or(AllSpecifiableFields(node), - field => IsValueType(field.Type) - ? string.Format("{0} <> Me.{1}", ToCamelCase(field.Name), field.Name) - : string.Format("{0} IsNot Me.{1}", ToCamelCase(field.Name), field.Name)); - WriteLine(" Then"); - Indent(); - Write("Dim result = New {0}", node.Name); - var fields = new[] { "Me.Syntax" }.Concat(AllSpecifiableFields(node).Select(f => ToCamelCase(f.Name))).Concat(new[] { "Me.HasErrors" }); - ParenList(fields); - WriteLine(""); - WriteLine("result.CopyAttributes(Me)"); - WriteLine("Return result"); - Outdent(); - WriteLine("End If"); - } - WriteLine("Return Me"); - - Outdent(); - WriteLine("End Function"); - break; - } + WriteUpdatedMethodVB(node, emitNew); + break; default: throw new ArgumentException("Unexpected target language", nameof(_targetLang)); } + } - string wasUpdatedCheck(Field field) + private void WriteUpdatedMethodCSharp(Node node, bool emitNew) + { + Blank(); + Write("public{1} {0} Update", node.Name, emitNew ? " new" : ""); + Paren(); + Comma(AllSpecifiableFields(node), field => string.Format("{0} {1}", GetField(node, field.Name).Type, ToCamelCase(field.Name))); + UnParen(); + Blank(); + Brace(); + if (AllSpecifiableFields(node).Any()) + { + Write("if "); + Paren(); + Or(AllSpecifiableFields(node), notEquals); + UnParen(); + Blank(); + Brace(); + Write("var result = new {0}", node.Name); + var fields = new[] { "this.Syntax" }.Concat(AllSpecifiableFields(node).Select(f => ToCamelCase(f.Name))).Concat(new[] { "this.HasErrors" }); + ParenList(fields); + WriteLine(";"); + WriteLine("result.CopyAttributes(this);"); + WriteLine("return result;"); + Unbrace(); + } + WriteLine("return this;"); + Unbrace(); + + string notEquals(Field field) { - var format = TypeIsTypeSymbol(field) - ? "!TypeSymbol.Equals({0}, this.{1}, TypeCompareKind.ConsiderEverything)" - : TypeIsSymbol(field) - ? "!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals({0}, this.{1})" - : IsValueType(field.Type) && field.Type[^1] == '?' - ? "!{0}.Equals(this.{1})" - : "{0} != this.{1}"; - - return string.Format(format, ToCamelCase(field.Name), field.Name); + var parameterName = ToCamelCase(field.Name); + var fieldName = field.Name; + + if (TypeIsTypeSymbol(field)) + return $"!TypeSymbol.Equals({parameterName}, this.{fieldName}, TypeCompareKind.ConsiderEverything)"; + + if (TypeIsSymbol(field)) + return $"!Symbols.SymbolEqualityComparer.ConsiderEverything.Equals({parameterName}, this.{fieldName})"; + + if (IsValueType(field.Type) && field.Type[^1] == '?') + return $"!{parameterName}.Equals(this.{fieldName})"; + + if (GetGenericType(field.Type) == "OneOrMany") + return $"!{parameterName}.SequenceEqual({fieldName})"; + + return $"{parameterName} != this.{fieldName}"; + } + } + + private void WriteUpdatedMethodVB(Node node, bool emitNew) + { + Blank(); + Write("Public{0} Function Update", emitNew ? " Shadows" : ""); + Paren(); + Comma(AllSpecifiableFields(node), field => string.Format("{1} As {0}", field.Type, ToCamelCase(field.Name))); + UnParen(); + WriteLine(" As {0}", node.Name); + Indent(); + + if (AllSpecifiableFields(node).Any()) + { + Write("If "); + Or(AllSpecifiableFields(node), notEquals); + WriteLine(" Then"); + Indent(); + Write("Dim result = New {0}", node.Name); + var fields = new[] { "Me.Syntax" }.Concat(AllSpecifiableFields(node).Select(f => ToCamelCase(f.Name))).Concat(new[] { "Me.HasErrors" }); + ParenList(fields); + WriteLine(""); + WriteLine("result.CopyAttributes(Me)"); + WriteLine("Return result"); + Outdent(); + WriteLine("End If"); + } + WriteLine("Return Me"); + + Outdent(); + WriteLine("End Function"); + + string notEquals(Field field) + { + var parameterName = ToCamelCase(field.Name); + var fieldName = field.Name; + + if (!IsValueType(field.Type)) + return $"{parameterName} IsNot Me.{fieldName}"; + + if (GetGenericType(field.Type) == "OneOrMany") + return $"Not {parameterName}.SequenceEqual({fieldName})"; + + return $"{parameterName} <> Me.{fieldName}"; } }