github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/go/ssa/sanity.go (about)

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