实例方法中的 CIL (MSIL) 尾调用递归

发布于 2025-01-04 00:30:50 字数 419 浏览 5 评论 0原文

背景:我正在为一个学校项目编写 .NET 编译器(与 C# 非常相似)。我当前尝试添加的功能之一是方法内的尾调用递归。

更多信息:在 CIL 中,“this”被传递到实例方法中,就好像它只是另一个参数一样。因此,访问静态方法的第一个参数,您将发出 ldarg.0,但访问实例方法的第一个参数,您将发出 ldarg.1,而在实例方法中访问“this”,您将发出 ldarg.0 。 (实例方法比我想象的更类似于扩展方法。)

问:你能使用 starg.0 设置“this”而不产生任何副作用吗?

为什么会出现这个问题:方法是否是实例方法是通过 MethodBuilder 设置的,这有点像黑匣子。尽管“this”看起来就像任何其他参数一样,但据我所知,一些 JIT 编译器单独跟踪“this”并根据该值更改其行为。如果在实例方法中设置“this”时出现副作用,那么如何避免它们呢?

Background: I am programming a .NET compiler (very similar to C#) for a school project. One of the features I am currently trying to add is tailcall recursion within methods.

More info: In CIL, the "this" is passed into instance methods as if it were just another argument. So, accessing the first argument of a static method, you would emit ldarg.0, but accessing the first argument of an instance method, you would emit ldarg.1, and accessing "this" in an instance method you would emit ldarg.0. (Instance methods are even more similar to extension methods than I ever imagined.)

Question: Can you set "this" using starg.0 without any side effects?

Why this is in question: Whether or not a method is an instance method is set with the MethodBuilder, which is a bit of a black box. Although "this" seems just like any other argument, for all I know some JIT compilers keep track of "this" separately and change their behavior depending on this value. If there are side effects when you set "this" in an instance method, then how can I avoid them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愁以何悠 2025-01-11 00:30:50

您可能想看看 F# 如何实现尾部调用

You may want to have a look at how F# implements tail-call.

清浅ˋ旧时光 2025-01-11 00:30:50

您可以将其提取为局部变量。这样您就会知道可以安全地进行设置。 (我希望我正确理解你的问题)

You can extract this as a local variable. This way you will know that you can set it safely. (I hope I understand your question correctly)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文