1 // Regression: how a field select addresses its base, and how a zeroed
2 // aggregate is written.
3 //
4 // A field select on a local variable must use the VARIABLE's address when the
5 // variable's value is a struct, and must LOAD it when the value is a pointer:
6 // the alloca holds the pointer, so taking the field offset from the alloca
7 // read `o.in.n` out of the slot holding `o` itself. That bug printed 2270074
8 // instead of 41.
9 //
10 // Addressing the struct-valued variable by loading its value first and then
11 // throwing the load away left the load in the instruction list as dead IR.
12 // For a large struct that dead IR is a full-struct copy: flate.NewWriter
13 // (`var dw Writer`, then `dw.d.init(w, level)`) emitted a 640KB load nothing
14 // read, and clang's DAG combiner segfaulted in
15 // SelectionDAG::ReplaceAllUsesWith while combining it. The address is now
16 // resolved before anything is emitted for the operand.
17 //
18 // The same shape produces the aggregate zero store: `var z outer` with `&z`
19 // escaping is a runtime.alloc plus an explicit
20 // `store {outer} zeroinitializer`. One such store is expanded by the backend
21 // into one store per 8 bytes; on flate.Writer's 640KB that was clang's second
22 // crash, in the instruction selector. A zero store of an aggregate is now a
23 // memset, exactly as a zeroed alloca always was.
24 package main
25 26 type inner struct {
27 tab []int32
28 n int64
29 ok bool
30 bad bool
31 }
32 33 func (i *inner) bump(v int64) {
34 i.n = i.n + v
35 }
36 37 type outer struct {
38 in inner
39 tag string
40 }
41 42 // struct-valued local, pointer-receiver method on its field, address escapes
43 func viaStructLocal() (o *outer) {
44 var z outer
45 z.in.bump(41)
46 return &z
47 }
48 49 // pointer-valued local: the select must go through the pointer
50 func viaPointerLocal() (n int64) {
51 o := &outer{}
52 o.in.bump(7)
53 return o.in.n
54 }
55 56 func main() {
57 // Termination: a batch program must still be stoppable, so the entry
58 // handles the channel the runtime closes on SIGINT/SIGTERM.
59 select {
60 case <-shutdown:
61 return
62 default:
63 }
64 65 o := viaStructLocal()
66 if o.in.n != 41 {
67 panic("struct local n")
68 }
69 // every other field of the aggregate must have been zeroed
70 if o.in.ok || o.in.bad {
71 panic("struct local bool not zero")
72 }
73 if o.in.tab != nil {
74 panic("struct local slice not zero")
75 }
76 if o.tag != "" {
77 panic("struct local tag not zero")
78 }
79 80 if viaPointerLocal() != 7 {
81 panic("pointer local n")
82 }
83 84 println("ok")
85 }
86