A DebugRef associates a source expression E with an ssa.Value
V, but until now did not record whether V was the value or the
address of E. So, we would guess from the "pointerness" of
the Value, leading to confusion in some cases, e.g.
type N *N
var n N
n = &n // lvalue and rvalue are both pointers
Now we explicitly record 'IsAddress bool' in DebugRef, and
plumb this everywhere: through (*Function).ValueForExpr and
(*Program).VarValue, all the way to forming the pointer
analysis query.
Also:
- VarValue now treats each reference to a global distinctly,
just like it does for other vars. So:
var g int
func f() {
g = 1 // VarValue(g) == Const(1:int), !isAddress
print(g) // VarValue(g) == Global(g), isAddress
}
- DebugRefs are not emitted for references to predeclared
identifiers (nil, built-in).
- DebugRefs no longer prevent lifting of an Alloc var into a
register; now we update or discard the debug info.
- TestValueForExpr: improve coverage of ssa.EnclosingFunction
by putting expectations in methods and init funcs, not just
normal funcs.
- oracle: fix golden file broken by recent
(*types.Var).IsField change.
R=gri
CC=golang-dev
https://golang.org/cl/16610045
Motivation:
Previously, we assumed that the set of types for which a
complete method set (containing all synthesized wrapper
functions) is required at runtime was the set of types
used as operands to some *ssa.MakeInterface instruction.
In fact, this is an underapproximation because types can
be derived from other ones via reflection, and some of
these may need methods. The reflect.Type API allows *T to
be derived from T, and these may have different method
sets. Reflection also allows almost any subcomponent of a
type to be accessed (with one exception: given T, defined
'type T struct{S}', you can reach S but not struct{S}).
As a result, the pointer analysis was unable to generate
all necessary constraints before running the solver,
causing a crash when reflection derives types whose
methods are unavailable. (A similar problem would afflict
an ahead-of-time compiler based on ssa. The ssa/interp
interpreter was immune only because it does not require
all wrapper methods to be created before execution
begins.)
Description:
This change causes the SSA builder to record, for each
package, the set of all types with non-empty method sets that
are referenced within that package. This set is accessed via
Packages.TypesWithMethodSets(). Program.TypesWithMethodSets()
returns its union across all packages.
The set of references that matter are:
- types of operands to some MakeInterface instruction (as before)
- types of all exported package members
- all subcomponents of the above, recursively.
This is a conservative approximation to the set of types
whose methods may be called dynamically.
We define the owning package of a type as follows:
- the owner of a named type is the package in which it is defined;
- the owner of a pointer-to-named type is the owner of that named type;
- the owner of all other types is nil.
A package must include the method sets for all types that it
owns, and all subcomponents of that type that are not owned by
another package, recursively. Types with an owner appear in
exactly one package; types with no owner (such as struct{T})
may appear within multiple packages.
(A typical Go compiler would emit multiple copies of these
methods as weak symbols; a typical linker would eliminate
duplicates.)
Also:
- go/types/typemap: implement hash function for *Tuple.
- pointer: generate nodes/constraints for all of
ssa.Program.TypesWithMethodSets().
Add rtti.go regression test.
- Add API test of Package.TypesWithMethodSets().
- Set Function.Pkg to nil (again) for wrapper functions,
since these may be shared by many packages.
- Remove a redundant logging statement.
- Document that ssa CREATE phase is in fact sequential.
Fixesgolang/go#6605
R=gri
CC=golang-dev
https://golang.org/cl/14920056
A function such as this:
func one() (x int) {
defer func() { recover() }()
x = 1
panic("return")
}
that combines named return parameters (NRPs) with deferred calls
that call recover, may return non-zero values despite the
fact it doesn't even contain a return statement. (!)
This requires a change to the SSA API: all functions'
control-flow graphs now have a second entry point, called
Recover, which is the block at which control flow resumes
after a recovered panic. The Recover block simply loads the
NRPs and returns them.
As an optimization, most functions don't need a Recover block,
so it is omitted. In fact it is only needed for functions that
have NRPs and defer a call to another function that _may_ call
recover.
Dataflow analysis of SSA now requires extra work, since every
may-panic instruction has an implicit control-flow edge to
the Recover block. The only dataflow analysis so far implemented
is SSA renaming, for which we make the following simplifying
assumption: the Recover block only loads the NRPs and returns.
This means we don't really need to analyze it, we can just
skip the "lifting" of such NRPs. We also special-case the Recover
block in the dominance computation.
Rejected alternative approaches:
- Specifying a Recover block for every defer instruction (like a
traditional exception handler).
This seemed like excessive generality, since Go programs
only need the same degenerate form of Recover block.
- Adding an instruction to set the Recover block immediately
after the named return values are set up, so that dominance
can be computed without special-casing.
This didn't seem worth the effort.
Interpreter:
- This CL completely reimplements the panic/recover/
defer logic in the interpreter. It's clearer and simpler
and closer to the model in the spec.
- Some runtime panic messages have been changed to be closer
to gc's, since tests depend on it.
- The interpreter now requires that the runtime.runtimeError
type be part of the SSA program. This requires that clients
import this package prior to invoking the interpreter.
This in turn requires (Importer).ImportPackage(path string),
which this CL adds.
- All $GOROOT/test/recover{,1,2,3}.go tests are now passing.
NB, the bug described in coverage.go (defer/recover in a concatenated
init function) remains. Will be fixed in a follow-up.
Fixesgolang/go#6381
R=gri
CC=crawshaw, golang-dev
https://golang.org/cl/13844043
Before, we would concatenate all the init() blocks together,
resulting in incorrect treatment of a recovered panic in one
init block: the implicit return would cause the subsequent ones
to be skipped.
The result is simpler, and closer to what gc does.
The additional functions are visible in the call graph,
so some tests required updating.
R=gri
CC=crawshaw, golang-dev
https://golang.org/cl/14671044
- removed support for nil constants from go/exact
- instead define a singleton Nil Object (the nil _value_)
- in assignments, follow more closely spec wording
(pending spec CL 14415043)
- removed use of goto in checker.unary
- cleanup around handling of isRepresentable for
constants, with better error messages
- fix missing checks in checker.convertUntyped
- added isTyped (== !isUntyped) and isInterface predicates
- fixed hasNil predicate: unsafe.Pointer also has nil
- adjusted ssa per adonovan
- implememted types.Implements (wrapper arounfd types.MissingMethod)
- use types.Implements in vet (and fix a bug)
R=adonovan, r
CC=golang-dev
https://golang.org/cl/14438052
Motivation: pointer analysis tools (like the oracle) want the
user to specify a set of initial packages, like 'go test'.
This change enables the user to specify a set of packages on
the command line using importer.LoadInitialPackages(args).
Each argument is interpreted as either:
- a comma-separated list of *.go source files together
comprising one non-importable ad-hoc package.
e.g. "src/pkg/net/http/triv.go" gives us [main].
- an import path, denoting both the imported package
and its non-importable external test package, if any.
e.g. "fmt" gives us [fmt, fmt_test].
Current type-checker limitations mean that only the first
import path may contribute tests: multiple packages augmented
by *_test.go files could create import cycles, which 'go test'
avoids by building a separate executable for each one.
That approach is less attractive for static analysis.
Details: (many files touched, but importer.go is the crux)
importer:
- PackageInfo.Importable boolean indicates whether
package is importable.
- un-expose Importer.Packages; expose AllPackages() instead.
- CreatePackageFromArgs has become LoadInitialPackages.
- imports() moved to util.go, renamed importsOf().
- InitialPackagesUsage usage message exported to clients.
- the package name for ad-hoc packages now comes from the
'package' decl, not "main".
ssa.Program:
- added CreatePackages() method
- PackagesByPath un-exposed, renamed 'imported'.
- expose AllPackages and ImportedPackage accessors.
oracle:
- describe: explain and workaround a go/types bug.
Misc:
- Removed various unnecessary error.Error() calls in Printf args.
R=crawshaw
CC=golang-dev
https://golang.org/cl/13579043
Previously, if the result was not wanted, the received
(value, ok) tuple had no type for 'value'.
Now it is always set to the channel's element type.
Also: set the position on such receive instructions to that of
the = or := token, and document it.
+ (indirect) test via pointer analysis.
R=crawshaw, gri
CC=golang-dev
https://golang.org/cl/12956052
Map literals should use the same recursion logic as
struct/array/slice literals to apply an implicit &-operator to
the nested literals when a pointer is wanted.
+ test.
Also:
- ensure we set the source location for all Lookup and
MapUpdate instructions.
- remove obsolete address.object field.
R=gri, crawshaw
CC=golang-dev
https://golang.org/cl/12787048
Fix bug: the Signature for an interface method wrapper
erroneously had a non-nil receiver.
Function:
- Set Pkg field non-nil even for wrappers.
It is equal to that of the wrapped function.
Only wrappers of error.Error
(and its embeddings in other interfaces) may have nil.
Sanity checker now asserts this.
- FullName() now uses .Synthetic field to discriminate
synthetic methods, not Pkg==nil.
- Fullname() uses new relType() utility to print receiver type
name unqualified if it belongs to the same package.
(Alloc.String also uses relType utility.)
CallCommon:
- Description(): fix switch logic broken when we
eliminated the Recv field.
- better docs.
R=david.crawshaw, crawshaw, gri
CC=golang-dev
https://golang.org/cl/13057043
Remove its 'name' field and treat it just like any other
ssa.Register: it gets a temp name like "t1".
Instead, give it a comment field holding its purpose, e.g, "x"
for a source-level vare, or "new", "slicelit", "complit" or
"varargs".
This improves usability of tools whose UI needs to refer to a
particular allocation site.
R=gri
CC=golang-dev
https://golang.org/cl/12273043
CanonicalPos was inadequate since many pairs of instruction share the same pos (e.g. Allocs and Phis). Instead, we generalize the DebugRef instruction to associate not just Idents but Exprs with ssa.Values.
We no longer store any DebugRefs for constant expressions, to save space. (The type and value of such expressions can be obtained by other means, at a cost in complexity.)
Function.ValueForExpr queries the DebugRef info to return the ssa.Value of a given Expr.
Added tests.
Also:
- the DebugInfo flag is now per package, not global.
It must be set between Create and Build phases if desired.
- {Value,Instruction}.Pos() documentation updated: we still maintain
this information in the instruction stream even in non-debug mode,
but we make fewer claims about its invariants.
- Go and Defer instructions can now use their respective go/defer
token positions (not the call's lparen), so they do.
- SelectState:
Posn token.Pos indicates the <- position
DebugNode ast.Expr is the send stmt or receive expr.
- In building SelectStmt, we introduce extra temporaries in debug
mode to hold the result of the receive in 'case <-ch' even though
this value isn't ordinarily needed.
- Use *SelectState (indirectly) since the struct is getting bigger.
- Document some missing instructions in doc.go.
R=gri
CC=golang-dev
https://golang.org/cl/12147043
stdlib_test runs the builder (in sanity-checking mode) over
the Go standard library. It also prints some stats about
the time and memory usage.
Also:
- importer.LoadPackage too (not just doImport) must consult
the cache to avoid creating duplicate Package instances for
the same import path when called serially from a test.
- importer: skip empty directories without an error.
- importer: print all errors, not just the first.
- visit.go: added AllFunctions utility for enumerating all
Functions in a Program.
- ssa.MethodSet is not safe to expose from the package since
it must be accessed under an (inaccessible) lock. (!!!)
This CL makes it unexported and restricts its use to the
single function Program.LookupMethod().
- Program.MethodSet() has gone.
Clients should instead iterate over the types.MethodSet
and call LookupMethod.
- Package.DumpTo(): improved efficiency of methodset printing
(by not creating wrappers) and accuracy (by showing * on
receiver type only when necessary).
- Program.CreatePackage: documented precondition and added
assertion.
R=gri
CC=golang-dev
https://golang.org/cl/12058048
buildDecl was visiting all decls in source order, but the spec
calls for visiting all vars and init() funcs in order, then
all remaining functions. These two passes are now called
buildInit(), buildFuncDecl().
+ Test.
Also:
- Added workaround to gcimporter for Func with pkg==nil.
- Prog.concreteMethods has been merged into Pkg.values.
- Prog.concreteMethod() renamed declaredFunc().
- s/mfunc/obj/ (name cleanup from recent gri CL)
R=gri
CC=golang-dev
https://golang.org/cl/12030044
A Method corresponds to a MethodVal Selection;
so the explicit Method object is not needed anymore.
- moved Selection code into separate file
- implemented Selection.String()
- improved and more consistent documentation
R=adonovan
CC=golang-dev
https://golang.org/cl/11950043
methprom.go covers method promotion.
Found bug: receiver() requires a following load under some
circumstances.
ifaceconv.go covers interface conversion.
Found bug: confusion about infallible and fallible conversions
led to use of TypeAssert in emitConv, which should never fail.
Changed semantics of ChangeInterface to make it infallible
and made some simplifications.
Also in this CL:
- SelectState.Pos now records the position of the
the '<-' operator for sends/receives done by a Select.
R=gri
CC=golang-dev
https://golang.org/cl/11931044
We now use LookupFieldOrMethod for all SelectorExprs, and
simplify the logic to discriminate the various cases.
We inline static calls to promoted/indirected functions,
dramatically reducing the number of functions created.
More tests are needed, but I'd like to submit this as-is.
In this CL, we:
- rely less on Id strings. Internally we now use
*types.Method (and its components) almost everywhere.
- stop thinking of types.Methods as objects. They don't
have stable identities. (Hopefully they will become
plain-old structs soon.)
- eliminate receiver indirection wrappers:
indirection and promotion are handled together by makeWrapper.
- Handle the interactions of promotion, indirection and
abstract methods much more cleanly.
- support receiver-bound interface method closures.
- break up builder.selectField so we can re-use parts
(emitFieldSelection).
- add importer.PackageInfo.classifySelector utility.
- delete interfaceMethodIndex()
- delete namedTypeMethodIndex()
- delete isSuperInterface() (replaced by types.IsAssignable)
- call memberFromObject on each declared concrete method's
*types.Func, not on every Method frem each method set, in the
CREATE phase for packages loaded by gcimporter.
go/types:
- document Func, Signature.Recv() better.
- use fmt in {Package,Label}.String
- reimplement Func.String to be prettier and to include method
receivers.
API changes:
- Function.method now holds the types.Method (soon to be
not-an-object) for synthetic wrappers.
- CallCommon.Method now contains an abstract (interface)
method object; was an abstract method index.
- CallCommon.MethodId() gone.
- Program.LookupMethod now takes a *Method not an Id string.
R=gri
CC=golang-dev
https://golang.org/cl/11674043
(Motivation: "Literal" is a syntactic property, not a semantic one.)
Also: delete a "TODO: opt" that the lifting pass already does for us.
R=gri
CC=golang-dev
https://golang.org/cl/11351043
- removed a number of obsolete TODO(gri) comments.
- bring ssa.DefaultType back into sync with types.defaultType.
- re-enable types.Package.Path()!="" assertion.
- use Path() (not reflect pointer) in sort routine.
- make interp.checkInterface use types.MissingMethod.
- un-export ssa.MakeId function.
- inline pointer() into all callers, and delete.
- enable two more interp_tests: $GOROOT/test/{method3,cmp}.go
- add links to bugs to other interp_tests.
- add runtime.NumCPU to ssa/interp/externals.go
R=gri
CC=golang-dev
https://golang.org/cl/11353043
This CL adds three new functions to determine the SSA Value
for a given syntactic var, func or const object:
Program.{Const,Func,Var}Value.
Since constants and functions are immutable, the first
two only need a types.Object; but each distinct
reference to a var may return a distinct Value, so the third
requires an ast.Ident parameter too.
Debug information for local vars is encoded in the
instruction stream in the form of DebugRef instructions,
which are a no-op but relate their operand to a particular
ident in the AST. The beauty of this approach is that it
naturally stays consistent during optimisation passes
(e.g. lifting) without additional bookkeeping.
DebugRef instructions are only generated if the DebugMode
builder flag is set; I plan to make the policy more fine-
grained (per function).
DebugRef instructions are inserted for:
- expr(Ident) for rvalue idents
- address.store() for idents that update an lvalue
- address.address() for idents that take address of lvalue
(this new method replaces all uses of lval.(address).addr)
- expr() for all constant expressions
- local ValueSpecs with implicit zero initialization (no RHS)
(this case doesn't call store() or address())
To ensure we don't forget to emit debug info for uses of Idents,
we must use the lvalue mechanism consistently. (Previously,
many simple cases had effectively inlined these functions.)
Similarly setCallFunc no longer inlines expr(Ident).
Also:
- Program.Value() has been inlined & specialized.
- Program.Package() has moved nearer the new lookup functions.
- refactoring: funcSyntax has lost paramFields, resultFields;
gained funcType, which provides access to both.
- add package-level constants to Package.values map.
- opt: don't call localValueSpec for constants.
(The resulting code is always optimised away.)
There are a number of comments asking whether Literals
should have positions. Will address in a follow-up.
Added tests of all interesting cases.
R=gri
CC=golang-dev
https://golang.org/cl/11259044
This exposed a bug: we weren't creating Functions for methods
of imported named types.
Also:
- simplification: 'candidate' no longer contains 'concrete *Function'.
We look this up on demand.
NB: this CL contains a copy of CL 10935047 (use of typemap);
will submit/sync/resolve soon.
R=gri
CC=golang-dev
https://golang.org/cl/11051043
Yields a ~20% improvement in SSA construction time.
Also: better names for promotion wrapper functions.
R=gri
CC=golang-dev
https://golang.org/cl/11050043
We use the new field to determine whether or not a function is
synthetic, not Pos() == 0, so synthetic functions can have
positions too.
R=gri
CC=golang-dev
https://golang.org/cl/10916044
Before, all values received on some channel by Select would
flow to an empty interface, creating a spurious confluence for
flow analyses. Now, the tuple returned by Select has one
component for each 'receive' case.
Also, fixes:
- Removed workarounds for now-fixed typechecker bug in FuncLit+TypeAssert.
- sanity check that all Value Instructions have non-nil Type().
- Convert: document and sanity-check that at least one of the types is basic.
Also, other things to help clients:
- Define CallInstruction interface: common parts of Call, Go, Defer.
- Add CallCommon.Signature() method.
- Literal.Pos() is now populated.
R=gri
CC=golang-dev
https://golang.org/cl/10505043
methodIndex() utility was split and specialized to its two
cases, *Interface vs *Named, which are logically quite
different.
We can't memoize promotion wrappers yet; we need typemap.
Terminology:
- "thunks" are now "wrappers"
- "bridge methods" are now "promotion wrappers"
Where the diff is messy it's just because of indentation.
R=gri
CC=golang-dev
https://golang.org/cl/10282043
Method sets:
- Simplify CallCommon.
Avoid the implicit copy when calling a T method on a *T
receiver. This simplifies clients. Instead we generate
"indirection wrapper" functions that do this (like gc does).
New invariant:
m's receiver type is exactly T for all m in MethodSet(T)
- MakeInterface no longer holds the concrete type's MethodSet.
We can defer its computation this way.
- ssa.Type now just wraps a types.TypeName object.
MethodSets are computed as needed, not eagerly.
Position info:
- new CanonicalPos utility maps ast.Expr to canonical
token.Pos, as returned by {Instruction,Value}.Pos() methods.
- Don't set posn for implicit operations (e.g. varargs array alloc)
- Set position info for ChangeInterface and Slice instructions.
Cosmetic:
- add Member.Token() method
- simplify isPointer
- Omit words "interface", "slice" when printing MakeInterface,
MakeSlice; the type is enough.
- Comments on PathEnclosingInterval.
- Remove Function.FullName() where implicit String() suffices.
Also:
- Exposed NewLiteral to clients.
- Added ssa.Instruction.Parent() *Function
Added ssa.BasicBlock.Parent() *Function.
Added Sanity checks for above.
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/10166045
Details:
- builder is now un-exported and is now a per-package entity.
- Package.nTo1Vars is now part of builder, where it belongs.
- CREATE phase code split out into its own file, create.go
- Context type is gone; it had become trivial after the
Importer refactoring.
- importer.PackageInfo.Imports() now encapsulates iteration
over imports.
Typical usage is now:
prog := ssa.NewProgram(imp.Fset, mode)
prog.CreatePackages(imp)
prog.BuildAll()
Builder.BuildPackage(Package) is now Package.Build()
Builder.BuildAllPackages() is now Program.BuildAll()
R=iant, gri
CC=golang-dev
https://golang.org/cl/9970044
A Builder is now just a Program and a Context.
Details of this CL:
- Builder.imp field removed.
- Builder.globals split up into Package.values and Prog.Builtins.
- Builder.packages moved to Prog.packages.
- Builder.PackageFor moved to Program.Package(types.Object)
- Program.Lookup() func replaces Builder.globals map.
- also: keep Package.info field around until end of BuildPackage.
Planned follow-ups to eliminate Builder from API:
- split NewBuilder up into NewProgram and Program.CreatePackages(...)
- move Builder.BuildAllPackages -> Program.BuildAll(Context)
- move Builder.BuildPackage -> Package.Build(Context)
R=gri, iant
CC=golang-dev
https://golang.org/cl/9966044
PLEASE NOTE: the APIs for both "importer" and "ssa" packages
will continue to evolve and both need some polishing; the key
thing is that this CL splits them.
The go.types/importer package contains contains the Importer,
which takes care of the mechanics of loading a set of packages
and type-checking them. It exposes for each package a
PackageInfo containing:
- the package's ASTs (i.e. the input to the typechecker)
- the types.Package object
- the memoization of the typechecker callbacks for identifier
resolution, constant folding and expression type inference.
Method-set computation (and hence bridge-method creation) is
now moved to after creation of all packages: since they are no
longer created in topological order, we can't guarantee the
needed delegate methods exist yet.
ssa.Package no longer has public TypeOf, ObjectOf, ValueOf methods.
The private counterparts are valid only during the build phase.
Also:
- added to go/types an informative error (not crash) for an
importer() returning nil without error.
- removed Package.Name(), barely needed.
- changed Package.String() slightly.
- flag what looks like a bug in makeBridgeMethod. Will follow up.
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/9898043
Implement Pos() method for
Values: Parameter, Capture, Phi. (Not Literal, Builtin.)
Instructions: UnOp, BinOp, Store.
'address' (an lvalue) now needs position of '*' in "*addr".
Also:
- Un-export fields Pos_ Type_ Name_ Block_ from various values/instructions.
Define NewFunction() as a temporary measure.
Will try to eliminate calls from clients...
- Remove Implements{Value,Member,Interface} marker methods.
I've decided I don't like them.
- Func.addParamObj helper.
- Various comment fixes.
R=gri
CC=golang-dev
https://golang.org/cl/9740046
PathEnclosingInterval: maps a source position to an ast.Node.
EnclosingFunction: finds ssa.Function enclosing an ast.Node.
HasEnclosingFunction: cheaper impl of EnclosingFunction()!=nil
NodeDescription: user friendly node type descriptions.
+ tests.
Also: make ssa.Package.TypeInfo field a pointer.
R=gri, r
CC=golang-dev
https://golang.org/cl/9639045
Extracted Builder.findMethod function to handle
methodset/receiver logic common to
function calls (Builder.setCall) and
bound method closure creation (Builder.selector).
Capture: added explicit Name, Type fields to Capture instead
of relying on Outer field, which is now un-exported since its
only purpose is to let Builder.expr(case *ast.FuncLit) know
which values to put in the closure; it is nilled immediately
after.
Simplified Function.lookup() logic: there's no need to walk
the Outer chain each time to set Alloc.Heap=true, as it's
already set during creation of the outermost
Capture{outer:*Alloc}.
Added interp/testdata/boundmeth.go test.
Cosmetic changes:
- add support for bound method thunks to Function.FullName().
- Simplified {Literal,Global,Builtin,Function}.String()
- doc: Captures are no longer necessarily addresses.
- added yet another missing pair of "()" (go/types accessors).
- print "Synthetic" not "Declared at -" for synthetic functions.
- use '$' not center-dot in synthetic identifiers (easier to type).
R=gri
CC=golang-dev
https://golang.org/cl/9654043