github.com/golangci/go-tools@v0.0.0-20190318060251-af6baa5dc196/ssa/func.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 // This file implements the Function and BasicBlock types. 8 9 import ( 10 "bytes" 11 "fmt" 12 "go/ast" 13 "go/token" 14 "go/types" 15 "io" 16 "os" 17 "strings" 18 ) 19 20 // addEdge adds a control-flow graph edge from from to to. 21 func addEdge(from, to *BasicBlock) { 22 from.Succs = append(from.Succs, to) 23 to.Preds = append(to.Preds, from) 24 } 25 26 // Parent returns the function that contains block b. 27 func (b *BasicBlock) Parent() *Function { return b.parent } 28 29 // String returns a human-readable label of this block. 30 // It is not guaranteed unique within the function. 31 // 32 func (b *BasicBlock) String() string { 33 return fmt.Sprintf("%d", b.Index) 34 } 35 36 // emit appends an instruction to the current basic block. 37 // If the instruction defines a Value, it is returned. 38 // 39 func (b *BasicBlock) emit(i Instruction) Value { 40 i.setBlock(b) 41 b.Instrs = append(b.Instrs, i) 42 v, _ := i.(Value) 43 return v 44 } 45 46 // predIndex returns the i such that b.Preds[i] == c or panics if 47 // there is none. 48 func (b *BasicBlock) predIndex(c *BasicBlock) int { 49 for i, pred := range b.Preds { 50 if pred == c { 51 return i 52 } 53 } 54 panic(fmt.Sprintf("no edge %s -> %s", c, b)) 55 } 56 57 // hasPhi returns true if b.Instrs contains φ-nodes. 58 func (b *BasicBlock) hasPhi() bool { 59 _, ok := b.Instrs[0].(*Phi) 60 return ok 61 } 62 63 func (b *BasicBlock) Phis() []Instruction { 64 return b.phis() 65 } 66 67 // phis returns the prefix of b.Instrs containing all the block's φ-nodes. 68 func (b *BasicBlock) phis() []Instruction { 69 for i, instr := range b.Instrs { 70 if _, ok := instr.(*Phi); !ok { 71 return b.Instrs[:i] 72 } 73 } 74 return nil // unreachable in well-formed blocks 75 } 76 77 // replacePred replaces all occurrences of p in b's predecessor list with q. 78 // Ordinarily there should be at most one. 79 // 80 func (b *BasicBlock) replacePred(p, q *BasicBlock) { 81 for i, pred := range b.Preds { 82 if pred == p { 83 b.Preds[i] = q 84 } 85 } 86 } 87 88 // replaceSucc replaces all occurrences of p in b's successor list with q. 89 // Ordinarily there should be at most one. 90 // 91 func (b *BasicBlock) replaceSucc(p, q *BasicBlock) { 92 for i, succ := range b.Succs { 93 if succ == p { 94 b.Succs[i] = q 95 } 96 } 97 } 98 99 func (b *BasicBlock) RemovePred(p *BasicBlock) { 100 b.removePred(p) 101 } 102 103 // removePred removes all occurrences of p in b's 104 // predecessor list and φ-nodes. 105 // Ordinarily there should be at most one. 106 // 107 func (b *BasicBlock) removePred(p *BasicBlock) { 108 phis := b.phis() 109 110 // We must preserve edge order for φ-nodes. 111 j := 0 112 for i, pred := range b.Preds { 113 if pred != p { 114 b.Preds[j] = b.Preds[i] 115 // Strike out φ-edge too. 116 for _, instr := range phis { 117 phi := instr.(*Phi) 118 phi.Edges[j] = phi.Edges[i] 119 } 120 j++ 121 } 122 } 123 // Nil out b.Preds[j:] and φ-edges[j:] to aid GC. 124 for i := j; i < len(b.Preds); i++ { 125 b.Preds[i] = nil 126 for _, instr := range phis { 127 instr.(*Phi).Edges[i] = nil 128 } 129 } 130 b.Preds = b.Preds[:j] 131 for _, instr := range phis { 132 phi := instr.(*Phi) 133 phi.Edges = phi.Edges[:j] 134 } 135 } 136 137 // Destinations associated with unlabelled for/switch/select stmts. 138 // We push/pop one of these as we enter/leave each construct and for 139 // each BranchStmt we scan for the innermost target of the right type. 140 // 141 type targets struct { 142 tail *targets // rest of stack 143 _break *BasicBlock 144 _continue *BasicBlock 145 _fallthrough *BasicBlock 146 } 147 148 // Destinations associated with a labelled block. 149 // We populate these as labels are encountered in forward gotos or 150 // labelled statements. 151 // 152 type lblock struct { 153 _goto *BasicBlock 154 _break *BasicBlock 155 _continue *BasicBlock 156 } 157 158 // labelledBlock returns the branch target associated with the 159 // specified label, creating it if needed. 160 // 161 func (f *Function) labelledBlock(label *ast.Ident) *lblock { 162 lb := f.lblocks[label.Obj] 163 if lb == nil { 164 lb = &lblock{_goto: f.newBasicBlock(label.Name)} 165 if f.lblocks == nil { 166 f.lblocks = make(map[*ast.Object]*lblock) 167 } 168 f.lblocks[label.Obj] = lb 169 } 170 return lb 171 } 172 173 // addParam adds a (non-escaping) parameter to f.Params of the 174 // specified name, type and source position. 175 // 176 func (f *Function) addParam(name string, typ types.Type, pos token.Pos) *Parameter { 177 v := &Parameter{ 178 name: name, 179 typ: typ, 180 pos: pos, 181 parent: f, 182 } 183 f.Params = append(f.Params, v) 184 return v 185 } 186 187 func (f *Function) addParamObj(obj types.Object) *Parameter { 188 name := obj.Name() 189 if name == "" { 190 name = fmt.Sprintf("arg%d", len(f.Params)) 191 } 192 param := f.addParam(name, obj.Type(), obj.Pos()) 193 param.object = obj 194 return param 195 } 196 197 // addSpilledParam declares a parameter that is pre-spilled to the 198 // stack; the function body will load/store the spilled location. 199 // Subsequent lifting will eliminate spills where possible. 200 // 201 func (f *Function) addSpilledParam(obj types.Object) { 202 param := f.addParamObj(obj) 203 spill := &Alloc{Comment: obj.Name()} 204 spill.setType(types.NewPointer(obj.Type())) 205 spill.setPos(obj.Pos()) 206 f.objects[obj] = spill 207 f.Locals = append(f.Locals, spill) 208 f.emit(spill) 209 f.emit(&Store{Addr: spill, Val: param}) 210 } 211 212 // startBody initializes the function prior to generating SSA code for its body. 213 // Precondition: f.Type() already set. 214 // 215 func (f *Function) startBody() { 216 f.currentBlock = f.newBasicBlock("entry") 217 f.objects = make(map[types.Object]Value) // needed for some synthetics, e.g. init 218 } 219 220 // createSyntacticParams populates f.Params and generates code (spills 221 // and named result locals) for all the parameters declared in the 222 // syntax. In addition it populates the f.objects mapping. 223 // 224 // Preconditions: 225 // f.startBody() was called. 226 // Postcondition: 227 // len(f.Params) == len(f.Signature.Params) + (f.Signature.Recv() ? 1 : 0) 228 // 229 func (f *Function) createSyntacticParams(recv *ast.FieldList, functype *ast.FuncType) { 230 // Receiver (at most one inner iteration). 231 if recv != nil { 232 for _, field := range recv.List { 233 for _, n := range field.Names { 234 f.addSpilledParam(f.Pkg.info.Defs[n]) 235 } 236 // Anonymous receiver? No need to spill. 237 if field.Names == nil { 238 f.addParamObj(f.Signature.Recv()) 239 } 240 } 241 } 242 243 // Parameters. 244 if functype.Params != nil { 245 n := len(f.Params) // 1 if has recv, 0 otherwise 246 for _, field := range functype.Params.List { 247 for _, n := range field.Names { 248 f.addSpilledParam(f.Pkg.info.Defs[n]) 249 } 250 // Anonymous parameter? No need to spill. 251 if field.Names == nil { 252 f.addParamObj(f.Signature.Params().At(len(f.Params) - n)) 253 } 254 } 255 } 256 257 // Named results. 258 if functype.Results != nil { 259 for _, field := range functype.Results.List { 260 // Implicit "var" decl of locals for named results. 261 for _, n := range field.Names { 262 f.namedResults = append(f.namedResults, f.addLocalForIdent(n)) 263 } 264 } 265 } 266 } 267 268 type setNumable interface { 269 setNum(int) 270 } 271 272 // numberRegisters assigns numbers to all SSA registers 273 // (value-defining Instructions) in f, to aid debugging. 274 // (Non-Instruction Values are named at construction.) 275 // 276 func numberRegisters(f *Function) { 277 v := 0 278 for _, b := range f.Blocks { 279 for _, instr := range b.Instrs { 280 switch instr.(type) { 281 case Value: 282 instr.(setNumable).setNum(v) 283 v++ 284 } 285 } 286 } 287 } 288 289 // buildReferrers populates the def/use information in all non-nil 290 // Value.Referrers slice. 291 // Precondition: all such slices are initially empty. 292 func buildReferrers(f *Function) { 293 var rands []*Value 294 for _, b := range f.Blocks { 295 for _, instr := range b.Instrs { 296 rands = instr.Operands(rands[:0]) // recycle storage 297 for _, rand := range rands { 298 if r := *rand; r != nil { 299 if ref := r.Referrers(); ref != nil { 300 *ref = append(*ref, instr) 301 } 302 } 303 } 304 } 305 } 306 } 307 308 // finishBody() finalizes the function after SSA code generation of its body. 309 func (f *Function) finishBody() { 310 f.objects = nil 311 f.currentBlock = nil 312 f.lblocks = nil 313 314 // Don't pin the AST in memory (except in debug mode). 315 if n := f.syntax; n != nil && !f.debugInfo() { 316 f.syntax = extentNode{n.Pos(), n.End()} 317 } 318 319 // Remove from f.Locals any Allocs that escape to the heap. 320 j := 0 321 for _, l := range f.Locals { 322 if !l.Heap { 323 f.Locals[j] = l 324 j++ 325 } 326 } 327 // Nil out f.Locals[j:] to aid GC. 328 for i := j; i < len(f.Locals); i++ { 329 f.Locals[i] = nil 330 } 331 f.Locals = f.Locals[:j] 332 333 optimizeBlocks(f) 334 335 buildReferrers(f) 336 337 buildDomTree(f) 338 339 if f.Prog.mode&NaiveForm == 0 { 340 // For debugging pre-state of lifting pass: 341 // numberRegisters(f) 342 // f.WriteTo(os.Stderr) 343 lift(f) 344 } 345 346 f.namedResults = nil // (used by lifting) 347 348 numberRegisters(f) 349 350 if f.Prog.mode&PrintFunctions != 0 { 351 printMu.Lock() 352 f.WriteTo(os.Stdout) 353 printMu.Unlock() 354 } 355 356 if f.Prog.mode&SanityCheckFunctions != 0 { 357 mustSanityCheck(f, nil) 358 } 359 } 360 361 func (f *Function) RemoveNilBlocks() { 362 f.removeNilBlocks() 363 } 364 365 // removeNilBlocks eliminates nils from f.Blocks and updates each 366 // BasicBlock.Index. Use this after any pass that may delete blocks. 367 // 368 func (f *Function) removeNilBlocks() { 369 j := 0 370 for _, b := range f.Blocks { 371 if b != nil { 372 b.Index = j 373 f.Blocks[j] = b 374 j++ 375 } 376 } 377 // Nil out f.Blocks[j:] to aid GC. 378 for i := j; i < len(f.Blocks); i++ { 379 f.Blocks[i] = nil 380 } 381 f.Blocks = f.Blocks[:j] 382 } 383 384 // SetDebugMode sets the debug mode for package pkg. If true, all its 385 // functions will include full debug info. This greatly increases the 386 // size of the instruction stream, and causes Functions to depend upon 387 // the ASTs, potentially keeping them live in memory for longer. 388 // 389 func (pkg *Package) SetDebugMode(debug bool) { 390 // TODO(adonovan): do we want ast.File granularity? 391 pkg.debug = debug 392 } 393 394 // debugInfo reports whether debug info is wanted for this function. 395 func (f *Function) debugInfo() bool { 396 return f.Pkg != nil && f.Pkg.debug 397 } 398 399 // addNamedLocal creates a local variable, adds it to function f and 400 // returns it. Its name and type are taken from obj. Subsequent 401 // calls to f.lookup(obj) will return the same local. 402 // 403 func (f *Function) addNamedLocal(obj types.Object) *Alloc { 404 l := f.addLocal(obj.Type(), obj.Pos()) 405 l.Comment = obj.Name() 406 f.objects[obj] = l 407 return l 408 } 409 410 func (f *Function) addLocalForIdent(id *ast.Ident) *Alloc { 411 return f.addNamedLocal(f.Pkg.info.Defs[id]) 412 } 413 414 // addLocal creates an anonymous local variable of type typ, adds it 415 // to function f and returns it. pos is the optional source location. 416 // 417 func (f *Function) addLocal(typ types.Type, pos token.Pos) *Alloc { 418 v := &Alloc{} 419 v.setType(types.NewPointer(typ)) 420 v.setPos(pos) 421 f.Locals = append(f.Locals, v) 422 f.emit(v) 423 return v 424 } 425 426 // lookup returns the address of the named variable identified by obj 427 // that is local to function f or one of its enclosing functions. 428 // If escaping, the reference comes from a potentially escaping pointer 429 // expression and the referent must be heap-allocated. 430 // 431 func (f *Function) lookup(obj types.Object, escaping bool) Value { 432 if v, ok := f.objects[obj]; ok { 433 if alloc, ok := v.(*Alloc); ok && escaping { 434 alloc.Heap = true 435 } 436 return v // function-local var (address) 437 } 438 439 // Definition must be in an enclosing function; 440 // plumb it through intervening closures. 441 if f.parent == nil { 442 panic("no ssa.Value for " + obj.String()) 443 } 444 outer := f.parent.lookup(obj, true) // escaping 445 v := &FreeVar{ 446 name: obj.Name(), 447 typ: outer.Type(), 448 pos: outer.Pos(), 449 outer: outer, 450 parent: f, 451 } 452 f.objects[obj] = v 453 f.FreeVars = append(f.FreeVars, v) 454 return v 455 } 456 457 // emit emits the specified instruction to function f. 458 func (f *Function) emit(instr Instruction) Value { 459 return f.currentBlock.emit(instr) 460 } 461 462 // RelString returns the full name of this function, qualified by 463 // package name, receiver type, etc. 464 // 465 // The specific formatting rules are not guaranteed and may change. 466 // 467 // Examples: 468 // "math.IsNaN" // a package-level function 469 // "(*bytes.Buffer).Bytes" // a declared method or a wrapper 470 // "(*bytes.Buffer).Bytes$thunk" // thunk (func wrapping method; receiver is param 0) 471 // "(*bytes.Buffer).Bytes$bound" // bound (func wrapping method; receiver supplied by closure) 472 // "main.main$1" // an anonymous function in main 473 // "main.init#1" // a declared init function 474 // "main.init" // the synthesized package initializer 475 // 476 // When these functions are referred to from within the same package 477 // (i.e. from == f.Pkg.Object), they are rendered without the package path. 478 // For example: "IsNaN", "(*Buffer).Bytes", etc. 479 // 480 // All non-synthetic functions have distinct package-qualified names. 481 // (But two methods may have the same name "(T).f" if one is a synthetic 482 // wrapper promoting a non-exported method "f" from another package; in 483 // that case, the strings are equal but the identifiers "f" are distinct.) 484 // 485 func (f *Function) RelString(from *types.Package) string { 486 // Anonymous? 487 if f.parent != nil { 488 // An anonymous function's Name() looks like "parentName$1", 489 // but its String() should include the type/package/etc. 490 parent := f.parent.RelString(from) 491 for i, anon := range f.parent.AnonFuncs { 492 if anon == f { 493 return fmt.Sprintf("%s$%d", parent, 1+i) 494 } 495 } 496 497 return f.name // should never happen 498 } 499 500 // Method (declared or wrapper)? 501 if recv := f.Signature.Recv(); recv != nil { 502 return f.relMethod(from, recv.Type()) 503 } 504 505 // Thunk? 506 if f.method != nil { 507 return f.relMethod(from, f.method.Recv()) 508 } 509 510 // Bound? 511 if len(f.FreeVars) == 1 && strings.HasSuffix(f.name, "$bound") { 512 return f.relMethod(from, f.FreeVars[0].Type()) 513 } 514 515 // Package-level function? 516 // Prefix with package name for cross-package references only. 517 if p := f.pkg(); p != nil && p != from { 518 return fmt.Sprintf("%s.%s", p.Path(), f.name) 519 } 520 521 // Unknown. 522 return f.name 523 } 524 525 func (f *Function) relMethod(from *types.Package, recv types.Type) string { 526 return fmt.Sprintf("(%s).%s", relType(recv, from), f.name) 527 } 528 529 // writeSignature writes to buf the signature sig in declaration syntax. 530 func writeSignature(buf *bytes.Buffer, from *types.Package, name string, sig *types.Signature, params []*Parameter) { 531 buf.WriteString("func ") 532 if recv := sig.Recv(); recv != nil { 533 buf.WriteString("(") 534 if n := params[0].Name(); n != "" { 535 buf.WriteString(n) 536 buf.WriteString(" ") 537 } 538 types.WriteType(buf, params[0].Type(), types.RelativeTo(from)) 539 buf.WriteString(") ") 540 } 541 buf.WriteString(name) 542 types.WriteSignature(buf, sig, types.RelativeTo(from)) 543 } 544 545 func (f *Function) pkg() *types.Package { 546 if f.Pkg != nil { 547 return f.Pkg.Pkg 548 } 549 return nil 550 } 551 552 var _ io.WriterTo = (*Function)(nil) // *Function implements io.Writer 553 554 func (f *Function) WriteTo(w io.Writer) (int64, error) { 555 var buf bytes.Buffer 556 WriteFunction(&buf, f) 557 n, err := w.Write(buf.Bytes()) 558 return int64(n), err 559 } 560 561 // WriteFunction writes to buf a human-readable "disassembly" of f. 562 func WriteFunction(buf *bytes.Buffer, f *Function) { 563 fmt.Fprintf(buf, "# Name: %s\n", f.String()) 564 if f.Pkg != nil { 565 fmt.Fprintf(buf, "# Package: %s\n", f.Pkg.Pkg.Path()) 566 } 567 if syn := f.Synthetic; syn != "" { 568 fmt.Fprintln(buf, "# Synthetic:", syn) 569 } 570 if pos := f.Pos(); pos.IsValid() { 571 fmt.Fprintf(buf, "# Location: %s\n", f.Prog.Fset.Position(pos)) 572 } 573 574 if f.parent != nil { 575 fmt.Fprintf(buf, "# Parent: %s\n", f.parent.Name()) 576 } 577 578 if f.Recover != nil { 579 fmt.Fprintf(buf, "# Recover: %s\n", f.Recover) 580 } 581 582 from := f.pkg() 583 584 if f.FreeVars != nil { 585 buf.WriteString("# Free variables:\n") 586 for i, fv := range f.FreeVars { 587 fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, fv.Name(), relType(fv.Type(), from)) 588 } 589 } 590 591 if len(f.Locals) > 0 { 592 buf.WriteString("# Locals:\n") 593 for i, l := range f.Locals { 594 fmt.Fprintf(buf, "# % 3d:\t%s %s\n", i, l.Name(), relType(deref(l.Type()), from)) 595 } 596 } 597 writeSignature(buf, from, f.Name(), f.Signature, f.Params) 598 buf.WriteString(":\n") 599 600 if f.Blocks == nil { 601 buf.WriteString("\t(external)\n") 602 } 603 604 // NB. column calculations are confused by non-ASCII 605 // characters and assume 8-space tabs. 606 const punchcard = 80 // for old time's sake. 607 const tabwidth = 8 608 for _, b := range f.Blocks { 609 if b == nil { 610 // Corrupt CFG. 611 fmt.Fprintf(buf, ".nil:\n") 612 continue 613 } 614 n, _ := fmt.Fprintf(buf, "%d:", b.Index) 615 bmsg := fmt.Sprintf("%s P:%d S:%d", b.Comment, len(b.Preds), len(b.Succs)) 616 fmt.Fprintf(buf, "%*s%s\n", punchcard-1-n-len(bmsg), "", bmsg) 617 618 if false { // CFG debugging 619 fmt.Fprintf(buf, "\t# CFG: %s --> %s --> %s\n", b.Preds, b, b.Succs) 620 } 621 for _, instr := range b.Instrs { 622 buf.WriteString("\t") 623 switch v := instr.(type) { 624 case Value: 625 l := punchcard - tabwidth 626 // Left-align the instruction. 627 if name := v.Name(); name != "" { 628 n, _ := fmt.Fprintf(buf, "%s = ", name) 629 l -= n 630 } 631 n, _ := buf.WriteString(instr.String()) 632 l -= n 633 // Right-align the type if there's space. 634 if t := v.Type(); t != nil { 635 buf.WriteByte(' ') 636 ts := relType(t, from) 637 l -= len(ts) + len(" ") // (spaces before and after type) 638 if l > 0 { 639 fmt.Fprintf(buf, "%*s", l, "") 640 } 641 buf.WriteString(ts) 642 } 643 case nil: 644 // Be robust against bad transforms. 645 buf.WriteString("<deleted>") 646 default: 647 buf.WriteString(instr.String()) 648 } 649 buf.WriteString("\n") 650 } 651 } 652 fmt.Fprintf(buf, "\n") 653 } 654 655 // newBasicBlock adds to f a new basic block and returns it. It does 656 // not automatically become the current block for subsequent calls to emit. 657 // comment is an optional string for more readable debugging output. 658 // 659 func (f *Function) newBasicBlock(comment string) *BasicBlock { 660 b := &BasicBlock{ 661 Index: len(f.Blocks), 662 Comment: comment, 663 parent: f, 664 } 665 b.Succs = b.succs2[:0] 666 f.Blocks = append(f.Blocks, b) 667 return b 668 } 669 670 // NewFunction returns a new synthetic Function instance belonging to 671 // prog, with its name and signature fields set as specified. 672 // 673 // The caller is responsible for initializing the remaining fields of 674 // the function object, e.g. Pkg, Params, Blocks. 675 // 676 // It is practically impossible for clients to construct well-formed 677 // SSA functions/packages/programs directly, so we assume this is the 678 // job of the Builder alone. NewFunction exists to provide clients a 679 // little flexibility. For example, analysis tools may wish to 680 // construct fake Functions for the root of the callgraph, a fake 681 // "reflect" package, etc. 682 // 683 // TODO(adonovan): think harder about the API here. 684 // 685 func (prog *Program) NewFunction(name string, sig *types.Signature, provenance string) *Function { 686 return &Function{Prog: prog, name: name, Signature: sig, Synthetic: provenance} 687 } 688 689 type extentNode [2]token.Pos 690 691 func (n extentNode) Pos() token.Pos { return n[0] } 692 func (n extentNode) End() token.Pos { return n[1] } 693 694 // Syntax returns an ast.Node whose Pos/End methods provide the 695 // lexical extent of the function if it was defined by Go source code 696 // (f.Synthetic==""), or nil otherwise. 697 // 698 // If f was built with debug information (see Package.SetDebugRef), 699 // the result is the *ast.FuncDecl or *ast.FuncLit that declared the 700 // function. Otherwise, it is an opaque Node providing only position 701 // information; this avoids pinning the AST in memory. 702 // 703 func (f *Function) Syntax() ast.Node { return f.syntax }