Newer
Older
Matthew Dempsky
committed
for len(rtypes) < i {
rtypes = append(rtypes, nil)
}
rtypes = append(rtypes, reflectdata.TypePtrAt(cas.Pos(), types.Types[types.TBOOL]))
}
}
}
}
clause := ir.NewCaseStmt(pos, cases, nil)
clause.RTypes = rtypes
if ident != nil {
pos := r.pos()
typ := r.typ()
name := ir.NewNameAt(pos, ident.Sym())
setType(name, typ)
r.addLocal(name, ir.PAUTO)
clause.Var = name
name.Defn = tag
}
clause.Body = r.stmts()
clauses[i] = clause
}
if len(clauses) > 0 {
r.closeScope()
}
r.closeScope()
n := ir.NewSwitchStmt(pos, tag, clauses)
n.Label = label
if init != nil {
n.SetInit([]ir.Node{init})
}
return n
}
func (r *reader) label() *types.Sym {
r.Sync(pkgbits.SyncLabel)
name := r.String()
if r.inlCall != nil {
name = fmt.Sprintf("~%s·%d", name, inlgen)
}
return typecheck.Lookup(name)
}
func (r *reader) optLabel() *types.Sym {
r.Sync(pkgbits.SyncOptLabel)
if r.Bool() {
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
return r.label()
}
return nil
}
// initDefn marks the given names as declared by defn and populates
// its Init field with ODCL nodes. It then reports whether any names
// were so declared, which can be used to initialize defn.Def.
func (r *reader) initDefn(defn ir.InitNode, names []*ir.Name) bool {
if len(names) == 0 {
return false
}
init := make([]ir.Node, len(names))
for i, name := range names {
name.Defn = defn
init[i] = ir.NewDecl(name.Pos(), ir.ODCL, name)
}
defn.SetInit(init)
return true
}
// @@@ Expressions
// expr reads and returns a typechecked expression.
func (r *reader) expr() (res ir.Node) {
defer func() {
if res != nil && res.Typecheck() == 0 {
base.FatalfAt(res.Pos(), "%v missed typecheck", res)
}
}()
switch tag := codeExpr(r.Code(pkgbits.SyncExpr)); tag {
default:
panic("unhandled expression")
case exprLocal:
return typecheck.Expr(r.useLocal())
case exprGlobal:
// Callee instead of Expr allows builtins
// TODO(mdempsky): Handle builtins directly in exprCall, like method calls?
return typecheck.Callee(r.obj())
case exprFuncInst:
pos := r.pos()
wrapperFn, baseFn, dictPtr := r.funcInst(pos)
if wrapperFn != nil {
return wrapperFn
}
return r.curry(pos, false, baseFn, dictPtr, nil)
case exprConst:
pos := r.pos()
val := FixValue(typ, r.Value())
orig := r.String()
return typecheck.Expr(OrigConst(pos, typ, val, op, orig))
case exprNil:
pos := r.pos()
typ := r.typ()
return Nil(pos, typ)
case exprCompLit:
return r.compLit()
case exprFuncLit:
return r.funcLit()
case exprFieldVal:
x := r.expr()
pos := r.pos()
_, sym := r.selector()
return typecheck.Expr(ir.NewSelectorExpr(pos, ir.OXDOT, x, sym)).(*ir.SelectorExpr)
case exprMethodVal:
recv := r.expr()
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
wrapperFn, baseFn, dictPtr := r.methodExpr()
// For simple wrapperFn values, the existing machinery for creating
// and deduplicating wrapperFn value wrappers still works fine.
if wrapperFn, ok := wrapperFn.(*ir.SelectorExpr); ok && wrapperFn.Op() == ir.OMETHEXPR {
// The receiver expression we constructed may have a shape type.
// For example, in fixedbugs/issue54343.go, `New[int]()` is
// constructed as `New[go.shape.int](&.dict.New[int])`, which
// has type `*T[go.shape.int]`, not `*T[int]`.
//
// However, the method we want to select here is `(*T[int]).M`,
// not `(*T[go.shape.int]).M`, so we need to manually convert
// the type back so that the OXDOT resolves correctly.
//
// TODO(mdempsky): Logically it might make more sense for
// exprCall to take responsibility for setting a non-shaped
// result type, but this is the only place where we care
// currently. And only because existing ir.OMETHVALUE backend
// code relies on n.X.Type() instead of n.Selection.Recv().Type
// (because the latter is types.FakeRecvType() in the case of
// interface method values).
//
if recv.Type().HasShape() {
typ := wrapperFn.Type().Params().Field(0).Type
if !types.Identical(typ, recv.Type()) {
base.FatalfAt(wrapperFn.Pos(), "receiver %L does not match %L", recv, wrapperFn)
}
recv = typecheck.Expr(ir.NewConvExpr(recv.Pos(), ir.OCONVNOP, typ, recv))
}
n := typecheck.Expr(ir.NewSelectorExpr(pos, ir.OXDOT, recv, wrapperFn.Sel)).(*ir.SelectorExpr)
assert(n.Selection == wrapperFn.Selection)
wrapper := methodValueWrapper{
rcvr: n.X.Type(),
method: n.Selection,
}
if r.importedDef() {
haveMethodValueWrappers = append(haveMethodValueWrappers, wrapper)
} else {
needMethodValueWrappers = append(needMethodValueWrappers, wrapper)
}
return n
// For more complicated method expressions, we construct a
// function literal wrapper.
return r.curry(pos, true, baseFn, recv, dictPtr)
case exprMethodExpr:
recv := r.typ()
implicits := make([]int, r.Len())
for i := range implicits {
implicits[i] = r.Len()
}
var deref, addr bool
if r.Bool() {
deref = true
} else if r.Bool() {
addr = true
}
pos := r.pos()
wrapperFn, baseFn, dictPtr := r.methodExpr()
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
// If we already have a wrapper and don't need to do anything with
// it, we can just return the wrapper directly.
//
// N.B., we use implicits/deref/addr here as the source of truth
// rather than types.Identical, because the latter can be confused
// by tricky promoted methods (e.g., typeparam/mdempsky/21.go).
if wrapperFn != nil && len(implicits) == 0 && !deref && !addr {
if !types.Identical(recv, wrapperFn.Type().Params().Field(0).Type) {
base.FatalfAt(pos, "want receiver type %v, but have method %L", recv, wrapperFn)
}
return wrapperFn
}
// Otherwise, if the wrapper function is a static method
// expression (OMETHEXPR) and the receiver type is unshaped, then
// we can rely on a statically generated wrapper being available.
if method, ok := wrapperFn.(*ir.SelectorExpr); ok && method.Op() == ir.OMETHEXPR && !recv.HasShape() {
return typecheck.Expr(ir.NewSelectorExpr(pos, ir.OXDOT, ir.TypeNode(recv), method.Sel)).(*ir.SelectorExpr)
}
return r.methodExprWrap(pos, recv, implicits, deref, addr, baseFn, dictPtr)
case exprIndex:
x := r.expr()
pos := r.pos()
index := r.expr()
n := typecheck.Expr(ir.NewIndexExpr(pos, x, index))
switch n.Op() {
case ir.OINDEXMAP:
n := n.(*ir.IndexExpr)
n.RType = r.rtype(pos)
}
return n
case exprSlice:
x := r.expr()
pos := r.pos()
var index [3]ir.Node
for i := range index {
Matthew Dempsky
committed
index[i] = r.optExpr()
}
op := ir.OSLICE
if index[2] != nil {
op = ir.OSLICE3
}
return typecheck.Expr(ir.NewSliceExpr(pos, op, x, index[0], index[1], index[2]))
case exprAssert:
x := r.expr()
pos := r.pos()
typ := r.exprType()
srcRType := r.rtype(pos)
// TODO(mdempsky): Always emit ODYNAMICDOTTYPE for uniformity?
if typ, ok := typ.(*ir.DynamicType); ok && typ.Op() == ir.ODYNAMICTYPE {
assert := ir.NewDynamicTypeAssertExpr(pos, ir.ODYNAMICDOTTYPE, x, typ.RType)
assert.SrcRType = srcRType
assert.ITab = typ.ITab
return typed(typ.Type(), assert)
}
return typecheck.Expr(ir.NewTypeAssertExpr(pos, x, typ.Type()))
case exprUnaryOp:
op := r.op()
pos := r.pos()
x := r.expr()
switch op {
case ir.OADDR:
return typecheck.Expr(typecheck.NodAddrAt(pos, x))
case ir.ODEREF:
return typecheck.Expr(ir.NewStarExpr(pos, x))
return typecheck.Expr(ir.NewUnaryExpr(pos, op, x))
case exprBinaryOp:
op := r.op()
x := r.expr()
pos := r.pos()
y := r.expr()
switch op {
case ir.OANDAND, ir.OOROR:
return typecheck.Expr(ir.NewLogicalExpr(pos, op, x, y))
return typecheck.Expr(ir.NewBinaryExpr(pos, op, x, y))
case exprRecv:
x := r.expr()
pos := r.pos()
for i, n := 0, r.Len(); i < n; i++ {
x = Implicit(DotField(pos, x, r.Len()))
}
if r.Bool() { // needs deref
x = Implicit(Deref(pos, x.Type().Elem(), x))
} else if r.Bool() { // needs addr
x = Implicit(Addr(pos, x))
}
return x
var fun ir.Node
var args ir.Nodes
if r.Bool() { // method call
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
recv := r.expr()
_, method, dictPtr := r.methodExpr()
if recv.Type().IsInterface() && method.Op() == ir.OMETHEXPR {
method := method.(*ir.SelectorExpr)
// The compiler backend (e.g., devirtualization) handle
// OCALLINTER/ODOTINTER better than OCALLFUNC/OMETHEXPR for
// interface calls, so we prefer to continue constructing
// calls that way where possible.
//
// There are also corner cases where semantically it's perhaps
// significant; e.g., fixedbugs/issue15975.go, #38634, #52025.
fun = typecheck.Callee(ir.NewSelectorExpr(method.Pos(), ir.OXDOT, recv, method.Sel))
} else {
if recv.Type().IsInterface() {
// N.B., this happens currently for typeparam/issue51521.go
// and typeparam/typeswitch3.go.
if base.Flag.LowerM > 0 {
base.WarnfAt(method.Pos(), "imprecise interface call")
}
}
fun = method
args.Append(recv)
}
if dictPtr != nil {
args.Append(dictPtr)
}
} else if r.Bool() { // call to instanced function
pos := r.pos()
_, shapedFn, dictPtr := r.funcInst(pos)
fun = shapedFn
args.Append(dictPtr)
} else {
fun = r.expr()
}
args.Append(r.multiExpr()...)
Matthew Dempsky
committed
dots := r.Bool()
n := typecheck.Call(pos, fun, args, dots)
switch n.Op() {
case ir.OAPPEND:
n := n.(*ir.CallExpr)
n.RType = r.rtype(pos)
// For append(a, b...), we don't need the implicit conversion. The typechecker already
// ensured that a and b are both slices with the same base type, or []byte and string.
if n.IsDDD {
if conv, ok := n.Args[1].(*ir.ConvExpr); ok && conv.Op() == ir.OCONVNOP && conv.Implicit() {
n.Args[1] = conv.X
}
}
case ir.OCOPY:
n := n.(*ir.BinaryExpr)
n.RType = r.rtype(pos)
case ir.ODELETE:
n := n.(*ir.CallExpr)
n.RType = r.rtype(pos)
case ir.OUNSAFESLICE:
n := n.(*ir.BinaryExpr)
n.RType = r.rtype(pos)
}
return n
Matthew Dempsky
committed
case exprMake:
pos := r.pos()
typ := r.exprType()
Matthew Dempsky
committed
extra := r.exprs()
n := typecheck.Expr(ir.NewCallExpr(pos, ir.OMAKE, nil, append([]ir.Node{typ}, extra...))).(*ir.MakeExpr)
n.RType = r.rtype(pos)
return n
Matthew Dempsky
committed
case exprNew:
pos := r.pos()
typ := r.exprType()
Matthew Dempsky
committed
return typecheck.Expr(ir.NewUnaryExpr(pos, ir.ONEW, typ))
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
case exprReshape:
typ := r.typ()
x := r.expr()
if types.IdenticalStrict(x.Type(), typ) {
return x
}
// Comparison expressions are constructed as "untyped bool" still.
//
// TODO(mdempsky): It should be safe to reshape them here too, but
// maybe it's better to construct them with the proper type
// instead.
if x.Type() == types.UntypedBool && typ.IsBoolean() {
return x
}
base.AssertfAt(x.Type().HasShape() || typ.HasShape(), x.Pos(), "%L and %v are not shape types", x, typ)
base.AssertfAt(types.Identical(x.Type(), typ), x.Pos(), "%L is not shape-identical to %v", x, typ)
// We use ir.HasUniquePos here as a check that x only appears once
// in the AST, so it's okay for us to call SetType without
// breaking any other uses of it.
//
// Notably, any ONAMEs should already have the exactly right shape
// type and been caught by types.IdenticalStrict above.
base.AssertfAt(ir.HasUniquePos(x), x.Pos(), "cannot call SetType(%v) on %L", typ, x)
if base.Debug.Reshape != 0 {
base.WarnfAt(x.Pos(), "reshaping %L to %v", x, typ)
}
x.SetType(typ)
return x
case exprConvert:
Matthew Dempsky
committed
implicit := r.Bool()
typ := r.typ()
typeWord, srcRType := r.convRTTI(pos)
Cuong Manh Le
committed
dstTypeParam := r.Bool()
// TODO(mdempsky): Stop constructing expressions of untyped type.
x = typecheck.DefaultLit(x, typ)
if op, why := typecheck.Convertop(x.Op() == ir.OLITERAL, x.Type(), typ); op == ir.OXXX {
// types2 ensured that x is convertable to typ under standard Go
// semantics, but cmd/compile also disallows some conversions
// involving //go:notinheap.
//
// TODO(mdempsky): This can be removed after #46731 is implemented.
base.ErrorfAt(pos, "cannot convert %L to type %v%v", x, typ, why)
base.ErrorExit() // harsh, but prevents constructing invalid IR
}
Cuong Manh Le
committed
ce := ir.NewConvExpr(pos, ir.OCONV, typ, x)
ce.TypeWord, ce.SrcRType = typeWord, srcRType
Matthew Dempsky
committed
if implicit {
Cuong Manh Le
committed
ce.SetImplicit(true)
Matthew Dempsky
committed
}
Cuong Manh Le
committed
n := typecheck.Expr(ce)
// Conversions between non-identical, non-empty interfaces always
// requires a runtime call, even if they have identical underlying
// interfaces. This is because we create separate itab instances
// for each unique interface type, not merely each unique
// interface shape.
//
// However, due to shape types, typecheck.Expr might mistakenly
// think a conversion between two non-empty interfaces are
// identical and set ir.OCONVNOP, instead of ir.OCONVIFACE. To
// ensure we update the itab field appropriately, we force it to
// ir.OCONVIFACE instead when shape types are involved.
//
// TODO(mdempsky): Are there other places we might get this wrong?
// Should this be moved down into typecheck.{Assign,Convert}op?
// This would be a non-issue if itabs were unique for each
// *underlying* interface type instead.
if n, ok := n.(*ir.ConvExpr); ok && n.Op() == ir.OCONVNOP && n.Type().IsInterface() && !n.Type().IsEmptyInterface() && (n.Type().HasShape() || n.X.Type().HasShape()) {
n.SetOp(ir.OCONVIFACE)
}
Cuong Manh Le
committed
// spec: "If the type is a type parameter, the constant is converted
// into a non-constant value of the type parameter."
if dstTypeParam && ir.IsConstNode(n) {
// Wrap in an OCONVNOP node to ensure result is non-constant.
n = Implicit(ir.NewConvExpr(pos, ir.OCONVNOP, n.Type(), n))
n.SetTypecheck(1)
}
return n
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
// funcInst reads an instantiated function reference, and returns
// three (possibly nil) expressions related to it:
//
// baseFn is always non-nil: it's either a function of the appropriate
// type already, or it has an extra dictionary parameter as the first
// parameter.
//
// If dictPtr is non-nil, then it's a dictionary argument that must be
// passed as the first argument to baseFn.
//
// If wrapperFn is non-nil, then it's either the same as baseFn (if
// dictPtr is nil), or it's semantically equivalent to currying baseFn
// to pass dictPtr. (wrapperFn is nil when dictPtr is an expression
// that needs to be computed dynamically.)
//
// For callers that are creating a call to the returned function, it's
// best to emit a call to baseFn, and include dictPtr in the arguments
// list as appropriate.
//
// For callers that want to return the function without invoking it,
// they may return wrapperFn if it's non-nil; but otherwise, they need
// to create their own wrapper.
func (r *reader) funcInst(pos src.XPos) (wrapperFn, baseFn, dictPtr ir.Node) {
// Like in methodExpr, I'm pretty sure this isn't needed.
var implicits []*types.Type
if r.dict != nil {
implicits = r.dict.targs
}
if r.Bool() { // dynamic subdictionary
idx := r.Len()
info := r.dict.subdicts[idx]
explicits := r.p.typListIdx(info.explicits, r.dict)
baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
// TODO(mdempsky): Is there a more robust way to get the
// dictionary pointer type here?
dictPtrType := baseFn.Type().Params().Field(0).Type
dictPtr = typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx)))
return
}
info := r.objInfo()
explicits := r.p.typListIdx(info.explicits, r.dict)
wrapperFn = r.p.objIdx(info.idx, implicits, explicits, false).(*ir.Name)
baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
dictName := r.p.objDictName(info.idx, implicits, explicits)
dictPtr = typecheck.Expr(ir.NewAddrExpr(pos, dictName))
return
}
func (pr *pkgReader) objDictName(idx pkgbits.Index, implicits, explicits []*types.Type) *ir.Name {
rname := pr.newReader(pkgbits.RelocName, idx, pkgbits.SyncObject1)
_, sym := rname.qualifiedIdent()
tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
if tag == pkgbits.ObjStub {
assert(!sym.IsBlank())
if pri, ok := objReader[sym]; ok {
return pri.pr.objDictName(pri.idx, nil, explicits)
}
base.Fatalf("unresolved stub: %v", sym)
}
dict := pr.objDictIdx(sym, idx, implicits, explicits, false)
return pr.dictNameOf(dict)
}
// curry returns a function literal that calls fun with arg0 and
// (optionally) arg1, accepting additional arguments to the function
// literal as necessary to satisfy fun's signature.
//
// If nilCheck is true and arg0 is an interface value, then it's
// checked to be non-nil as an initial step at the point of evaluating
// the function literal itself.
func (r *reader) curry(pos src.XPos, ifaceHack bool, fun ir.Node, arg0, arg1 ir.Node) ir.Node {
var captured ir.Nodes
captured.Append(fun, arg0)
if arg1 != nil {
captured.Append(arg1)
}
params, results := syntheticSig(fun.Type())
params = params[len(captured)-1:] // skip curried parameters
typ := types.NewSignature(types.NoPkg, nil, nil, params, results)
addBody := func(pos src.XPos, r *reader, captured []ir.Node) {
recvs, params := r.syntheticArgs(pos)
assert(len(recvs) == 0)
fun := captured[0]
var args ir.Nodes
args.Append(captured[1:]...)
args.Append(params...)
r.syntheticTailCall(pos, fun, args)
}
return r.syntheticClosure(pos, typ, ifaceHack, captured, addBody)
}
// methodExprWrap returns a function literal that changes method's
// first parameter's type to recv, and uses implicits/deref/addr to
// select the appropriate receiver parameter to pass to method.
func (r *reader) methodExprWrap(pos src.XPos, recv *types.Type, implicits []int, deref, addr bool, method, dictPtr ir.Node) ir.Node {
var captured ir.Nodes
captured.Append(method)
params, results := syntheticSig(method.Type())
// Change first parameter to recv.
params[0].Type = recv
// If we have a dictionary pointer argument to pass, then omit the
// underlying method expression's dictionary parameter from the
// returned signature too.
if dictPtr != nil {
captured.Append(dictPtr)
params = append(params[:1], params[2:]...)
}
typ := types.NewSignature(types.NoPkg, nil, nil, params, results)
addBody := func(pos src.XPos, r *reader, captured []ir.Node) {
recvs, args := r.syntheticArgs(pos)
assert(len(recvs) == 0)
fn := captured[0]
// Rewrite first argument based on implicits/deref/addr.
{
arg := args[0]
for _, ix := range implicits {
arg = Implicit(DotField(pos, arg, ix))
}
if deref {
arg = Implicit(Deref(pos, arg.Type().Elem(), arg))
} else if addr {
arg = Implicit(Addr(pos, arg))
}
args[0] = arg
}
// Insert dictionary argument, if provided.
if dictPtr != nil {
newArgs := make([]ir.Node, len(args)+1)
newArgs[0] = args[0]
newArgs[1] = captured[1]
copy(newArgs[2:], args[1:])
args = newArgs
}
r.syntheticTailCall(pos, fn, args)
}
return r.syntheticClosure(pos, typ, false, captured, addBody)
}
// syntheticClosure constructs a synthetic function literal for
// currying dictionary arguments. pos is the position used for the
// closure. typ is the function literal's signature type.
//
// captures is a list of expressions that need to be evaluated at the
// point of function literal evaluation and captured by the function
// literal. If ifaceHack is true and captures[1] is an interface type,
// it's checked to be non-nil after evaluation.
//
// addBody is a callback function to populate the function body. The
// list of captured values passed back has the captured variables for
// use within the function literal, corresponding to the expressions
// in captures.
func (r *reader) syntheticClosure(pos src.XPos, typ *types.Type, ifaceHack bool, captures ir.Nodes, addBody func(pos src.XPos, r *reader, captured []ir.Node)) ir.Node {
// isSafe reports whether n is an expression that we can safely
// defer to evaluating inside the closure instead, to avoid storing
// them into the closure.
//
// In practice this is always (and only) the wrappee function.
isSafe := func(n ir.Node) bool {
if n.Op() == ir.ONAME && n.(*ir.Name).Class == ir.PFUNC {
return true
}
if n.Op() == ir.OMETHEXPR {
return true
}
return false
}
fn := ir.NewClosureFunc(pos, r.curfn != nil)
fn.SetWrapper(true)
clo := fn.OClosure
ir.NameClosure(clo, r.curfn)
setType(fn.Nname, typ)
typecheck.Func(fn)
setType(clo, fn.Type())
var init ir.Nodes
for i, n := range captures {
if isSafe(n) {
continue // skip capture; can reference directly
}
tmp := r.tempCopy(pos, n, &init)
ir.NewClosureVar(pos, fn, tmp)
// We need to nil check interface receivers at the point of method
// value evaluation, ugh.
if ifaceHack && i == 1 && n.Type().IsInterface() {
check := ir.NewUnaryExpr(pos, ir.OCHECKNIL, ir.NewUnaryExpr(pos, ir.OITAB, tmp))
init.Append(typecheck.Stmt(check))
}
}
pri := pkgReaderIndex{synthetic: func(pos src.XPos, r *reader) {
captured := make([]ir.Node, len(captures))
next := 0
for i, n := range captures {
if isSafe(n) {
captured[i] = n
} else {
captured[i] = r.closureVars[next]
next++
}
}
assert(next == len(r.closureVars))
addBody(pos, r, captured)
}}
bodyReader[fn] = pri
pri.funcBody(fn)
// TODO(mdempsky): Remove hard-coding of typecheck.Target.
return ir.InitExpr(init, ir.UseClosure(clo, typecheck.Target))
}
// syntheticSig duplicates and returns the params and results lists
// for sig, but renaming anonymous parameters so they can be assigned
// ir.Names.
func syntheticSig(sig *types.Type) (params, results []*types.Field) {
clone := func(params []*types.Field) []*types.Field {
res := make([]*types.Field, len(params))
for i, param := range params {
sym := param.Sym
if sym == nil || sym.Name == "_" {
sym = typecheck.LookupNum(".anon", i)
}
// TODO(mdempsky): It would be nice to preserve the original
// parameter positions here instead, but at least
// typecheck.NewMethodType replaces them with base.Pos, making
// them useless. Worse, the positions copied from base.Pos may
// have inlining contexts, which we definitely don't want here
// (e.g., #54625).
res[i] = types.NewField(base.AutogeneratedPos, sym, param.Type)
res[i].SetIsDDD(param.IsDDD())
}
return res
}
return clone(sig.Params().FieldSlice()), clone(sig.Results().FieldSlice())
}
Matthew Dempsky
committed
func (r *reader) optExpr() ir.Node {
if r.Bool() {
return r.expr()
}
return nil
}
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
// methodExpr reads a method expression reference, and returns three
// (possibly nil) expressions related to it:
//
// baseFn is always non-nil: it's either a function of the appropriate
// type already, or it has an extra dictionary parameter as the second
// parameter (i.e., immediately after the promoted receiver
// parameter).
//
// If dictPtr is non-nil, then it's a dictionary argument that must be
// passed as the second argument to baseFn.
//
// If wrapperFn is non-nil, then it's either the same as baseFn (if
// dictPtr is nil), or it's semantically equivalent to currying baseFn
// to pass dictPtr. (wrapperFn is nil when dictPtr is an expression
// that needs to be computed dynamically.)
//
// For callers that are creating a call to the returned method, it's
// best to emit a call to baseFn, and include dictPtr in the arguments
// list as appropriate.
//
// For callers that want to return a method expression without
// invoking it, they may return wrapperFn if it's non-nil; but
// otherwise, they need to create their own wrapper.
func (r *reader) methodExpr() (wrapperFn, baseFn, dictPtr ir.Node) {
recv := r.typ()
sig0 := r.typ()
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
pos := r.pos()
_, sym := r.selector()
// Signature type to return (i.e., recv prepended to the method's
// normal parameters list).
sig := typecheck.NewMethodType(sig0, recv)
if r.Bool() { // type parameter method expression
idx := r.Len()
word := r.dictWord(pos, r.dict.typeParamMethodExprsOffset()+idx)
// TODO(mdempsky): If the type parameter was instantiated with an
// interface type (i.e., embed.IsInterface()), then we could
// return the OMETHEXPR instead and save an indirection.
// We wrote the method expression's entry point PC into the
// dictionary, but for Go `func` values we need to return a
// closure (i.e., pointer to a structure with the PC as the first
// field). Because method expressions don't have any closure
// variables, we pun the dictionary entry as the closure struct.
fn := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, sig, ir.NewAddrExpr(pos, word)))
return fn, fn, nil
}
// TODO(mdempsky): I'm pretty sure this isn't needed: implicits is
// only relevant to locally defined types, but they can't have
// (non-promoted) methods.
var implicits []*types.Type
if r.dict != nil {
implicits = r.dict.targs
}
if r.Bool() { // dynamic subdictionary
idx := r.Len()
info := r.dict.subdicts[idx]
explicits := r.p.typListIdx(info.explicits, r.dict)
shapedObj := r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
shapedFn := shapedMethodExpr(pos, shapedObj, sym)
// TODO(mdempsky): Is there a more robust way to get the
// dictionary pointer type here?
dictPtrType := shapedFn.Type().Params().Field(1).Type
dictPtr := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx)))
return nil, shapedFn, dictPtr
}
if r.Bool() { // static dictionary
info := r.objInfo()
explicits := r.p.typListIdx(info.explicits, r.dict)
shapedObj := r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name)
shapedFn := shapedMethodExpr(pos, shapedObj, sym)
dict := r.p.objDictName(info.idx, implicits, explicits)
dictPtr := typecheck.Expr(ir.NewAddrExpr(pos, dict))
// Check that dictPtr matches shapedFn's dictionary parameter.
if !types.Identical(dictPtr.Type(), shapedFn.Type().Params().Field(1).Type) {
base.FatalfAt(pos, "dict %L, but shaped method %L", dict, shapedFn)
}
// For statically known instantiations, we can take advantage of
// the stenciled wrapper.
base.AssertfAt(!recv.HasShape(), pos, "shaped receiver %v", recv)
wrapperFn := typecheck.Expr(ir.NewSelectorExpr(pos, ir.OXDOT, ir.TypeNode(recv), sym)).(*ir.SelectorExpr)
base.AssertfAt(types.Identical(sig, wrapperFn.Type()), pos, "wrapper %L does not have type %v", wrapperFn, sig)
return wrapperFn, shapedFn, dictPtr
}
// Simple method expression; no dictionary needed.
base.AssertfAt(!recv.HasShape() || recv.IsInterface(), pos, "shaped receiver %v", recv)
fn := typecheck.Expr(ir.NewSelectorExpr(pos, ir.OXDOT, ir.TypeNode(recv), sym)).(*ir.SelectorExpr)
return fn, fn, nil
}
// shapedMethodExpr returns the specified method on the given shaped
// type.
func shapedMethodExpr(pos src.XPos, obj *ir.Name, sym *types.Sym) *ir.SelectorExpr {
assert(obj.Op() == ir.OTYPE)
typ := obj.Type()
assert(typ.HasShape())
method := func() *types.Field {
for _, method := range typ.Methods().Slice() {
if method.Sym == sym {
return method
}
}
base.FatalfAt(pos, "failed to find method %v in shaped type %v", sym, typ)
panic("unreachable")
}()
// Construct an OMETHEXPR node.
recv := method.Type.Recv().Type
return typecheck.Expr(ir.NewSelectorExpr(pos, ir.OXDOT, ir.TypeNode(recv), sym)).(*ir.SelectorExpr)
}
Matthew Dempsky
committed
func (r *reader) multiExpr() []ir.Node {
r.Sync(pkgbits.SyncMultiExpr)
Matthew Dempsky
committed
if r.Bool() { // N:1
pos := r.pos()
expr := r.expr()
results := make([]ir.Node, r.Len())
as := ir.NewAssignListStmt(pos, ir.OAS2, nil, []ir.Node{expr})
as.Def = true
for i := range results {
Matthew Dempsky
committed
tmp := r.temp(pos, r.typ())
Matthew Dempsky
committed
as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp))
as.Lhs.Append(tmp)
res := ir.Node(tmp)
if r.Bool() {
Matthew Dempsky
committed
n := ir.NewConvExpr(pos, ir.OCONV, r.typ(), res)
n.TypeWord, n.SrcRType = r.convRTTI(pos)
Matthew Dempsky
committed
n.SetImplicit(true)
res = typecheck.Expr(n)
Matthew Dempsky
committed
}
results[i] = res
}
// TODO(mdempsky): Could use ir.InlinedCallExpr instead?
results[0] = ir.InitExpr([]ir.Node{typecheck.Stmt(as)}, results[0])
return results
}
// N:N
Matthew Dempsky
committed
exprs := make([]ir.Node, r.Len())
if len(exprs) == 0 {
return nil
}
for i := range exprs {
exprs[i] = r.expr()
}
return exprs
}
Matthew Dempsky
committed
// temp returns a new autotemp of the specified type.
func (r *reader) temp(pos src.XPos, typ *types.Type) *ir.Name {
// See typecheck.typecheckargs.
curfn := r.curfn
if curfn == nil {
curfn = typecheck.InitTodoFunc
}
return typecheck.TempAt(pos, curfn, typ)
}
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
// tempCopy declares and returns a new autotemp initialized to the
// value of expr.
func (r *reader) tempCopy(pos src.XPos, expr ir.Node, init *ir.Nodes) *ir.Name {
if r.curfn == nil {
// Escape analysis doesn't know how to handle package-scope
// function literals with free variables (i.e., that capture
// temporary variables added to typecheck.InitTodoFunc).
//
// stencil.go works around this limitation by spilling values to
// global variables instead, but that causes the value to stay
// alive indefinitely; see go.dev/issue/54343.
//
// This code path (which implements the same workaround) isn't
// actually needed by unified IR, because it creates uses normal
// OMETHEXPR/OMETHVALUE nodes when statically-known instantiated
// types are used. But it's kept around for now because it's handy
// for testing that the generic fallback paths work correctly.
base.Fatalf("tempCopy called at package scope")
tmp := staticinit.StaticName(expr.Type())
assign := ir.NewAssignStmt(pos, tmp, expr)
assign.Def = true
tmp.Defn = assign
typecheck.Target.Decls = append(typecheck.Target.Decls, typecheck.Stmt(assign))
return tmp
}
tmp := r.temp(pos, expr.Type())
init.Append(typecheck.Stmt(ir.NewDecl(pos, ir.ODCL, tmp)))
assign := ir.NewAssignStmt(pos, tmp, expr)
assign.Def = true
init.Append(typecheck.Stmt(ir.NewAssignStmt(pos, tmp, expr)))
tmp.Defn = assign
return tmp
}
func (r *reader) compLit() ir.Node {
r.Sync(pkgbits.SyncCompLit)
typ0 := r.typ()
typ := typ0
if typ.IsPtr() {
typ = typ.Elem()
}
if typ.Kind() == types.TFORW {
base.FatalfAt(pos, "unresolved composite literal type: %v", typ)
}
var rtype ir.Node
if typ.IsMap() {
rtype = r.rtype(pos)
}
isStruct := typ.Kind() == types.TSTRUCT
elems := make([]ir.Node, r.Len())
for i := range elems {
elemp := &elems[i]
if isStruct {
sk := ir.NewStructKeyExpr(r.pos(), typ.Field(r.Len()), nil)
*elemp, elemp = sk, &sk.Value
} else if r.Bool() {