cmd/compile: stop race instrumentation from clobbering frame pointer

There is an optimization rule that removes calls to racefuncenter and
racefuncexit, if there are no other race calls in the function. The
rule removes the call to racefuncenter, but it does *not* remove the
store of its argument to the outargs section of the frame. If the
outargs section is now size 0 (because the calls to racefuncenter/exit
were the only calls), then that argument store clobbers the frame
pointer instead.

The fix is to remove the argument store when removing the call to
racefuncenter.  (Racefuncexit doesn't have an argument.)

Change-Id: I183ec4d92bbb4920200e1be27b7b8f66b89a2a0a
Reviewed-on: https://go-review.googlesource.com/c/go/+/248262
Reviewed-by: Robert Griesemer <gri@golang.org>
Run-TryBot: Keith Randall <khr@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/src/cmd/compile/internal/gc/racewalk.go b/src/cmd/compile/internal/gc/racewalk.go
index 6f25137..3552617 100644
--- a/src/cmd/compile/internal/gc/racewalk.go
+++ b/src/cmd/compile/internal/gc/racewalk.go
@@ -42,7 +42,7 @@
 	"internal/cpu",
 }
 
-// Only insert racefuncenterfp/racefuncexit into the following packages.
+// Don't insert racefuncenterfp/racefuncexit into the following packages.
 // Memory accesses in the packages are either uninteresting or will cause false positives.
 var norace_inst_pkgs = []string{"sync", "sync/atomic"}
 
diff --git a/src/cmd/compile/internal/ssa/rewrite.go b/src/cmd/compile/internal/ssa/rewrite.go
index 2152b16..e082bb1 100644
--- a/src/cmd/compile/internal/ssa/rewrite.go
+++ b/src/cmd/compile/internal/ssa/rewrite.go
@@ -1379,6 +1379,15 @@
 			}
 		}
 	}
+	if symNamed(sym, "runtime.racefuncenter") {
+		// If we're removing racefuncenter, remove its argument as well.
+		if v.Args[0].Op != OpStore {
+			return false
+		}
+		mem := v.Args[0].Args[2]
+		v.Args[0].reset(OpCopy)
+		v.Args[0].AddArg(mem)
+	}
 	return true
 }