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 *Phi:
98 if idx == 0 {
99 // It suffices to apply this check to just the first phi node.
100 if dup := findDuplicate(s.block.Preds); dup != nil {
101 s.errorf("phi node in block with duplicate predecessor %s", dup)
102 }
103 } else {
104 prev := s.block.Instrs[idx-1]
105 switch prev.(type) {
106 case *Phi:
107 default:
108 s.errorf("Phi instruction follows a non-Phi: %T", prev)
109 }
110 }
111 if ne, np := len(instr.Edges), len(s.block.Preds); ne != np {
112 s.errorf("phi node has %d edges but %d predecessors", ne, np)
113 } else {
114 for i, e := range instr.Edges {
115 if e == nil {
116 s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment(), i, s.block.Preds[i])
117 } else if !types.Identical(instr.typ, e.Type()) {
118 s.errorf("phi node '%s' has a different type (%s) for edge #%d from %s (%s)",
119 instr.Comment(), instr.Type(), i, s.block.Preds[i], e.Type())
120 }
121 }
122 }
123
124 case *Alloc:
125 if !instr.Heap && !slices.Contains(s.fn.Locals, instr) {
126 s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr)
127 }
128
129 case *BinOp:
130 case *Call:
131 if common := instr.Call; common.IsInvoke() {
132 if !types.IsInterface(common.Value.Type()) {
133 s.errorf("invoke on %s (%s) which is not an interface type (or type param)", common.Value, common.Value.Type())
134 }
135 }
136 case *ChangeInterface:
137 case *ChangeType:
138 case *SliceToArrayPointer:
139 case *SliceToArray:
140 case *Convert:
141 if from := instr.X.Type(); !isBasicConvTypes(from) {
142 if to := instr.Type(); !isBasicConvTypes(to) {
143 s.errorf("convert %s -> %s: at least one type must be basic (or all basic, []byte, or []rune)", from, to)
144 }
145 }
146 case *MultiConvert:
147 case *Defer:
148 case *Extract:
149 case *Field:
150 case *FieldAddr:
151 case *Go:
152 case *Index:
153 case *IndexAddr:
154 case *MapLookup:
155 case *StringLookup:
156 case *MakeChan:
157 case *MakeClosure:
158 numFree := len(instr.Fn.(*Function).FreeVars)
159 numBind := len(instr.Bindings)
160 if numFree != numBind {
161 s.errorf("MakeClosure has %d Bindings for function %s with %d free vars",
162 numBind, instr.Fn, numFree)
163 } else {
164 for i, fv := range instr.Fn.(*Function).FreeVars {
165 if !types.Identical(instr.Bindings[i].Type(), fv.Type()) {
166 s.errorf("MakeClosure binding %d for %s has type %s, expected %s",
167 i, fv.Name(), instr.Bindings[i].Type(), fv.Type())
168 }
169 }
170 }
171 if recv := instr.Type().(*types.Signature).Recv(); recv != nil {
172 s.errorf("MakeClosure's type includes receiver %s", recv.Type())
173 }
174
175 case *MakeInterface:
176 case *MakeMap:
177 case *MakeSlice:
178 case *MapUpdate:
179 case *Next:
180 rng, ok := instr.Iter.(*Range)
181 if !ok {
182 s.errorf("Next: Iter is %T, not *Range", instr.Iter)
183 }
184 var ek, ev types.Type
185 switch xt := typeutil.CoreType(rng.X.Type()).(type) {
186 case *types.Basic:
187 if types.Default(xt) != tString {
188 s.errorf("Next: basic operand of Next.Iter (Range) is %s, want string or untyped string", xt)
189 }
190 ek, ev = tInt, tRune
191 case *types.Map:
192 ek, ev = xt.Key(), xt.Elem()
193 }
194
195 res := instr.Type().(*types.Tuple) // (ok bool, k K, v V), but K or V may be invalid if unused
196 if !types.Identical(res.At(1).Type(), ek) && res.At(1).Type() != tInvalid {
197 s.errorf("Next: key type %s does not match map key type %s", res.At(1).Type(), ek)
198 }
199 if !types.Identical(res.At(2).Type(), ev) && res.At(2).Type() != tInvalid {
200 s.errorf("Next: value type %s does not match map value type %s", res.At(2).Type(), ev)
201 }
202
203 case *Range:
204 case *RunDefers:
205 case *Select:
206 case *Send:
207 case *Slice:
208 case *Store:
209 if !types.Identical(instr.Val.Type(), typeutil.CoreType(instr.Addr.Type()).(*types.Pointer).Elem()) {
210 s.errorf("Store: value type %s does not match address type %s",
211 instr.Val.Type(), instr.Addr.Type())
212 }
213 case *TypeAssert:
214 case *UnOp:
215 case *debugRef:
216 case *BlankStore:
217 case *Load:
218 case *Recv:
219 case *TypeSwitch:
220 case *CompositeValue:
221 default:
222 panic(fmt.Sprintf("Unknown instruction type: %T", instr))
223 }
224
225 if call, ok := instr.(CallInstruction); ok {
226 if call.Common().Signature() == nil {
227 s.errorf("nil signature: %s", call)
228 }
229 }
230
231 // Check that value-defining instructions have valid types
232 // and a valid referrer list.
233 if v, ok := instr.(Value); ok {
234 t := v.Type()
235 if t == nil {
236 s.errorf("no type: %s = %s", v.Name(), v)
237 } else if t == tDeferStack {
238 // not a proper type; ignore.
239 } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
240 if _, ok := v.(*Const); !ok {
241 s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t)
242 }
243 }
244 s.checkReferrerList(v)
245 }
246
247 // Untyped constants are legal as instruction Operands(),
248 // for example:
249 // _ = "foo"[0]
250 // or:
251 // if wordsize==64 {...}
252
253 // All other non-Instruction Values can be found via their
254 // enclosing Function or Package.
255 }
256
257 func (s *sanity) checkFinalInstr(instr Instruction) {
258 switch instr := instr.(type) {
259 case *If:
260 if nsuccs := len(s.block.Succs); nsuccs != 2 {
261 s.errorf("If-terminated block has %d successors; expected 2", nsuccs)
262 return
263 }
264 if s.block.Succs[0] == s.block.Succs[1] {
265 s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0])
266 return
267 }
268
269 case *Jump:
270 if nsuccs := len(s.block.Succs); nsuccs != 1 {
271 s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs)
272 return
273 }
274
275 case *Return:
276 if nsuccs := len(s.block.Succs); nsuccs != 0 {
277 s.errorf("Return-terminated block has %d successors; expected none", nsuccs)
278 return
279 }
280 if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na {
281 s.errorf("%d-ary return in %d-ary function", na, nf)
282 }
283
284 case *Panic:
285 if nsuccs := len(s.block.Succs); nsuccs != 0 {
286 s.errorf("Panic-terminated block has %d successors; expected none", nsuccs)
287 return
288 }
289
290 case *Unreachable:
291 if nsuccs := len(s.block.Succs); nsuccs != 0 {
292 s.errorf("Unreachable-terminated block has %d successors; expected none", nsuccs)
293 return
294 }
295
296 case *ConstantSwitch:
297 if nsuccs := len(s.block.Succs); nsuccs != len(instr.Conds) {
298 s.errorf("ConstantSwitch-terminated block has %d successors for %d constants",
299 nsuccs, len(instr.Conds))
300 return
301 }
302
303 default:
304 s.errorf("non-control flow instruction at end of block")
305 }
306 }
307
308 func (s *sanity) checkBlock(b *BasicBlock, index int) {
309 s.block = b
310
311 if b.Index != index {
312 s.errorf("block has incorrect Index %d", b.Index)
313 }
314 if b.parent != s.fn {
315 s.errorf("block has incorrect parent %s", b.parent)
316 }
317
318 // Check all blocks are reachable.
319 // (The entry block is always implicitly reachable,
320 // as is the Recover block, if any.)
321 if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 {
322 s.warnf("unreachable block")
323 if b.Instrs == nil {
324 // Since this block is about to be pruned,
325 // tolerating transient problems in it
326 // simplifies other optimizations.
327 return
328 }
329 }
330
331 // Check predecessor and successor relations are dual,
332 // and that all blocks in CFG belong to same function.
333 for _, a := range b.Preds {
334 if !slices.Contains(a.Succs, b) {
335 s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs)
336 }
337 if a.parent != s.fn {
338 s.errorf("predecessor %s belongs to different function %s", a, a.parent)
339 }
340 }
341 for _, c := range b.Succs {
342 if !slices.Contains(c.Preds, b) {
343 s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds)
344 }
345 if c.parent != s.fn {
346 s.errorf("successor %s belongs to different function %s", c, c.parent)
347 }
348 }
349
350 // Check each instruction is sane.
351 n := len(b.Instrs)
352 if n == 0 {
353 s.errorf("basic block contains no instructions")
354 }
355 var rands [10]*Value // reuse storage
356 for j, instr := range b.Instrs {
357 if instr == nil {
358 s.errorf("nil instruction at index %d", j)
359 continue
360 }
361 if b2 := instr.Block(); b2 == nil {
362 s.errorf("nil Block() for instruction at index %d", j)
363 continue
364 } else if b2 != b {
365 s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j)
366 continue
367 }
368 if j < n-1 {
369 s.checkInstr(j, instr)
370 } else {
371 s.checkFinalInstr(instr)
372 }
373
374 // Check Instruction.Operands.
375 operands:
376 for i, op := range instr.Operands(rands[:0]) {
377 if op == nil {
378 s.errorf("nil operand pointer %d of %s", i, instr)
379 continue
380 }
381 val := *op
382 if val == nil {
383 continue // a nil operand is ok
384 }
385
386 // Check that "untyped" types only appear on constant operands.
387 if _, ok := (*op).(*Const); !ok {
388 if basic, ok := (*op).Type().Underlying().(*types.Basic); ok {
389 if basic.Info()&types.IsUntyped != 0 {
390 s.errorf("operand #%d of %s is untyped: %s", i, instr, basic)
391 }
392 }
393 }
394
395 // Check that Operands that are also Instructions belong to same function.
396 // TODO(adonovan): also check their block dominates block b.
397 if val, ok := val.(Instruction); ok {
398 if val.Block() == nil {
399 s.errorf("operand %d of %s is an instruction (%s) that belongs to no block", i, instr, val)
400 } else if val.Parent() != s.fn {
401 s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent())
402 }
403 }
404
405 // Check that each function-local operand of
406 // instr refers back to instr. (NB: quadratic)
407 switch val := val.(type) {
408 case *Const, *Global, *Builtin:
409 continue // not local
410 case *Function:
411 if val.parent == nil {
412 continue // only anon functions are local
413 }
414 }
415
416 // TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined.
417
418 if refs := val.Referrers(); refs != nil {
419 for _, ref := range *refs {
420 if ref == instr {
421 continue operands
422 }
423 }
424 s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val)
425 } else {
426 s.errorf("operand %d of %s (%s) has no referrers", i, instr, val)
427 }
428 }
429 }
430 }
431
432 func (s *sanity) checkReferrerList(v Value) {
433 refs := v.Referrers()
434 if refs == nil {
435 s.errorf("%s has missing referrer list", v.Name())
436 return
437 }
438 for i, ref := range *refs {
439 if _, ok := s.instrs[ref]; !ok {
440 if val, ok := ref.(Value); ok {
441 s.errorf("%s.Referrers()[%d] = %s = %s is not an instruction belonging to this function", v.Name(), i, val.Name(), val)
442 } else {
443 s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref)
444 }
445 }
446 }
447 }
448
449 func (s *sanity) checkFunctionParams() {
450 signature := s.fn.Signature
451 params := s.fn.Params
452
453 // startSigParams is the start of signature.Params() within params.
454 startSigParams := 0
455 if signature.Recv() != nil {
456 startSigParams = 1
457 }
458
459 if startSigParams+signature.Params().Len() != len(params) {
460 s.errorf("function has %d parameters in signature but has %d after building",
461 startSigParams+signature.Params().Len(), len(params))
462 return
463 }
464
465 for i, param := range params {
466 var sigType types.Type
467 si := i - startSigParams
468 if si < 0 {
469 sigType = signature.Recv().Type()
470 } else {
471 sigType = signature.Params().At(si).Type()
472 }
473
474 if !types.Identical(sigType, param.Type()) {
475 s.errorf("expect type %s in signature but got type %s in param %d", sigType, param.Type(), i)
476 }
477 }
478 }
479
480 // checkTransientFields checks whether all transient fields of Function are cleared.
481 func (s *sanity) checkTransientFields() {
482 fn := s.fn
483 if fn.build != nil {
484 s.errorf("function transient field 'build' is not nil")
485 }
486 if fn.currentBlock != nil {
487 s.errorf("function transient field 'currentBlock' is not nil")
488 }
489 if fn.vars != nil {
490 s.errorf("function transient field 'vars' is not nil")
491 }
492 if fn.results != nil {
493 s.errorf("function transient field 'results' is not nil")
494 }
495 if fn.returnVars != nil {
496 s.errorf("function transient field 'returnVars' is not nil")
497 }
498 if fn.targets != nil {
499 s.errorf("function transient field 'targets' is not nil")
500 }
501 if fn.lblocks != nil {
502 s.errorf("function transient field 'lblocks' is not nil")
503 }
504 if fn.subst != nil {
505 s.errorf("function transient field 'subst' is not nil")
506 }
507 if fn.jump != nil {
508 s.errorf("function transient field 'jump' is not nil")
509 }
510 if fn.deferstack != nil {
511 s.errorf("function transient field 'deferstack' is not nil")
512 }
513 if fn.source != nil {
514 s.errorf("function transient field 'source' is not nil")
515 }
516 if fn.exits != nil {
517 s.errorf("function transient field 'exits' is not nil")
518 }
519 if fn.uniq != 0 {
520 s.errorf("function transient field 'uniq' is not zero")
521 }
522 }
523
524 func (s *sanity) checkFunction(fn *Function) bool {
525 s.fn = fn
526 s.checkFunctionParams()
527 s.checkTransientFields()
528
529 // TODO(taking): Sanity check origin, typeparams, and typeargs.
530 if fn.Prog == nil {
531 s.errorf("nil Prog")
532 }
533
534 var buf bytes.Buffer
535 _ = fn.String() // must not crash
536 _ = fn.RelString(fn.relPkg()) // must not crash
537 WriteFunction(&buf, fn) // must not crash
538
539 // All functions have a package, except delegates (which are
540 // shared across packages, or duplicated as weak symbols in a
541 // separate-compilation model), and error.Error.
542 if fn.Pkg == nil {
543 if strings.HasPrefix(fn.Synthetic, "from type information (on demand)") ||
544 strings.HasPrefix(fn.Synthetic, "wrapper ") ||
545 strings.HasPrefix(fn.Synthetic, "bound ") ||
546 strings.HasPrefix(fn.Synthetic, "thunk ") ||
547 strings.HasSuffix(fn.name, "Error") ||
548 strings.HasPrefix(fn.Synthetic, "instance ") ||
549 strings.HasPrefix(fn.Synthetic, "instantiation ") ||
550 fn.parent != nil && fn.parent.hasTypeArgs() /* anon fun in instance */ {
551 // ok
552 } else {
553 s.errorf("nil Pkg")
554 }
555 }
556 if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn {
557 if fn.hasTypeArgs() && fn.Prog.mode&InstantiateGenerics != 0 {
558 // ok (instantiation with InstantiateGenerics on)
559 } else if fn.hasTypeArgs() && fn.topLevelOrigin != nil {
560 // ok (we always have the syntax set for instantiation)
561 } else if _, rng := fn.syntax.(*ast.RangeStmt); rng && fn.Synthetic == "range-over-func yield" {
562 // ok (range-func-yields are both synthetic and keep syntax)
563 } else {
564 s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn)
565 }
566 }
567
568 // Build the set of valid referrers.
569 s.instrs = make(map[Instruction]struct{})
570
571 // instrs are the instructions that are present in the function.
572 for instr := range fn.instrs() {
573 s.instrs[instr] = unit{}
574 }
575
576 // Check all Locals allocations appear in the function instruction.
577 for i, l := range fn.Locals {
578 if _, present := s.instrs[l]; !present {
579 s.warnf("function doesn't contain Local alloc %s", l.Name())
580 }
581
582 if l.Parent() != fn {
583 s.errorf("Local %s at index %d has wrong parent", l.Name(), i)
584 }
585 if l.Heap {
586 s.errorf("Local %s at index %d has Heap flag set", l.Name(), i)
587 }
588 }
589 for i, p := range fn.Params {
590 if p.Parent() != fn {
591 s.errorf("Param %s at index %d has wrong parent", p.Name(), i)
592 }
593 // Check common suffix of Signature and Params match type.
594 if sig := fn.Signature; sig != nil {
595 j := i - len(fn.Params) + sig.Params().Len() // index within sig.Params
596 if j < 0 {
597 continue
598 }
599 if !types.Identical(p.Type(), sig.Params().At(j).Type()) {
600 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())
601 }
602 }
603
604 s.checkReferrerList(p)
605 }
606 for i, fv := range fn.FreeVars {
607 if fv.Parent() != fn {
608 s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i)
609 }
610 s.checkReferrerList(fv)
611 }
612
613 if fn.Blocks != nil && len(fn.Blocks) == 0 {
614 // Function _had_ blocks (so it's not external) but
615 // they were "optimized" away, even the entry block.
616 s.errorf("Blocks slice is non-nil but empty")
617 }
618 for i, b := range fn.Blocks {
619 if b == nil {
620 s.warnf("nil *BasicBlock at f.Blocks[%d]", i)
621 continue
622 }
623 s.checkBlock(b, i)
624 }
625 if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover {
626 s.errorf("Recover block is not in Blocks slice")
627 }
628
629 s.block = nil
630 for i, anon := range fn.AnonFuncs {
631 if anon.Parent() != fn {
632 s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent())
633 }
634 if i != int(anon.anonIdx) {
635 s.errorf("AnonFuncs[%d]=%s but %s.anonIdx=%d", i, anon, anon, anon.anonIdx)
636 }
637 }
638 s.fn = nil
639 return !s.insane
640 }
641
642 // sanityCheckPackage checks invariants of packages upon creation.
643 // It does not require that the package is built.
644 // Unlike sanityCheck (for functions), it just panics at the first error.
645 func sanityCheckPackage(pkg *Package) {
646 if pkg.Pkg == nil {
647 panic(fmt.Sprintf("Package %s has no Object", pkg))
648 }
649 if pkg.info != nil {
650 panic(fmt.Sprintf("package %s field 'info' is not cleared", pkg))
651 }
652 if pkg.files != nil {
653 panic(fmt.Sprintf("package %s field 'files' is not cleared", pkg))
654 }
655 if pkg.created != nil {
656 panic(fmt.Sprintf("package %s field 'created' is not cleared", pkg))
657 }
658 if pkg.initVersion != nil {
659 panic(fmt.Sprintf("package %s field 'initVersion' is not cleared", pkg))
660 }
661
662 _ = pkg.String() // must not crash
663
664 for name, mem := range pkg.Members {
665 if name != mem.Name() {
666 panic(fmt.Sprintf("%s: %T.Name() = %s, want %s",
667 pkg.Pkg.Path(), mem, mem.Name(), name))
668 }
669 obj := mem.Object()
670 if obj == nil {
671 // This check is sound because fields
672 // {Global,Function}.object have type
673 // types.Object. (If they were declared as
674 // *types.{Var,Func}, we'd have a non-empty
675 // interface containing a nil pointer.)
676
677 continue // not all members have typechecker objects
678 }
679 if obj.Name() != name {
680 if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") {
681 // Ok. The name of a declared init function varies between
682 // its types.Func ("init") and its ir.Function ("init#%d").
683 } else {
684 panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s",
685 pkg.Pkg.Path(), mem, obj.Name(), name))
686 }
687 }
688 }
689 }