为什么零长度的stackalloc会让C#编译器乐于允许有条件的stackallocs?

c#

下面的“修复”让我很困惑;这里的场景是根据大小有条件地决定是使用堆栈还是租用缓冲区 - 这是一个非常利基但有时必要的优化,但是:使用“明显”的实现(数字 3,推迟明确的分配,直到我们真正想要分配它),编译器抱怨 CS8353:

不能在此上下文中使用类型为“Span<int>”的 stackalloc 表达式的结果,因为它可能会暴露在包含方法之外

简短的再现(完整的再现如下)是:

// take your pick of:
// Span<int> s = stackalloc[0]; // works
// Span<int> s = default; // fails
// Span<int> s; // fails

if (condition)
{   // CS8353 happens here
    s = stackalloc int[size];
}
else
{
    s = // some other expression
}
// use s here

我在这里唯一能想到的是,编译器确实在标记stackalloc正在逃避发生的上下文stackalloc,并且挥舞着一个标志说“我无法证明这在方法后面是否安全” ,但是通过stackalloc[0]在开始时使用 ,我们将“危险”上下文范围推得更高,现在编译器很高兴它永远不会逃脱“危险”范围(即它从未真正离开方法,因为我们声明在顶部范围)。这种理解是否正确,就可以证明的内容而言,这只是编译器的限制?

什么是真正有趣的(对我)是,= stackalloc[0]是根本无操作无论如何,这意味着至少在编译的形式工作1号= stackalloc[0]是相同的故障数2 = default

完整再现(也可在 SharpLab 上查看 IL)。

using System;
using System.Buffers;

public static class C
{
    public static void StackAllocFun(int count)
    {
        // #1 this is legal, just initializes s as a default span
        Span<int> s = stackalloc int[0];
        
        // #2 this is illegal: error CS8353: A result of a stackalloc expression
        // of type 'Span<int>' cannot be used in this context because it may
        // be exposed outside of the containing method
        // Span<int> s = default;
        
        // #3 as is this (also illegal, identical error)
        // Span<int> s;
        
        int[] oversized = null;
        try
        {
            if (count < 32)
            {   // CS8353 happens at this stackalloc
                s = stackalloc int[count];
            }
            else
            {
                oversized = ArrayPool<int>.Shared.Rent(count);
                s = new Span<int>(oversized, 0, count);
            }
            Populate(s);
            DoSomethingWith(s);
        }
        finally
        {
            if (oversized is not null)
            {
                ArrayPool<int>.Shared.Return(oversized);
            }
        }
    }

    private static void Populate(Span<int> s)
        => throw new NotImplementedException(); // whatever
    private static void DoSomethingWith(ReadOnlySpan<int> s)
        => throw new NotImplementedException(); // whatever
    
    // note: ShowNoOpX and ShowNoOpY compile identically just:
    // ldloca.s 0, initobj Span<int>, ldloc.0
    static void ShowNoOpX()
    {
        Span<int> s = stackalloc int[0];
        DoSomethingWith(s);
    }
    static void ShowNoOpY()
    {
        Span<int> s = default;
        DoSomethingWith(s);
    }
}

回答

Span<T> / ref功能本质上是一系列关于给定值可以通过值或引用转义到哪个范围的规则。虽然这是根据方法范围编写的,但简化为以下两个语句之一是有帮助的:

  1. 该值不能从方法返回
  2. 该值可以从方法返回

该跨度安全文档介绍了有关的范围是如何为各种语句和表达式计算非常详细。不过,这里的相关部分是关于如何处理当地人的。

主要的收获是本地是否可以返回是在本地声明时间计算的。在声明局部变量时,编译器会检查初始化器并决定局部变量是否可以从方法中返回。在有初始化器的情况下,如果能够返回初始化表达式,则本地将能够返回。

你如何处理声明了本地但没有初始化程序的情况?编译器必须做出决定:它可以还是不可以返回?在设计功能时,我们决定默认为“它可以返回”,因为这是对现有模式造成最少摩擦的决定。

这确实给我们留下了一个问题,即开发人员如何声明一个不能安全返回但也缺少初始化程序的本地。最终我们确定了 的模式= stackalloc [0]。这是一个可以安全优化的表达式,并且是一个强有力的指标,基本上是一个要求,本地不安全返回。

知道这解释了您所看到的行为:

  • Span<int> s = stackalloc[0]:这不安全返回因此后来stackalloc成功
  • Span<int> s = default: 这是可以安全返回的,因为default可以安全返回。这意味着后者stackalloc失败,因为您分配了一个不安全的值返回到标记为安全返回的本地
  • Span<int> s;:这是可以安全返回的,因为这是未初始化的本地人的默认设置。这意味着后者stackalloc失败,因为您分配了一个不安全的值返回到标记为安全返回的本地

这种= stackalloc[0]方法的真正缺点是它只适用于Span<T>. 这不是ref struct. 在实践中,尽管对于其他类型来说这不是什么大问题。有一些关于我们如何使它更普遍的猜测,但目前还没有足够的证据证明这样做是合理的。


回答

不是“为什么”的答案;但是,您可以将其更改为三元运算符,将数组分配的结果切片为 Span:

public static void StackAllocFun(int count)
{
    int[] oversized = null;
    try
    {
        Span<int> s = ((uint)count < 32) ?
            stackalloc int[count] :
            (oversized = ArrayPool<int>.Shared.Rent(count)).AsSpan(0, count);

        Populate(s);
        DoSomethingWith(s);
    }
    finally
    {
        if (oversized is not null)
        {
            ArrayPool<int>.Shared.Return(oversized);
        }
    }
}

  • I would consider changing that `(count < 32)` to `((uint)count < 32)`, or otherwise assert that `count` is positive. Otherwise the stackalloc will try to stackalloc a negative value, which is treated as unsigned, and you'll... stack overflow.

以上是为什么零长度的stackalloc会让C#编译器乐于允许有条件的stackallocs?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>