Source file test/fixedbugs/issue12588.go

     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 {
    22  		if x != 0 {
    23  			return 64*i + int(x)
    24  		}
    25  	}
    26  	return 0
    27  }
    28  
    29  func g(a *A) int { // ERROR "a does not escape"
    30  	for i, x := range &a.b {
    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 ~r0 level=1"
    39  	for i, x := range &a.b {
    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 ~r0 level=1"
    48  	p := &a.b
    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 ~r0 level=0"
    59  	for i, x := range &a.b {
    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
    74  	b2.b[0] = &x2
    75  	b3.b[0] = &x3
    76  	b4.b[0] = &x4
    77  	f(a1)
    78  	g(&a2)
    79  	sink = h(&b1)
    80  	h(&b2)
    81  	sink = h2(&b1)
    82  	h2(&b4)
    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  }
    89  

View as plain text