Debian Codegraph @

go/ir/sanity.go

raw
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ir
6
7 // An optional pass for sanity-checking invariants of the IR representation.
8 // Currently it checks CFG invariants but little at the instruction level.
9
10 import (
11 "bytes"
12 "fmt"
13 "go/ast"
14 "go/types"
15 "io"
16 "os"
17 "slices"
18 "strings"
19
20 "honnef.co/go/tools/go/types/typeutil"
21 )
22
23 type sanity struct {
24 reporter io.Writer
25 fn *Function
26 block *BasicBlock
27 instrs map[Instruction]struct{}
28 insane bool
29 }
30
31 // sanityCheck performs integrity checking of the IR representation
32 // of the function fn and returns true if it was valid. Diagnostics
33 // are written to reporter if non-nil, os.Stderr otherwise. Some
34 // diagnostics are only warnings and do not imply a negative result.
35 //
36 // Sanity-checking is intended to facilitate the debugging of code
37 // transformation passes.
38 func sanityCheck(fn *Function, reporter io.Writer) bool {
39 if reporter == nil {
40 reporter = os.Stderr
41 }
42 return (&sanity{reporter: reporter}).checkFunction(fn)
43 }
44
45 // mustSanityCheck is like sanityCheck but panics instead of returning
46 // a negative result.
47 func mustSanityCheck(fn *Function, reporter io.Writer) {
48 if !sanityCheck(fn, reporter) {
49 fn.WriteTo(os.Stderr)
50 panic("SanityCheck failed")
51 }
52 }
53
54 func (s *sanity) diagnostic(prefix, format string, args ...any) {
55 fmt.Fprintf(s.reporter, "%s: function %s", prefix, s.fn)
56 if s.block != nil {
57 fmt.Fprintf(s.reporter, ", block %s", s.block)
58 }
59 io.WriteString(s.reporter, ": ")
60 fmt.Fprintf(s.reporter, format, args...)
61 io.WriteString(s.reporter, "\n")
62 }
63
64 func (s *sanity) errorf(format string, args ...any) {
65 s.insane = true
66 s.diagnostic("Error", format, args...)
67 }
68
69 func (s *sanity) warnf(format string, args ...any) {
70 s.diagnostic("Warning", format, args...)
71 }
72
73 // findDuplicate returns an arbitrary basic block that appeared more
74 // than once in blocks, or nil if all were unique.
75 func findDuplicate(blocks []*BasicBlock) *BasicBlock {
76 if len(blocks) < 2 {
77 return nil
78 }
79 if blocks[0] == blocks[1] {
80 return blocks[0]
81 }
82 // Slow path:
83 m := make(map[*BasicBlock]bool)
84 for _, b := range blocks {
85 if m[b] {
86 return b
87 }
88 m[b] = true
89 }
90 return nil
91 }
92
93 func (s *sanity) checkInstr(idx int, instr Instruction) {
94 switch instr := instr.(type) {
95 case *If, *Jump, *Return, *Panic, *Unreachable, *ConstantSwitch:
96 s.errorf("control flow instruction not at end of block")
97 case *Sigma:
98 if idx > 0 {
99 prev := s.block.Instrs[idx-1]
100 if _, ok := prev.(*Sigma); !ok {
101 s.errorf("Sigma instruction follows a non-Sigma: %T", prev)
102 }
103 }
104 case *Phi:
105 if idx == 0 {
106 // It suffices to apply this check to just the first phi node.
107 if dup := findDuplicate(s.block.Preds); dup != nil {
108 s.errorf("phi node in block with duplicate predecessor %s", dup)
109 }
110 } else {
111 prev := s.block.Instrs[idx-1]
112 switch prev.(type) {
113 case *Phi, *Sigma:
114 default:
115 s.errorf("Phi instruction follows a non-Phi, non-Sigma: %T", prev)
116 }
117 }
118 if ne, np := len(instr.Edges), len(s.block.Preds); ne != np {
119 s.errorf("phi node has %d edges but %d predecessors", ne, np)
120
121 } else {
122 for i, e := range instr.Edges {
123 if e == nil {
124 s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment(), i, s.block.Preds[i])
125 }
126 }
127 }
128
129 case *Alloc:
130 if !instr.Heap && !slices.Contains(s.fn.Locals, instr) {
131 s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr)
132 }
133
134 case *BinOp:
135 case *Call:
136 case *ChangeInterface:
137 case *ChangeType:
138 case *SliceToArrayPointer:
139 case *SliceToArray:
140 case *Convert:
141 tsetInstrX := typeutil.NewTypeSet(instr.X.Type().Underlying())
142 tsetInstr := typeutil.NewTypeSet(instr.Type().Underlying())
143 ok1 := tsetInstr.Any(func(term *types.Term) bool { _, ok := term.Type().Underlying().(*types.Basic); return ok })
144 ok2 := tsetInstrX.Any(func(term *types.Term) bool { _, ok := term.Type().Underlying().(*types.Basic); return ok })
145 if !ok1 && !ok2 {
146 s.errorf("convert %s -> %s: at least one type set must contain basic type", instr.X.Type(), instr.Type())
147 }
148
149 case *MultiConvert:
150 case *Defer:
151 case *Extract:
152 case *Field:
153 case *FieldAddr:
154 case *Go:
155 case *Index:
156 case *IndexAddr:
157 case *MapLookup:
158 case *StringLookup:
159 case *MakeChan:
160 case *MakeClosure:
161 numFree := len(instr.Fn.(*Function).FreeVars)
162 numBind := len(instr.Bindings)
163 if numFree != numBind {
164 s.errorf("MakeClosure has %d Bindings for function %s with %d free vars",
165 numBind, instr.Fn, numFree)
166
167 }
168 if recv := instr.Type().(*types.Signature).Recv(); recv != nil {
169 s.errorf("MakeClosure's type includes receiver %s", recv.Type())
170 }
171
172 case *MakeInterface:
173 case *MakeMap:
174 case *MakeSlice:
175 case *MapUpdate:
176 case *Next:
177 case *Range:
178 case *RunDefers:
179 case *Select:
180 case *Send:
181 case *Slice:
182 case *Store:
183 case *TypeAssert:
184 case *UnOp:
185 case *DebugRef:
186 case *BlankStore:
187 case *Load:
188 case *Parameter:
189 case *Const:
190 case *AggregateConst:
191 case *ArrayConst:
192 case *GenericConst:
193 case *Recv:
194 case *TypeSwitch:
195 case *CompositeValue:
196 default:
197 panic(fmt.Sprintf("Unknown instruction type: %T", instr))
198 }
199
200 if call, ok := instr.(CallInstruction); ok {
201 if call.Common().Signature() == nil {
202 s.errorf("nil signature: %s", call)
203 }
204 }
205
206 // Check that value-defining instructions have valid types
207 // and a valid referrer list.
208 if v, ok := instr.(Value); ok {
209 t := v.Type()
210 if t == nil {
211 s.errorf("no type: %s = %s", v.Name(), v)
212 } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
213 if _, ok := v.(*Const); !ok {
214 s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t)
215 }
216 }
217 s.checkReferrerList(v)
218 }
219
220 // Untyped constants are legal as instruction Operands(),
221 // for example:
222 // _ = "foo"[0]
223 // or:
224 // if wordsize==64 {...}
225
226 // All other non-Instruction Values can be found via their
227 // enclosing Function or Package.
228 }
229
230 func (s *sanity) checkFinalInstr(instr Instruction) {
231 switch instr := instr.(type) {
232 case *If:
233 if nsuccs := len(s.block.Succs); nsuccs != 2 {
234 s.errorf("If-terminated block has %d successors; expected 2", nsuccs)
235 return
236 }
237 if s.block.Succs[0] == s.block.Succs[1] {
238 s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0])
239 return
240 }
241
242 case *Jump:
243 if nsuccs := len(s.block.Succs); nsuccs != 1 {
244 s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs)
245 return
246 }
247
248 case *Return:
249 if nsuccs := len(s.block.Succs); nsuccs != 0 {
250 s.errorf("Return-terminated block has %d successors; expected none", nsuccs)
251 return
252 }
253 if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na {
254 s.errorf("%d-ary return in %d-ary function", na, nf)
255 }
256
257 case *Panic:
258 if nsuccs := len(s.block.Succs); nsuccs != 1 {
259 s.errorf("Panic-terminated block has %d successors; expected one", nsuccs)
260 return
261 }
262
263 case *Unreachable:
264 if nsuccs := len(s.block.Succs); nsuccs != 1 {
265 s.errorf("Unreachable-terminated block has %d successors; expected one", nsuccs)
266 return
267 }
268
269 case *ConstantSwitch:
270
271 default:
272 s.errorf("non-control flow instruction at end of block")
273 }
274 }
275
276 func (s *sanity) checkBlock(b *BasicBlock, index int) {
277 s.block = b
278
279 if b.Index != index {
280 s.errorf("block has incorrect Index %d", b.Index)
281 }
282 if b.parent != s.fn {
283 s.errorf("block has incorrect parent %s", b.parent)
284 }
285
286 // Check all blocks are reachable.
287 // (The entry block is always implicitly reachable, the exit block may be unreachable.)
288 if index > 1 && len(b.Preds) == 0 {
289 s.warnf("unreachable block")
290 if b.Instrs == nil {
291 // Since this block is about to be pruned,
292 // tolerating transient problems in it
293 // simplifies other optimizations.
294 return
295 }
296 }
297
298 // Check predecessor and successor relations are dual,
299 // and that all blocks in CFG belong to same function.
300 for _, a := range b.Preds {
301 if !slices.Contains(a.Succs, b) {
302 s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs)
303 }
304 if a.parent != s.fn {
305 s.errorf("predecessor %s belongs to different function %s", a, a.parent)
306 }
307 }
308 for _, c := range b.Succs {
309 if !slices.Contains(c.Preds, b) {
310 s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds)
311 }
312 if c.parent != s.fn {
313 s.errorf("successor %s belongs to different function %s", c, c.parent)
314 }
315 }
316
317 // Check each instruction is sane.
318 n := len(b.Instrs)
319 if n == 0 {
320 s.errorf("basic block contains no instructions")
321 }
322 var rands [10]*Value // reuse storage
323 for j, instr := range b.Instrs {
324 if instr == nil {
325 s.errorf("nil instruction at index %d", j)
326 continue
327 }
328 if b2 := instr.Block(); b2 == nil {
329 s.errorf("nil Block() for instruction at index %d", j)
330 continue
331 } else if b2 != b {
332 s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j)
333 continue
334 }
335 if j < n-1 {
336 s.checkInstr(j, instr)
337 } else {
338 s.checkFinalInstr(instr)
339 }
340
341 // Check Instruction.Operands.
342 operands:
343 for i, op := range instr.Operands(rands[:0]) {
344 if op == nil {
345 s.errorf("nil operand pointer %d of %s", i, instr)
346 continue
347 }
348 val := *op
349 if val == nil {
350 continue // a nil operand is ok
351 }
352
353 // Check that "untyped" types only appear on constant operands.
354 if _, ok := (*op).(*Const); !ok {
355 if basic, ok := types.Unalias((*op).Type()).(*types.Basic); ok {
356 if basic.Info()&types.IsUntyped != 0 {
357 s.errorf("operand #%d of %s is untyped: %s", i, instr, basic)
358 }
359 }
360 }
361
362 // Check that Operands that are also Instructions belong to same function.
363 // TODO(adonovan): also check their block dominates block b.
364 if val, ok := val.(Instruction); ok {
365 if val.Block() == nil {
366 s.errorf("operand %d of %s is an instruction (%s) that belongs to no block", i, instr, val)
367 } else if val.Parent() != s.fn {
368 s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent())
369 }
370 }
371
372 // Check that each function-local operand of
373 // instr refers back to instr. (NB: quadratic)
374 switch val := val.(type) {
375 case *Const, *Global, *Builtin:
376 continue // not local
377 case *Function:
378 if val.parent == nil {
379 continue // only anon functions are local
380 }
381 }
382
383 // TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined.
384
385 if refs := val.Referrers(); refs != nil {
386 for _, ref := range *refs {
387 if ref == instr {
388 continue operands
389 }
390 }
391 s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val)
392 } else {
393 s.errorf("operand %d of %s (%s) has no referrers", i, instr, val)
394 }
395 }
396 }
397 }
398
399 func (s *sanity) checkReferrerList(v Value) {
400 refs := v.Referrers()
401 if refs == nil {
402 s.errorf("%s has missing referrer list", v.Name())
403 return
404 }
405 for i, ref := range *refs {
406 if _, ok := s.instrs[ref]; !ok {
407 if val, ok := ref.(Value); ok {
408 s.errorf("%s.Referrers()[%d] = %s = %s is not an instruction belonging to this function", v.Name(), i, val.Name(), val)
409 } else {
410 s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref)
411 }
412 }
413 }
414 }
415
416 func (s *sanity) checkFunction(fn *Function) bool {
417 // TODO(adonovan): check Function invariants:
418 // - check params match signature
419 // - check transient fields are nil
420 // - warn if any fn.Locals do not appear among block instructions.
421 s.fn = fn
422 if fn.Prog == nil {
423 s.errorf("nil Prog")
424 }
425
426 var buf bytes.Buffer
427 _ = fn.String() // must not crash
428 _ = fn.RelString(fn.pkg()) // must not crash
429 WriteFunction(&buf, fn) // must not crash
430
431 // All functions have a package, except delegates (which are
432 // shared across packages, or duplicated as weak symbols in a
433 // separate-compilation model), and error.Error.
434 if fn.Pkg == nil {
435 switch fn.Synthetic {
436 case SyntheticWrapper, SyntheticBound, SyntheticThunk, SyntheticGeneric:
437 default:
438 if !strings.HasSuffix(fn.name, "Error") {
439 s.errorf("nil Pkg")
440 }
441 }
442 }
443 if syn, src := fn.Synthetic == 0, fn.source != nil; src != syn {
444 if _, ok := fn.source.(*ast.RangeStmt); !ok || fn.Synthetic != SyntheticRangeOverFuncYield {
445 // Only range-over-func yield functions are synthetic and have syntax
446 s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn)
447 }
448 }
449 for i, l := range fn.Locals {
450 if l.Parent() != fn {
451 s.errorf("Local %s at index %d has wrong parent", l.Name(), i)
452 }
453 if l.Heap {
454 s.errorf("Local %s at index %d has Heap flag set", l.Name(), i)
455 }
456 }
457 // Build the set of valid referrers.
458 s.instrs = make(map[Instruction]struct{})
459 for _, b := range fn.Blocks {
460 for _, instr := range b.Instrs {
461 s.instrs[instr] = struct{}{}
462 }
463 }
464 for i, p := range fn.Params {
465 if p.Parent() != fn {
466 s.errorf("Param %s at index %d has wrong parent", p.Name(), i)
467 }
468 // Check common suffix of Signature and Params match type.
469 if sig := fn.Signature; sig != nil {
470 j := i - len(fn.Params) + sig.Params().Len() // index within sig.Params
471 if j < 0 {
472 continue
473 }
474 if !types.Identical(p.Type(), sig.Params().At(j).Type()) {
475 s.errorf("Param %s at index %d has wrong type (%s, versus %s in Signature)", p.Name(), i, p.Type(), sig.Params().At(j).Type())
476
477 }
478 }
479
480 s.checkReferrerList(p)
481 }
482 for i, fv := range fn.FreeVars {
483 if fv.Parent() != fn {
484 s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i)
485 }
486 s.checkReferrerList(fv)
487 }
488
489 if fn.Blocks != nil && len(fn.Blocks) == 0 {
490 // Function _had_ blocks (so it's not external) but
491 // they were "optimized" away, even the entry block.
492 s.errorf("Blocks slice is non-nil but empty")
493 }
494 for i, b := range fn.Blocks {
495 if b == nil {
496 s.warnf("nil *BasicBlock at f.Blocks[%d]", i)
497 continue
498 }
499 s.checkBlock(b, i)
500 }
501
502 s.block = nil
503 for i, anon := range fn.AnonFuncs {
504 if anon.Parent() != fn {
505 s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent())
506 }
507 }
508 s.fn = nil
509 return !s.insane
510 }
511
512 // sanityCheckPackage checks invariants of packages upon creation.
513 // It does not require that the package is built.
514 // Unlike sanityCheck (for functions), it just panics at the first error.
515 func sanityCheckPackage(pkg *Package) {
516 if pkg.Pkg == nil {
517 panic(fmt.Sprintf("Package %s has no Object", pkg))
518 }
519 _ = pkg.String() // must not crash
520
521 for name, mem := range pkg.Members {
522 if name != mem.Name() {
523 panic(fmt.Sprintf("%s: %T.Name() = %s, want %s",
524 pkg.Pkg.Path(), mem, mem.Name(), name))
525 }
526 obj := mem.Object()
527 if obj == nil {
528 // This check is sound because fields
529 // {Global,Function}.object have type
530 // types.Object. (If they were declared as
531 // *types.{Var,Func}, we'd have a non-empty
532 // interface containing a nil pointer.)
533
534 continue // not all members have typechecker objects
535 }
536 if obj.Name() != name {
537 if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") {
538 // Ok. The name of a declared init function varies between
539 // its types.Func ("init") and its ir.Function ("init#%d").
540 } else {
541 panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s",
542 pkg.Pkg.Path(), mem, obj.Name(), name))
543 }
544 }
545 }
546 }