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