modernc.org/gc@v1.0.1-0.20240304020402-f0dba7c97c2b/testdata/errchk/test/fixedbugs/issue12588.go (about)

     1  // errorcheck -0 -m -l
     2  
     3  // Copyright 2015 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Tests escape analysis for range of arrays.
     8  // Compiles but need not run.  Inlining is disabled.
     9  
    10  package main
    11  
    12  type A struct {
    13  	b [3]uint64
    14  }
    15  
    16  type B struct {
    17  	b [3]*uint64
    18  }
    19  
    20  func f(a A) int {
    21  	for i, x := range &a.b { // ERROR "f &a.b does not escape"
    22  		if x != 0 {
    23  			return 64*i + int(x)
    24  		}
    25  	}
    26  	return 0
    27  }
    28  
    29  func g(a *A) int { // ERROR "g a does not escape"
    30  	for i, x := range &a.b { // ERROR "g &a.b does not escape"
    31  		if x != 0 {
    32  			return 64*i + int(x)
    33  		}
    34  	}
    35  	return 0
    36  }
    37  
    38  func h(a *B) *uint64 { // ERROR "leaking param: a to result ~r1 level=1"
    39  	for i, x := range &a.b { // ERROR "h &a.b does not escape"
    40  		if i == 0 {
    41  			return x
    42  		}
    43  	}
    44  	return nil
    45  }
    46  
    47  func h2(a *B) *uint64 { // ERROR "leaking param: a to result ~r1 level=1"
    48  	p := &a.b // ERROR "h2 &a.b does not escape"
    49  	for i, x := range p {
    50  		if i == 0 {
    51  			return x
    52  		}
    53  	}
    54  	return nil
    55  }
    56  
    57  // Seems like below should be level=1, not 0.
    58  func k(a B) *uint64 { // ERROR "leaking param: a to result ~r1 level=0"
    59  	for i, x := range &a.b { // ERROR "k &a.b does not escape"
    60  		if i == 0 {
    61  			return x
    62  		}
    63  	}
    64  	return nil
    65  }
    66  
    67  var sink *uint64
    68  
    69  func main() {
    70  	var a1, a2 A
    71  	var b1, b2, b3, b4 B
    72  	var x1, x2, x3, x4 uint64 // ERROR "moved to heap: x1" "moved to heap: x3"
    73  	b1.b[0] = &x1             // ERROR "&x1 escapes to heap"
    74  	b2.b[0] = &x2             // ERROR "main &x2 does not escape"
    75  	b3.b[0] = &x3             // ERROR "&x3 escapes to heap"
    76  	b4.b[0] = &x4             // ERROR "main &x4 does not escape"
    77  	f(a1)
    78  	g(&a2)         // ERROR "main &a2 does not escape"
    79  	sink = h(&b1)  // ERROR "main &b1 does not escape"
    80  	h(&b2)         // ERROR "main &b2 does not escape"
    81  	sink = h2(&b1) // ERROR "main &b1 does not escape"
    82  	h2(&b4)        // ERROR "main &b4 does not escape"
    83  	x1 = 17
    84  	println("*sink=", *sink) // Verify that sink addresses x1
    85  	x3 = 42
    86  	sink = k(b3)
    87  	println("*sink=", *sink) // Verify that sink addresses x3
    88  }