golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/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 "bytes" 12 "fmt" 13 "go/ast" 14 "go/types" 15 "io" 16 "os" 17 "strings" 18 ) 19 20 type sanity struct { 21 reporter io.Writer 22 fn *Function 23 block *BasicBlock 24 instrs map[Instruction]struct{} 25 insane bool 26 } 27 28 // sanityCheck performs integrity checking of the SSA representation 29 // of the function fn and returns true if it was valid. Diagnostics 30 // are written to reporter if non-nil, os.Stderr otherwise. Some 31 // diagnostics are only warnings and do not imply a negative result. 32 // 33 // Sanity-checking is intended to facilitate the debugging of code 34 // transformation passes. 35 func sanityCheck(fn *Function, reporter io.Writer) bool { 36 if reporter == nil { 37 reporter = os.Stderr 38 } 39 return (&sanity{reporter: reporter}).checkFunction(fn) 40 } 41 42 // mustSanityCheck is like sanityCheck but panics instead of returning 43 // a negative result. 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 } else if !types.Identical(instr.typ, e.Type()) { 114 s.errorf("phi node '%s' has a different type (%s) for edge #%d from %s (%s)", 115 instr.Comment, instr.Type(), i, s.block.Preds[i], e.Type()) 116 } 117 } 118 } 119 120 case *Alloc: 121 if !instr.Heap { 122 found := false 123 for _, l := range s.fn.Locals { 124 if l == instr { 125 found = true 126 break 127 } 128 } 129 if !found { 130 s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr) 131 } 132 } 133 134 case *BinOp: 135 case *Call: 136 if common := instr.Call; common.IsInvoke() { 137 if !types.IsInterface(common.Value.Type()) { 138 s.errorf("invoke on %s (%s) which is not an interface type (or type param)", common.Value, common.Value.Type()) 139 } 140 } 141 case *ChangeInterface: 142 case *ChangeType: 143 case *SliceToArrayPointer: 144 case *Convert: 145 if from := instr.X.Type(); !isBasicConvTypes(typeSetOf(from)) { 146 if to := instr.Type(); !isBasicConvTypes(typeSetOf(to)) { 147 s.errorf("convert %s -> %s: at least one type must be basic (or all basic, []byte, or []rune)", from, to) 148 } 149 } 150 case *MultiConvert: 151 case *Defer: 152 case *Extract: 153 case *Field: 154 case *FieldAddr: 155 case *Go: 156 case *Index: 157 case *IndexAddr: 158 case *Lookup: 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 // TODO(adonovan): implement checks. 187 default: 188 panic(fmt.Sprintf("Unknown instruction type: %T", instr)) 189 } 190 191 if call, ok := instr.(CallInstruction); ok { 192 if call.Common().Signature() == nil { 193 s.errorf("nil signature: %s", call) 194 } 195 } 196 197 // Check that value-defining instructions have valid types 198 // and a valid referrer list. 199 if v, ok := instr.(Value); ok { 200 t := v.Type() 201 if t == nil { 202 s.errorf("no type: %s = %s", v.Name(), v) 203 } else if t == tRangeIter || t == tDeferStack { 204 // not a proper type; ignore. 205 } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 { 206 s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t) 207 } 208 s.checkReferrerList(v) 209 } 210 211 // Untyped constants are legal as instruction Operands(), 212 // for example: 213 // _ = "foo"[0] 214 // or: 215 // if wordsize==64 {...} 216 217 // All other non-Instruction Values can be found via their 218 // enclosing Function or Package. 219 } 220 221 func (s *sanity) checkFinalInstr(instr Instruction) { 222 switch instr := instr.(type) { 223 case *If: 224 if nsuccs := len(s.block.Succs); nsuccs != 2 { 225 s.errorf("If-terminated block has %d successors; expected 2", nsuccs) 226 return 227 } 228 if s.block.Succs[0] == s.block.Succs[1] { 229 s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0]) 230 return 231 } 232 233 case *Jump: 234 if nsuccs := len(s.block.Succs); nsuccs != 1 { 235 s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs) 236 return 237 } 238 239 case *Return: 240 if nsuccs := len(s.block.Succs); nsuccs != 0 { 241 s.errorf("Return-terminated block has %d successors; expected none", nsuccs) 242 return 243 } 244 if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na { 245 s.errorf("%d-ary return in %d-ary function", na, nf) 246 } 247 248 case *Panic: 249 if nsuccs := len(s.block.Succs); nsuccs != 0 { 250 s.errorf("Panic-terminated block has %d successors; expected none", nsuccs) 251 return 252 } 253 254 default: 255 s.errorf("non-control flow instruction at end of block") 256 } 257 } 258 259 func (s *sanity) checkBlock(b *BasicBlock, index int) { 260 s.block = b 261 262 if b.Index != index { 263 s.errorf("block has incorrect Index %d", b.Index) 264 } 265 if b.parent != s.fn { 266 s.errorf("block has incorrect parent %s", b.parent) 267 } 268 269 // Check all blocks are reachable. 270 // (The entry block is always implicitly reachable, 271 // as is the Recover block, if any.) 272 if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 { 273 s.warnf("unreachable block") 274 if b.Instrs == nil { 275 // Since this block is about to be pruned, 276 // tolerating transient problems in it 277 // simplifies other optimizations. 278 return 279 } 280 } 281 282 // Check predecessor and successor relations are dual, 283 // and that all blocks in CFG belong to same function. 284 for _, a := range b.Preds { 285 found := false 286 for _, bb := range a.Succs { 287 if bb == b { 288 found = true 289 break 290 } 291 } 292 if !found { 293 s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs) 294 } 295 if a.parent != s.fn { 296 s.errorf("predecessor %s belongs to different function %s", a, a.parent) 297 } 298 } 299 for _, c := range b.Succs { 300 found := false 301 for _, bb := range c.Preds { 302 if bb == b { 303 found = true 304 break 305 } 306 } 307 if !found { 308 s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds) 309 } 310 if c.parent != s.fn { 311 s.errorf("successor %s belongs to different function %s", c, c.parent) 312 } 313 } 314 315 // Check each instruction is sane. 316 n := len(b.Instrs) 317 if n == 0 { 318 s.errorf("basic block contains no instructions") 319 } 320 var rands [10]*Value // reuse storage 321 for j, instr := range b.Instrs { 322 if instr == nil { 323 s.errorf("nil instruction at index %d", j) 324 continue 325 } 326 if b2 := instr.Block(); b2 == nil { 327 s.errorf("nil Block() for instruction at index %d", j) 328 continue 329 } else if b2 != b { 330 s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j) 331 continue 332 } 333 if j < n-1 { 334 s.checkInstr(j, instr) 335 } else { 336 s.checkFinalInstr(instr) 337 } 338 339 // Check Instruction.Operands. 340 operands: 341 for i, op := range instr.Operands(rands[:0]) { 342 if op == nil { 343 s.errorf("nil operand pointer %d of %s", i, instr) 344 continue 345 } 346 val := *op 347 if val == nil { 348 continue // a nil operand is ok 349 } 350 351 // Check that "untyped" types only appear on constant operands. 352 if _, ok := (*op).(*Const); !ok { 353 if basic, ok := (*op).Type().Underlying().(*types.Basic); ok { 354 if basic.Info()&types.IsUntyped != 0 { 355 s.errorf("operand #%d of %s is untyped: %s", i, instr, basic) 356 } 357 } 358 } 359 360 // Check that Operands that are also Instructions belong to same function. 361 // TODO(adonovan): also check their block dominates block b. 362 if val, ok := val.(Instruction); ok { 363 if val.Block() == nil { 364 s.errorf("operand %d of %s is an instruction (%s) that belongs to no block", i, instr, val) 365 } else if val.Parent() != s.fn { 366 s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent()) 367 } 368 } 369 370 // Check that each function-local operand of 371 // instr refers back to instr. (NB: quadratic) 372 switch val := val.(type) { 373 case *Const, *Global, *Builtin: 374 continue // not local 375 case *Function: 376 if val.parent == nil { 377 continue // only anon functions are local 378 } 379 } 380 381 // TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined. 382 383 if refs := val.Referrers(); refs != nil { 384 for _, ref := range *refs { 385 if ref == instr { 386 continue operands 387 } 388 } 389 s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val) 390 } else { 391 s.errorf("operand %d of %s (%s) has no referrers", i, instr, val) 392 } 393 } 394 } 395 } 396 397 func (s *sanity) checkReferrerList(v Value) { 398 refs := v.Referrers() 399 if refs == nil { 400 s.errorf("%s has missing referrer list", v.Name()) 401 return 402 } 403 for i, ref := range *refs { 404 if _, ok := s.instrs[ref]; !ok { 405 s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref) 406 } 407 } 408 } 409 410 func (s *sanity) checkFunction(fn *Function) bool { 411 // TODO(adonovan): check Function invariants: 412 // - check params match signature 413 // - check transient fields are nil 414 // - warn if any fn.Locals do not appear among block instructions. 415 416 // TODO(taking): Sanity check origin, typeparams, and typeargs. 417 s.fn = fn 418 if fn.Prog == nil { 419 s.errorf("nil Prog") 420 } 421 422 var buf bytes.Buffer 423 _ = fn.String() // must not crash 424 _ = fn.RelString(fn.relPkg()) // must not crash 425 WriteFunction(&buf, fn) // must not crash 426 427 // All functions have a package, except delegates (which are 428 // shared across packages, or duplicated as weak symbols in a 429 // separate-compilation model), and error.Error. 430 if fn.Pkg == nil { 431 if strings.HasPrefix(fn.Synthetic, "from type information (on demand)") || 432 strings.HasPrefix(fn.Synthetic, "wrapper ") || 433 strings.HasPrefix(fn.Synthetic, "bound ") || 434 strings.HasPrefix(fn.Synthetic, "thunk ") || 435 strings.HasSuffix(fn.name, "Error") || 436 strings.HasPrefix(fn.Synthetic, "instance ") || 437 strings.HasPrefix(fn.Synthetic, "instantiation ") || 438 (fn.parent != nil && len(fn.typeargs) > 0) /* anon fun in instance */ { 439 // ok 440 } else { 441 s.errorf("nil Pkg") 442 } 443 } 444 if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn { 445 if len(fn.typeargs) > 0 && fn.Prog.mode&InstantiateGenerics != 0 { 446 // ok (instantiation with InstantiateGenerics on) 447 } else if fn.topLevelOrigin != nil && len(fn.typeargs) > 0 { 448 // ok (we always have the syntax set for instantiation) 449 } else if _, rng := fn.syntax.(*ast.RangeStmt); rng && fn.Synthetic == "range-over-func yield" { 450 // ok (range-func-yields are both synthetic and keep syntax) 451 } else { 452 s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn) 453 } 454 } 455 for i, l := range fn.Locals { 456 if l.Parent() != fn { 457 s.errorf("Local %s at index %d has wrong parent", l.Name(), i) 458 } 459 if l.Heap { 460 s.errorf("Local %s at index %d has Heap flag set", l.Name(), i) 461 } 462 } 463 // Build the set of valid referrers. 464 s.instrs = make(map[Instruction]struct{}) 465 for _, b := range fn.Blocks { 466 for _, instr := range b.Instrs { 467 s.instrs[instr] = struct{}{} 468 } 469 } 470 for i, p := range fn.Params { 471 if p.Parent() != fn { 472 s.errorf("Param %s at index %d has wrong parent", p.Name(), i) 473 } 474 // Check common suffix of Signature and Params match type. 475 if sig := fn.Signature; sig != nil { 476 j := i - len(fn.Params) + sig.Params().Len() // index within sig.Params 477 if j < 0 { 478 continue 479 } 480 if !types.Identical(p.Type(), sig.Params().At(j).Type()) { 481 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()) 482 483 } 484 } 485 s.checkReferrerList(p) 486 } 487 for i, fv := range fn.FreeVars { 488 if fv.Parent() != fn { 489 s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i) 490 } 491 s.checkReferrerList(fv) 492 } 493 494 if fn.Blocks != nil && len(fn.Blocks) == 0 { 495 // Function _had_ blocks (so it's not external) but 496 // they were "optimized" away, even the entry block. 497 s.errorf("Blocks slice is non-nil but empty") 498 } 499 for i, b := range fn.Blocks { 500 if b == nil { 501 s.warnf("nil *BasicBlock at f.Blocks[%d]", i) 502 continue 503 } 504 s.checkBlock(b, i) 505 } 506 if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover { 507 s.errorf("Recover block is not in Blocks slice") 508 } 509 510 s.block = nil 511 for i, anon := range fn.AnonFuncs { 512 if anon.Parent() != fn { 513 s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent()) 514 } 515 if i != int(anon.anonIdx) { 516 s.errorf("AnonFuncs[%d]=%s but %s.anonIdx=%d", i, anon, anon, anon.anonIdx) 517 } 518 } 519 s.fn = nil 520 return !s.insane 521 } 522 523 // sanityCheckPackage checks invariants of packages upon creation. 524 // It does not require that the package is built. 525 // Unlike sanityCheck (for functions), it just panics at the first error. 526 func sanityCheckPackage(pkg *Package) { 527 if pkg.Pkg == nil { 528 panic(fmt.Sprintf("Package %s has no Object", pkg)) 529 } 530 _ = pkg.String() // must not crash 531 532 for name, mem := range pkg.Members { 533 if name != mem.Name() { 534 panic(fmt.Sprintf("%s: %T.Name() = %s, want %s", 535 pkg.Pkg.Path(), mem, mem.Name(), name)) 536 } 537 obj := mem.Object() 538 if obj == nil { 539 // This check is sound because fields 540 // {Global,Function}.object have type 541 // types.Object. (If they were declared as 542 // *types.{Var,Func}, we'd have a non-empty 543 // interface containing a nil pointer.) 544 545 continue // not all members have typechecker objects 546 } 547 if obj.Name() != name { 548 if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") { 549 // Ok. The name of a declared init function varies between 550 // its types.Func ("init") and its ssa.Function ("init#%d"). 551 } else { 552 panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s", 553 pkg.Pkg.Path(), mem, obj.Name(), name)) 554 } 555 } 556 if obj.Pos() != mem.Pos() { 557 panic(fmt.Sprintf("%s Pos=%d obj.Pos=%d", mem, mem.Pos(), obj.Pos())) 558 } 559 } 560 }