]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/typecheck/typecheck.go
[dev.typeparams] all: merge master (4711bf3) into dev.typeparams
[gostls13.git] / src / cmd / compile / internal / typecheck / typecheck.go
1 // Copyright 2009 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 typecheck
6
7 import (
8         "fmt"
9         "go/constant"
10         "go/token"
11         "strings"
12
13         "cmd/compile/internal/base"
14         "cmd/compile/internal/ir"
15         "cmd/compile/internal/types"
16 )
17
18 // Function collecting autotmps generated during typechecking,
19 // to be included in the package-level init function.
20 var InitTodoFunc = ir.NewFunc(base.Pos)
21
22 var inimport bool // set during import
23
24 var TypecheckAllowed bool
25
26 var (
27         NeedRuntimeType = func(*types.Type) {}
28 )
29
30 func AssignExpr(n ir.Node) ir.Node { return typecheck(n, ctxExpr|ctxAssign) }
31 func Expr(n ir.Node) ir.Node       { return typecheck(n, ctxExpr) }
32 func Stmt(n ir.Node) ir.Node       { return typecheck(n, ctxStmt) }
33
34 func Exprs(exprs []ir.Node) { typecheckslice(exprs, ctxExpr) }
35 func Stmts(stmts []ir.Node) { typecheckslice(stmts, ctxStmt) }
36
37 func Call(call *ir.CallExpr) {
38         t := call.X.Type()
39         if t == nil {
40                 panic("misuse of Call")
41         }
42         ctx := ctxStmt
43         if t.NumResults() > 0 {
44                 ctx = ctxExpr | ctxMultiOK
45         }
46         if typecheck(call, ctx) != call {
47                 panic("bad typecheck")
48         }
49 }
50
51 func Callee(n ir.Node) ir.Node {
52         return typecheck(n, ctxExpr|ctxCallee)
53 }
54
55 func FuncBody(n *ir.Func) {
56         ir.CurFunc = n
57         errorsBefore := base.Errors()
58         Stmts(n.Body)
59         CheckUnused(n)
60         CheckReturn(n)
61         if base.Errors() > errorsBefore {
62                 n.Body = nil // type errors; do not compile
63         }
64 }
65
66 var importlist []*ir.Func
67
68 // AllImportedBodies reads in the bodies of all imported functions and typechecks
69 // them, if needed.
70 func AllImportedBodies() {
71         for _, n := range importlist {
72                 if n.Inl != nil {
73                         ImportedBody(n)
74                 }
75         }
76 }
77
78 var traceIndent []byte
79
80 func tracePrint(title string, n ir.Node) func(np *ir.Node) {
81         indent := traceIndent
82
83         // guard against nil
84         var pos, op string
85         var tc uint8
86         if n != nil {
87                 pos = base.FmtPos(n.Pos())
88                 op = n.Op().String()
89                 tc = n.Typecheck()
90         }
91
92         types.SkipSizeForTracing = true
93         defer func() { types.SkipSizeForTracing = false }()
94         fmt.Printf("%s: %s%s %p %s %v tc=%d\n", pos, indent, title, n, op, n, tc)
95         traceIndent = append(traceIndent, ". "...)
96
97         return func(np *ir.Node) {
98                 traceIndent = traceIndent[:len(traceIndent)-2]
99
100                 // if we have a result, use that
101                 if np != nil {
102                         n = *np
103                 }
104
105                 // guard against nil
106                 // use outer pos, op so we don't get empty pos/op if n == nil (nicer output)
107                 var tc uint8
108                 var typ *types.Type
109                 if n != nil {
110                         pos = base.FmtPos(n.Pos())
111                         op = n.Op().String()
112                         tc = n.Typecheck()
113                         typ = n.Type()
114                 }
115
116                 types.SkipSizeForTracing = true
117                 defer func() { types.SkipSizeForTracing = false }()
118                 fmt.Printf("%s: %s=> %p %s %v tc=%d type=%L\n", pos, indent, n, op, n, tc, typ)
119         }
120 }
121
122 const (
123         ctxStmt    = 1 << iota // evaluated at statement level
124         ctxExpr                // evaluated in value context
125         ctxType                // evaluated in type context
126         ctxCallee              // call-only expressions are ok
127         ctxMultiOK             // multivalue function returns are ok
128         ctxAssign              // assigning to expression
129 )
130
131 // type checks the whole tree of an expression.
132 // calculates expression types.
133 // evaluates compile time constants.
134 // marks variables that escape the local frame.
135 // rewrites n.Op to be more specific in some cases.
136
137 var typecheckdefstack []*ir.Name
138
139 // Resolve ONONAME to definition, if any.
140 func Resolve(n ir.Node) (res ir.Node) {
141         if n == nil || n.Op() != ir.ONONAME {
142                 return n
143         }
144
145         // only trace if there's work to do
146         if base.EnableTrace && base.Flag.LowerT {
147                 defer tracePrint("resolve", n)(&res)
148         }
149
150         if sym := n.Sym(); sym.Pkg != types.LocalPkg {
151                 // We might have an ir.Ident from oldname or importDot.
152                 if id, ok := n.(*ir.Ident); ok {
153                         if pkgName := DotImportRefs[id]; pkgName != nil {
154                                 pkgName.Used = true
155                         }
156                 }
157
158                 return expandDecl(n)
159         }
160
161         r := ir.AsNode(n.Sym().Def)
162         if r == nil {
163                 return n
164         }
165
166         if r.Op() == ir.OIOTA {
167                 if x := getIotaValue(); x >= 0 {
168                         return ir.NewInt(x)
169                 }
170                 return n
171         }
172
173         return r
174 }
175
176 func typecheckslice(l []ir.Node, top int) {
177         for i := range l {
178                 l[i] = typecheck(l[i], top)
179         }
180 }
181
182 var _typekind = []string{
183         types.TINT:        "int",
184         types.TUINT:       "uint",
185         types.TINT8:       "int8",
186         types.TUINT8:      "uint8",
187         types.TINT16:      "int16",
188         types.TUINT16:     "uint16",
189         types.TINT32:      "int32",
190         types.TUINT32:     "uint32",
191         types.TINT64:      "int64",
192         types.TUINT64:     "uint64",
193         types.TUINTPTR:    "uintptr",
194         types.TCOMPLEX64:  "complex64",
195         types.TCOMPLEX128: "complex128",
196         types.TFLOAT32:    "float32",
197         types.TFLOAT64:    "float64",
198         types.TBOOL:       "bool",
199         types.TSTRING:     "string",
200         types.TPTR:        "pointer",
201         types.TUNSAFEPTR:  "unsafe.Pointer",
202         types.TSTRUCT:     "struct",
203         types.TINTER:      "interface",
204         types.TCHAN:       "chan",
205         types.TMAP:        "map",
206         types.TARRAY:      "array",
207         types.TSLICE:      "slice",
208         types.TFUNC:       "func",
209         types.TNIL:        "nil",
210         types.TIDEAL:      "untyped number",
211 }
212
213 func typekind(t *types.Type) string {
214         if t.IsUntyped() {
215                 return fmt.Sprintf("%v", t)
216         }
217         et := t.Kind()
218         if int(et) < len(_typekind) {
219                 s := _typekind[et]
220                 if s != "" {
221                         return s
222                 }
223         }
224         return fmt.Sprintf("etype=%d", et)
225 }
226
227 func cycleFor(start ir.Node) []ir.Node {
228         // Find the start node in typecheck_tcstack.
229         // We know that it must exist because each time we mark
230         // a node with n.SetTypecheck(2) we push it on the stack,
231         // and each time we mark a node with n.SetTypecheck(2) we
232         // pop it from the stack. We hit a cycle when we encounter
233         // a node marked 2 in which case is must be on the stack.
234         i := len(typecheck_tcstack) - 1
235         for i > 0 && typecheck_tcstack[i] != start {
236                 i--
237         }
238
239         // collect all nodes with same Op
240         var cycle []ir.Node
241         for _, n := range typecheck_tcstack[i:] {
242                 if n.Op() == start.Op() {
243                         cycle = append(cycle, n)
244                 }
245         }
246
247         return cycle
248 }
249
250 func cycleTrace(cycle []ir.Node) string {
251         var s string
252         for i, n := range cycle {
253                 s += fmt.Sprintf("\n\t%v: %v uses %v", ir.Line(n), n, cycle[(i+1)%len(cycle)])
254         }
255         return s
256 }
257
258 var typecheck_tcstack []ir.Node
259
260 func Func(fn *ir.Func) {
261         new := Stmt(fn)
262         if new != fn {
263                 base.Fatalf("typecheck changed func")
264         }
265 }
266
267 func typecheckNtype(n ir.Ntype) ir.Ntype {
268         return typecheck(n, ctxType).(ir.Ntype)
269 }
270
271 // typecheck type checks node n.
272 // The result of typecheck MUST be assigned back to n, e.g.
273 //      n.Left = typecheck(n.Left, top)
274 func typecheck(n ir.Node, top int) (res ir.Node) {
275         // cannot type check until all the source has been parsed
276         if !TypecheckAllowed {
277                 base.Fatalf("early typecheck")
278         }
279
280         if n == nil {
281                 return nil
282         }
283
284         // only trace if there's work to do
285         if base.EnableTrace && base.Flag.LowerT {
286                 defer tracePrint("typecheck", n)(&res)
287         }
288
289         lno := ir.SetPos(n)
290
291         // Skip over parens.
292         for n.Op() == ir.OPAREN {
293                 n = n.(*ir.ParenExpr).X
294         }
295
296         // Resolve definition of name and value of iota lazily.
297         n = Resolve(n)
298
299         // Skip typecheck if already done.
300         // But re-typecheck ONAME/OTYPE/OLITERAL/OPACK node in case context has changed.
301         if n.Typecheck() == 1 || n.Typecheck() == 3 {
302                 switch n.Op() {
303                 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.OPACK:
304                         break
305
306                 default:
307                         base.Pos = lno
308                         return n
309                 }
310         }
311
312         if n.Typecheck() == 2 {
313                 // Typechecking loop. Trying printing a meaningful message,
314                 // otherwise a stack trace of typechecking.
315                 switch n.Op() {
316                 // We can already diagnose variables used as types.
317                 case ir.ONAME:
318                         n := n.(*ir.Name)
319                         if top&(ctxExpr|ctxType) == ctxType {
320                                 base.Errorf("%v is not a type", n)
321                         }
322
323                 case ir.OTYPE:
324                         // Only report a type cycle if we are expecting a type.
325                         // Otherwise let other code report an error.
326                         if top&ctxType == ctxType {
327                                 // A cycle containing only alias types is an error
328                                 // since it would expand indefinitely when aliases
329                                 // are substituted.
330                                 cycle := cycleFor(n)
331                                 for _, n1 := range cycle {
332                                         if n1.Name() != nil && !n1.Name().Alias() {
333                                                 // Cycle is ok. But if n is an alias type and doesn't
334                                                 // have a type yet, we have a recursive type declaration
335                                                 // with aliases that we can't handle properly yet.
336                                                 // Report an error rather than crashing later.
337                                                 if n.Name() != nil && n.Name().Alias() && n.Type() == nil {
338                                                         base.Pos = n.Pos()
339                                                         base.Fatalf("cannot handle alias type declaration (issue #25838): %v", n)
340                                                 }
341                                                 base.Pos = lno
342                                                 return n
343                                         }
344                                 }
345                                 base.ErrorfAt(n.Pos(), "invalid recursive type alias %v%s", n, cycleTrace(cycle))
346                         }
347
348                 case ir.OLITERAL:
349                         if top&(ctxExpr|ctxType) == ctxType {
350                                 base.Errorf("%v is not a type", n)
351                                 break
352                         }
353                         base.ErrorfAt(n.Pos(), "constant definition loop%s", cycleTrace(cycleFor(n)))
354                 }
355
356                 if base.Errors() == 0 {
357                         var trace string
358                         for i := len(typecheck_tcstack) - 1; i >= 0; i-- {
359                                 x := typecheck_tcstack[i]
360                                 trace += fmt.Sprintf("\n\t%v %v", ir.Line(x), x)
361                         }
362                         base.Errorf("typechecking loop involving %v%s", n, trace)
363                 }
364
365                 base.Pos = lno
366                 return n
367         }
368
369         typecheck_tcstack = append(typecheck_tcstack, n)
370
371         n.SetTypecheck(2)
372         n = typecheck1(n, top)
373         n.SetTypecheck(1)
374
375         last := len(typecheck_tcstack) - 1
376         typecheck_tcstack[last] = nil
377         typecheck_tcstack = typecheck_tcstack[:last]
378
379         _, isExpr := n.(ir.Expr)
380         _, isStmt := n.(ir.Stmt)
381         isMulti := false
382         switch n.Op() {
383         case ir.OCALLFUNC, ir.OCALLINTER, ir.OCALLMETH:
384                 n := n.(*ir.CallExpr)
385                 if t := n.X.Type(); t != nil && t.Kind() == types.TFUNC {
386                         nr := t.NumResults()
387                         isMulti = nr > 1
388                         if nr == 0 {
389                                 isExpr = false
390                         }
391                 }
392         case ir.OAPPEND:
393                 // Must be used (and not BinaryExpr/UnaryExpr).
394                 isStmt = false
395         case ir.OCLOSE, ir.ODELETE, ir.OPANIC, ir.OPRINT, ir.OPRINTN, ir.OVARKILL, ir.OVARLIVE:
396                 // Must not be used.
397                 isExpr = false
398                 isStmt = true
399         case ir.OCOPY, ir.ORECOVER, ir.ORECV:
400                 // Can be used or not.
401                 isStmt = true
402         }
403
404         t := n.Type()
405         if t != nil && !t.IsFuncArgStruct() && n.Op() != ir.OTYPE {
406                 switch t.Kind() {
407                 case types.TFUNC, // might have TANY; wait until it's called
408                         types.TANY, types.TFORW, types.TIDEAL, types.TNIL, types.TBLANK:
409                         break
410
411                 default:
412                         types.CheckSize(t)
413                 }
414         }
415         if t != nil {
416                 n = EvalConst(n)
417                 t = n.Type()
418         }
419
420         // TODO(rsc): Lots of the complexity here is because typecheck can
421         // see OTYPE, ONAME, and OLITERAL nodes multiple times.
422         // Once we make the IR a proper tree, we should be able to simplify
423         // this code a bit, especially the final case.
424         switch {
425         case top&(ctxStmt|ctxExpr) == ctxExpr && !isExpr && n.Op() != ir.OTYPE && !isMulti:
426                 if !n.Diag() {
427                         base.Errorf("%v used as value", n)
428                         n.SetDiag(true)
429                 }
430                 if t != nil {
431                         n.SetType(nil)
432                 }
433
434         case top&ctxType == 0 && n.Op() == ir.OTYPE && t != nil:
435                 if !n.Type().Broke() {
436                         base.Errorf("type %v is not an expression", n.Type())
437                         n.SetDiag(true)
438                 }
439
440         case top&(ctxStmt|ctxExpr) == ctxStmt && !isStmt && t != nil:
441                 if !n.Diag() {
442                         base.Errorf("%v evaluated but not used", n)
443                         n.SetDiag(true)
444                 }
445                 n.SetType(nil)
446
447         case top&(ctxType|ctxExpr) == ctxType && n.Op() != ir.OTYPE && n.Op() != ir.ONONAME && (t != nil || n.Op() == ir.ONAME):
448                 base.Errorf("%v is not a type", n)
449                 if t != nil {
450                         if n.Op() == ir.ONAME {
451                                 t.SetBroke(true)
452                         } else {
453                                 n.SetType(nil)
454                         }
455                 }
456
457         }
458
459         base.Pos = lno
460         return n
461 }
462
463 // indexlit implements typechecking of untyped values as
464 // array/slice indexes. It is almost equivalent to DefaultLit
465 // but also accepts untyped numeric values representable as
466 // value of type int (see also checkmake for comparison).
467 // The result of indexlit MUST be assigned back to n, e.g.
468 //      n.Left = indexlit(n.Left)
469 func indexlit(n ir.Node) ir.Node {
470         if n != nil && n.Type() != nil && n.Type().Kind() == types.TIDEAL {
471                 return DefaultLit(n, types.Types[types.TINT])
472         }
473         return n
474 }
475
476 // typecheck1 should ONLY be called from typecheck.
477 func typecheck1(n ir.Node, top int) ir.Node {
478         if n, ok := n.(*ir.Name); ok {
479                 typecheckdef(n)
480         }
481
482         switch n.Op() {
483         default:
484                 ir.Dump("typecheck", n)
485                 base.Fatalf("typecheck %v", n.Op())
486                 panic("unreachable")
487
488         case ir.OLITERAL:
489                 if n.Sym() == nil && n.Type() == nil {
490                         if !n.Diag() {
491                                 base.Fatalf("literal missing type: %v", n)
492                         }
493                 }
494                 return n
495
496         case ir.ONIL:
497                 return n
498
499         // names
500         case ir.ONONAME:
501                 if !n.Diag() {
502                         // Note: adderrorname looks for this string and
503                         // adds context about the outer expression
504                         base.ErrorfAt(n.Pos(), "undefined: %v", n.Sym())
505                         n.SetDiag(true)
506                 }
507                 n.SetType(nil)
508                 return n
509
510         case ir.ONAME:
511                 n := n.(*ir.Name)
512                 if n.BuiltinOp != 0 {
513                         if top&ctxCallee == 0 {
514                                 base.Errorf("use of builtin %v not in function call", n.Sym())
515                                 n.SetType(nil)
516                                 return n
517                         }
518                         return n
519                 }
520                 if top&ctxAssign == 0 {
521                         // not a write to the variable
522                         if ir.IsBlank(n) {
523                                 base.Errorf("cannot use _ as value")
524                                 n.SetType(nil)
525                                 return n
526                         }
527                         n.SetUsed(true)
528                 }
529                 return n
530
531         case ir.OLINKSYMOFFSET:
532                 // type already set
533                 return n
534
535         case ir.OPACK:
536                 n := n.(*ir.PkgName)
537                 base.Errorf("use of package %v without selector", n.Sym())
538                 n.SetDiag(true)
539                 return n
540
541         // types (ODEREF is with exprs)
542         case ir.OTYPE:
543                 return n
544
545         case ir.OTSLICE:
546                 n := n.(*ir.SliceType)
547                 return tcSliceType(n)
548
549         case ir.OTARRAY:
550                 n := n.(*ir.ArrayType)
551                 return tcArrayType(n)
552
553         case ir.OTMAP:
554                 n := n.(*ir.MapType)
555                 return tcMapType(n)
556
557         case ir.OTCHAN:
558                 n := n.(*ir.ChanType)
559                 return tcChanType(n)
560
561         case ir.OTSTRUCT:
562                 n := n.(*ir.StructType)
563                 return tcStructType(n)
564
565         case ir.OTINTER:
566                 n := n.(*ir.InterfaceType)
567                 return tcInterfaceType(n)
568
569         case ir.OTFUNC:
570                 n := n.(*ir.FuncType)
571                 return tcFuncType(n)
572         // type or expr
573         case ir.ODEREF:
574                 n := n.(*ir.StarExpr)
575                 return tcStar(n, top)
576
577         // x op= y
578         case ir.OASOP:
579                 n := n.(*ir.AssignOpStmt)
580                 n.X, n.Y = Expr(n.X), Expr(n.Y)
581                 checkassign(n, n.X)
582                 if n.IncDec && !okforarith[n.X.Type().Kind()] {
583                         base.Errorf("invalid operation: %v (non-numeric type %v)", n, n.X.Type())
584                         return n
585                 }
586                 switch n.AsOp {
587                 case ir.OLSH, ir.ORSH:
588                         n.X, n.Y, _ = tcShift(n, n.X, n.Y)
589                 case ir.OADD, ir.OAND, ir.OANDNOT, ir.ODIV, ir.OMOD, ir.OMUL, ir.OOR, ir.OSUB, ir.OXOR:
590                         n.X, n.Y, _ = tcArith(n, n.AsOp, n.X, n.Y)
591                 default:
592                         base.Fatalf("invalid assign op: %v", n.AsOp)
593                 }
594                 return n
595
596         // logical operators
597         case ir.OANDAND, ir.OOROR:
598                 n := n.(*ir.LogicalExpr)
599                 n.X, n.Y = Expr(n.X), Expr(n.Y)
600                 if n.X.Type() == nil || n.Y.Type() == nil {
601                         n.SetType(nil)
602                         return n
603                 }
604                 // For "x == x && len(s)", it's better to report that "len(s)" (type int)
605                 // can't be used with "&&" than to report that "x == x" (type untyped bool)
606                 // can't be converted to int (see issue #41500).
607                 if !n.X.Type().IsBoolean() {
608                         base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, n.Op(), typekind(n.X.Type()))
609                         n.SetType(nil)
610                         return n
611                 }
612                 if !n.Y.Type().IsBoolean() {
613                         base.Errorf("invalid operation: %v (operator %v not defined on %s)", n, n.Op(), typekind(n.Y.Type()))
614                         n.SetType(nil)
615                         return n
616                 }
617                 l, r, t := tcArith(n, n.Op(), n.X, n.Y)
618                 n.X, n.Y = l, r
619                 n.SetType(t)
620                 return n
621
622         // shift operators
623         case ir.OLSH, ir.ORSH:
624                 n := n.(*ir.BinaryExpr)
625                 n.X, n.Y = Expr(n.X), Expr(n.Y)
626                 l, r, t := tcShift(n, n.X, n.Y)
627                 n.X, n.Y = l, r
628                 n.SetType(t)
629                 return n
630
631         // comparison operators
632         case ir.OEQ, ir.OGE, ir.OGT, ir.OLE, ir.OLT, ir.ONE:
633                 n := n.(*ir.BinaryExpr)
634                 n.X, n.Y = Expr(n.X), Expr(n.Y)
635                 l, r, t := tcArith(n, n.Op(), n.X, n.Y)
636                 if t != nil {
637                         n.X, n.Y = l, r
638                         n.SetType(types.UntypedBool)
639                         if con := EvalConst(n); con.Op() == ir.OLITERAL {
640                                 return con
641                         }
642                         n.X, n.Y = defaultlit2(l, r, true)
643                 }
644                 return n
645
646         // binary operators
647         case ir.OADD, ir.OAND, ir.OANDNOT, ir.ODIV, ir.OMOD, ir.OMUL, ir.OOR, ir.OSUB, ir.OXOR:
648                 n := n.(*ir.BinaryExpr)
649                 n.X, n.Y = Expr(n.X), Expr(n.Y)
650                 l, r, t := tcArith(n, n.Op(), n.X, n.Y)
651                 if t != nil && t.Kind() == types.TSTRING && n.Op() == ir.OADD {
652                         // create or update OADDSTR node with list of strings in x + y + z + (w + v) + ...
653                         var add *ir.AddStringExpr
654                         if l.Op() == ir.OADDSTR {
655                                 add = l.(*ir.AddStringExpr)
656                                 add.SetPos(n.Pos())
657                         } else {
658                                 add = ir.NewAddStringExpr(n.Pos(), []ir.Node{l})
659                         }
660                         if r.Op() == ir.OADDSTR {
661                                 r := r.(*ir.AddStringExpr)
662                                 add.List.Append(r.List.Take()...)
663                         } else {
664                                 add.List.Append(r)
665                         }
666                         add.SetType(t)
667                         return add
668                 }
669                 n.X, n.Y = l, r
670                 n.SetType(t)
671                 return n
672
673         case ir.OBITNOT, ir.ONEG, ir.ONOT, ir.OPLUS:
674                 n := n.(*ir.UnaryExpr)
675                 return tcUnaryArith(n)
676
677         // exprs
678         case ir.OADDR:
679                 n := n.(*ir.AddrExpr)
680                 return tcAddr(n)
681
682         case ir.OCOMPLIT:
683                 return tcCompLit(n.(*ir.CompLitExpr))
684
685         case ir.OXDOT, ir.ODOT:
686                 n := n.(*ir.SelectorExpr)
687                 return tcDot(n, top)
688
689         case ir.ODOTTYPE:
690                 n := n.(*ir.TypeAssertExpr)
691                 return tcDotType(n)
692
693         case ir.OINDEX:
694                 n := n.(*ir.IndexExpr)
695                 return tcIndex(n)
696
697         case ir.ORECV:
698                 n := n.(*ir.UnaryExpr)
699                 return tcRecv(n)
700
701         case ir.OSEND:
702                 n := n.(*ir.SendStmt)
703                 return tcSend(n)
704
705         case ir.OSLICEHEADER:
706                 n := n.(*ir.SliceHeaderExpr)
707                 return tcSliceHeader(n)
708
709         case ir.OMAKESLICECOPY:
710                 n := n.(*ir.MakeExpr)
711                 return tcMakeSliceCopy(n)
712
713         case ir.OSLICE, ir.OSLICE3:
714                 n := n.(*ir.SliceExpr)
715                 return tcSlice(n)
716
717         // call and call like
718         case ir.OCALL:
719                 n := n.(*ir.CallExpr)
720                 return tcCall(n, top)
721
722         case ir.OALIGNOF, ir.OOFFSETOF, ir.OSIZEOF:
723                 n := n.(*ir.UnaryExpr)
724                 n.SetType(types.Types[types.TUINTPTR])
725                 return n
726
727         case ir.OCAP, ir.OLEN:
728                 n := n.(*ir.UnaryExpr)
729                 return tcLenCap(n)
730
731         case ir.OREAL, ir.OIMAG:
732                 n := n.(*ir.UnaryExpr)
733                 return tcRealImag(n)
734
735         case ir.OCOMPLEX:
736                 n := n.(*ir.BinaryExpr)
737                 return tcComplex(n)
738
739         case ir.OCLOSE:
740                 n := n.(*ir.UnaryExpr)
741                 return tcClose(n)
742
743         case ir.ODELETE:
744                 n := n.(*ir.CallExpr)
745                 return tcDelete(n)
746
747         case ir.OAPPEND:
748                 n := n.(*ir.CallExpr)
749                 return tcAppend(n)
750
751         case ir.OCOPY:
752                 n := n.(*ir.BinaryExpr)
753                 return tcCopy(n)
754
755         case ir.OCONV:
756                 n := n.(*ir.ConvExpr)
757                 return tcConv(n)
758
759         case ir.OMAKE:
760                 n := n.(*ir.CallExpr)
761                 return tcMake(n)
762
763         case ir.ONEW:
764                 n := n.(*ir.UnaryExpr)
765                 return tcNew(n)
766
767         case ir.OPRINT, ir.OPRINTN:
768                 n := n.(*ir.CallExpr)
769                 return tcPrint(n)
770
771         case ir.OPANIC:
772                 n := n.(*ir.UnaryExpr)
773                 return tcPanic(n)
774
775         case ir.ORECOVER:
776                 n := n.(*ir.CallExpr)
777                 return tcRecover(n)
778
779         case ir.ORECOVERFP:
780                 n := n.(*ir.CallExpr)
781                 return tcRecoverFP(n)
782
783         case ir.OUNSAFEADD:
784                 n := n.(*ir.BinaryExpr)
785                 return tcUnsafeAdd(n)
786
787         case ir.OUNSAFESLICE:
788                 n := n.(*ir.BinaryExpr)
789                 return tcUnsafeSlice(n)
790
791         case ir.OCLOSURE:
792                 n := n.(*ir.ClosureExpr)
793                 return tcClosure(n, top)
794
795         case ir.OITAB:
796                 n := n.(*ir.UnaryExpr)
797                 return tcITab(n)
798
799         case ir.OIDATA:
800                 // Whoever creates the OIDATA node must know a priori the concrete type at that moment,
801                 // usually by just having checked the OITAB.
802                 n := n.(*ir.UnaryExpr)
803                 base.Fatalf("cannot typecheck interface data %v", n)
804                 panic("unreachable")
805
806         case ir.OSPTR:
807                 n := n.(*ir.UnaryExpr)
808                 return tcSPtr(n)
809
810         case ir.OCFUNC:
811                 n := n.(*ir.UnaryExpr)
812                 n.X = Expr(n.X)
813                 n.SetType(types.Types[types.TUINTPTR])
814                 return n
815
816         case ir.OGETCALLERPC, ir.OGETCALLERSP:
817                 n := n.(*ir.CallExpr)
818                 if len(n.Args) != 0 {
819                         base.FatalfAt(n.Pos(), "unexpected arguments: %v", n)
820                 }
821                 n.SetType(types.Types[types.TUINTPTR])
822                 return n
823
824         case ir.OCONVNOP:
825                 n := n.(*ir.ConvExpr)
826                 n.X = Expr(n.X)
827                 return n
828
829         // statements
830         case ir.OAS:
831                 n := n.(*ir.AssignStmt)
832                 tcAssign(n)
833
834                 // Code that creates temps does not bother to set defn, so do it here.
835                 if n.X.Op() == ir.ONAME && ir.IsAutoTmp(n.X) {
836                         n.X.Name().Defn = n
837                 }
838                 return n
839
840         case ir.OAS2:
841                 tcAssignList(n.(*ir.AssignListStmt))
842                 return n
843
844         case ir.OBREAK,
845                 ir.OCONTINUE,
846                 ir.ODCL,
847                 ir.OGOTO,
848                 ir.OFALL,
849                 ir.OVARKILL,
850                 ir.OVARLIVE:
851                 return n
852
853         case ir.OBLOCK:
854                 n := n.(*ir.BlockStmt)
855                 Stmts(n.List)
856                 return n
857
858         case ir.OLABEL:
859                 if n.Sym().IsBlank() {
860                         // Empty identifier is valid but useless.
861                         // Eliminate now to simplify life later.
862                         // See issues 7538, 11589, 11593.
863                         n = ir.NewBlockStmt(n.Pos(), nil)
864                 }
865                 return n
866
867         case ir.ODEFER, ir.OGO:
868                 n := n.(*ir.GoDeferStmt)
869                 n.Call = typecheck(n.Call, ctxStmt|ctxExpr)
870                 if !n.Call.Diag() {
871                         tcGoDefer(n)
872                 }
873                 return n
874
875         case ir.OFOR, ir.OFORUNTIL:
876                 n := n.(*ir.ForStmt)
877                 return tcFor(n)
878
879         case ir.OIF:
880                 n := n.(*ir.IfStmt)
881                 return tcIf(n)
882
883         case ir.ORETURN:
884                 n := n.(*ir.ReturnStmt)
885                 return tcReturn(n)
886
887         case ir.OTAILCALL:
888                 n := n.(*ir.TailCallStmt)
889                 return n
890
891         case ir.OCHECKNIL:
892                 n := n.(*ir.UnaryExpr)
893                 return tcCheckNil(n)
894
895         case ir.OSELECT:
896                 tcSelect(n.(*ir.SelectStmt))
897                 return n
898
899         case ir.OSWITCH:
900                 tcSwitch(n.(*ir.SwitchStmt))
901                 return n
902
903         case ir.ORANGE:
904                 tcRange(n.(*ir.RangeStmt))
905                 return n
906
907         case ir.OTYPESW:
908                 n := n.(*ir.TypeSwitchGuard)
909                 base.Errorf("use of .(type) outside type switch")
910                 n.SetDiag(true)
911                 return n
912
913         case ir.ODCLFUNC:
914                 tcFunc(n.(*ir.Func))
915                 return n
916
917         case ir.ODCLCONST:
918                 n := n.(*ir.Decl)
919                 n.X = Expr(n.X).(*ir.Name)
920                 return n
921
922         case ir.ODCLTYPE:
923                 n := n.(*ir.Decl)
924                 n.X = typecheck(n.X, ctxType).(*ir.Name)
925                 types.CheckSize(n.X.Type())
926                 return n
927         }
928
929         // No return n here!
930         // Individual cases can type-assert n, introducing a new one.
931         // Each must execute its own return n.
932 }
933
934 func typecheckargs(n ir.InitNode) {
935         var list []ir.Node
936         switch n := n.(type) {
937         default:
938                 base.Fatalf("typecheckargs %+v", n.Op())
939         case *ir.CallExpr:
940                 list = n.Args
941                 if n.IsDDD {
942                         Exprs(list)
943                         return
944                 }
945         case *ir.ReturnStmt:
946                 list = n.Results
947         }
948         if len(list) != 1 {
949                 Exprs(list)
950                 return
951         }
952
953         typecheckslice(list, ctxExpr|ctxMultiOK)
954         t := list[0].Type()
955         if t == nil || !t.IsFuncArgStruct() {
956                 return
957         }
958
959         // Save n as n.Orig for fmt.go.
960         if ir.Orig(n) == n {
961                 n.(ir.OrigNode).SetOrig(ir.SepCopy(n))
962         }
963
964         // Rewrite f(g()) into t1, t2, ... = g(); f(t1, t2, ...).
965         RewriteMultiValueCall(n, list[0])
966 }
967
968 // RewriteMultiValueCall rewrites multi-valued f() to use temporaries,
969 // so the backend wouldn't need to worry about tuple-valued expressions.
970 func RewriteMultiValueCall(n ir.InitNode, call ir.Node) {
971         // If we're outside of function context, then this call will
972         // be executed during the generated init function. However,
973         // init.go hasn't yet created it. Instead, associate the
974         // temporary variables with  InitTodoFunc for now, and init.go
975         // will reassociate them later when it's appropriate.
976         static := ir.CurFunc == nil
977         if static {
978                 ir.CurFunc = InitTodoFunc
979         }
980
981         as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, []ir.Node{call})
982         results := call.Type().FieldSlice()
983         list := make([]ir.Node, len(results))
984         for i, result := range results {
985                 tmp := Temp(result.Type)
986                 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, tmp))
987                 as.Lhs.Append(tmp)
988                 list[i] = tmp
989         }
990         if static {
991                 ir.CurFunc = nil
992         }
993
994         n.PtrInit().Append(Stmt(as))
995
996         switch n := n.(type) {
997         default:
998                 base.Fatalf("rewriteMultiValueCall %+v", n.Op())
999         case *ir.CallExpr:
1000                 n.Args = list
1001         case *ir.ReturnStmt:
1002                 n.Results = list
1003         case *ir.AssignListStmt:
1004                 if n.Op() != ir.OAS2FUNC {
1005                         base.Fatalf("rewriteMultiValueCall: invalid op %v", n.Op())
1006                 }
1007                 as.SetOp(ir.OAS2FUNC)
1008                 n.SetOp(ir.OAS2)
1009                 n.Rhs = make([]ir.Node, len(list))
1010                 for i, tmp := range list {
1011                         n.Rhs[i] = AssignConv(tmp, n.Lhs[i].Type(), "assignment")
1012                 }
1013         }
1014 }
1015
1016 func checksliceindex(l ir.Node, r ir.Node, tp *types.Type) bool {
1017         t := r.Type()
1018         if t == nil {
1019                 return false
1020         }
1021         if !t.IsInteger() {
1022                 base.Errorf("invalid slice index %v (type %v)", r, t)
1023                 return false
1024         }
1025
1026         if r.Op() == ir.OLITERAL {
1027                 x := r.Val()
1028                 if constant.Sign(x) < 0 {
1029                         base.Errorf("invalid slice index %v (index must be non-negative)", r)
1030                         return false
1031                 } else if tp != nil && tp.NumElem() >= 0 && constant.Compare(x, token.GTR, constant.MakeInt64(tp.NumElem())) {
1032                         base.Errorf("invalid slice index %v (out of bounds for %d-element array)", r, tp.NumElem())
1033                         return false
1034                 } else if ir.IsConst(l, constant.String) && constant.Compare(x, token.GTR, constant.MakeInt64(int64(len(ir.StringVal(l))))) {
1035                         base.Errorf("invalid slice index %v (out of bounds for %d-byte string)", r, len(ir.StringVal(l)))
1036                         return false
1037                 } else if ir.ConstOverflow(x, types.Types[types.TINT]) {
1038                         base.Errorf("invalid slice index %v (index too large)", r)
1039                         return false
1040                 }
1041         }
1042
1043         return true
1044 }
1045
1046 func checksliceconst(lo ir.Node, hi ir.Node) bool {
1047         if lo != nil && hi != nil && lo.Op() == ir.OLITERAL && hi.Op() == ir.OLITERAL && constant.Compare(lo.Val(), token.GTR, hi.Val()) {
1048                 base.Errorf("invalid slice index: %v > %v", lo, hi)
1049                 return false
1050         }
1051
1052         return true
1053 }
1054
1055 // The result of implicitstar MUST be assigned back to n, e.g.
1056 //      n.Left = implicitstar(n.Left)
1057 func implicitstar(n ir.Node) ir.Node {
1058         // insert implicit * if needed for fixed array
1059         t := n.Type()
1060         if t == nil || !t.IsPtr() {
1061                 return n
1062         }
1063         t = t.Elem()
1064         if t == nil {
1065                 return n
1066         }
1067         if !t.IsArray() {
1068                 return n
1069         }
1070         star := ir.NewStarExpr(base.Pos, n)
1071         star.SetImplicit(true)
1072         return Expr(star)
1073 }
1074
1075 func needOneArg(n *ir.CallExpr, f string, args ...interface{}) (ir.Node, bool) {
1076         if len(n.Args) == 0 {
1077                 p := fmt.Sprintf(f, args...)
1078                 base.Errorf("missing argument to %s: %v", p, n)
1079                 return nil, false
1080         }
1081
1082         if len(n.Args) > 1 {
1083                 p := fmt.Sprintf(f, args...)
1084                 base.Errorf("too many arguments to %s: %v", p, n)
1085                 return n.Args[0], false
1086         }
1087
1088         return n.Args[0], true
1089 }
1090
1091 func needTwoArgs(n *ir.CallExpr) (ir.Node, ir.Node, bool) {
1092         if len(n.Args) != 2 {
1093                 if len(n.Args) < 2 {
1094                         base.Errorf("not enough arguments in call to %v", n)
1095                 } else {
1096                         base.Errorf("too many arguments in call to %v", n)
1097                 }
1098                 return nil, nil, false
1099         }
1100         return n.Args[0], n.Args[1], true
1101 }
1102
1103 // Lookdot1 looks up the specified method s in the list fs of methods, returning
1104 // the matching field or nil. If dostrcmp is 0, it matches the symbols. If
1105 // dostrcmp is 1, it matches by name exactly. If dostrcmp is 2, it matches names
1106 // with case folding.
1107 func Lookdot1(errnode ir.Node, s *types.Sym, t *types.Type, fs *types.Fields, dostrcmp int) *types.Field {
1108         var r *types.Field
1109         for _, f := range fs.Slice() {
1110                 if dostrcmp != 0 && f.Sym.Name == s.Name {
1111                         return f
1112                 }
1113                 if dostrcmp == 2 && strings.EqualFold(f.Sym.Name, s.Name) {
1114                         return f
1115                 }
1116                 if f.Sym != s {
1117                         continue
1118                 }
1119                 if r != nil {
1120                         if errnode != nil {
1121                                 base.Errorf("ambiguous selector %v", errnode)
1122                         } else if t.IsPtr() {
1123                                 base.Errorf("ambiguous selector (%v).%v", t, s)
1124                         } else {
1125                                 base.Errorf("ambiguous selector %v.%v", t, s)
1126                         }
1127                         break
1128                 }
1129
1130                 r = f
1131         }
1132
1133         return r
1134 }
1135
1136 // typecheckMethodExpr checks selector expressions (ODOT) where the
1137 // base expression is a type expression (OTYPE).
1138 func typecheckMethodExpr(n *ir.SelectorExpr) (res ir.Node) {
1139         if base.EnableTrace && base.Flag.LowerT {
1140                 defer tracePrint("typecheckMethodExpr", n)(&res)
1141         }
1142
1143         t := n.X.Type()
1144
1145         // Compute the method set for t.
1146         var ms *types.Fields
1147         if t.IsInterface() {
1148                 ms = t.AllMethods()
1149         } else {
1150                 mt := types.ReceiverBaseType(t)
1151                 if mt == nil {
1152                         base.Errorf("%v undefined (type %v has no method %v)", n, t, n.Sel)
1153                         n.SetType(nil)
1154                         return n
1155                 }
1156                 CalcMethods(mt)
1157                 ms = mt.AllMethods()
1158
1159                 // The method expression T.m requires a wrapper when T
1160                 // is different from m's declared receiver type. We
1161                 // normally generate these wrappers while writing out
1162                 // runtime type descriptors, which is always done for
1163                 // types declared at package scope. However, we need
1164                 // to make sure to generate wrappers for anonymous
1165                 // receiver types too.
1166                 if mt.Sym() == nil {
1167                         NeedRuntimeType(t)
1168                 }
1169         }
1170
1171         s := n.Sel
1172         m := Lookdot1(n, s, t, ms, 0)
1173         if m == nil {
1174                 if Lookdot1(n, s, t, ms, 1) != nil {
1175                         base.Errorf("%v undefined (cannot refer to unexported method %v)", n, s)
1176                 } else if _, ambig := dotpath(s, t, nil, false); ambig {
1177                         base.Errorf("%v undefined (ambiguous selector)", n) // method or field
1178                 } else {
1179                         base.Errorf("%v undefined (type %v has no method %v)", n, t, s)
1180                 }
1181                 n.SetType(nil)
1182                 return n
1183         }
1184
1185         if !types.IsMethodApplicable(t, m) {
1186                 base.Errorf("invalid method expression %v (needs pointer receiver: (*%v).%S)", n, t, s)
1187                 n.SetType(nil)
1188                 return n
1189         }
1190
1191         n.SetOp(ir.OMETHEXPR)
1192         n.Selection = m
1193         n.SetType(NewMethodType(m.Type, n.X.Type()))
1194         return n
1195 }
1196
1197 func derefall(t *types.Type) *types.Type {
1198         for t != nil && t.IsPtr() {
1199                 t = t.Elem()
1200         }
1201         return t
1202 }
1203
1204 // Lookdot looks up field or method n.Sel in the type t and returns the matching
1205 // field. It transforms the op of node n to ODOTINTER or ODOTMETH, if appropriate.
1206 // It also may add a StarExpr node to n.X as needed for access to non-pointer
1207 // methods. If dostrcmp is 0, it matches the field/method with the exact symbol
1208 // as n.Sel (appropriate for exported fields). If dostrcmp is 1, it matches by name
1209 // exactly. If dostrcmp is 2, it matches names with case folding.
1210 func Lookdot(n *ir.SelectorExpr, t *types.Type, dostrcmp int) *types.Field {
1211         s := n.Sel
1212
1213         types.CalcSize(t)
1214         var f1 *types.Field
1215         if t.IsStruct() {
1216                 f1 = Lookdot1(n, s, t, t.Fields(), dostrcmp)
1217         } else if t.IsInterface() {
1218                 f1 = Lookdot1(n, s, t, t.AllMethods(), dostrcmp)
1219         }
1220
1221         var f2 *types.Field
1222         if n.X.Type() == t || n.X.Type().Sym() == nil {
1223                 mt := types.ReceiverBaseType(t)
1224                 if mt != nil {
1225                         f2 = Lookdot1(n, s, mt, mt.Methods(), dostrcmp)
1226                 }
1227         }
1228
1229         if f1 != nil {
1230                 if dostrcmp > 1 || f1.Broke() {
1231                         // Already in the process of diagnosing an error.
1232                         return f1
1233                 }
1234                 if f2 != nil {
1235                         base.Errorf("%v is both field and method", n.Sel)
1236                 }
1237                 if f1.Offset == types.BADWIDTH {
1238                         base.Fatalf("Lookdot badwidth t=%v, f1=%v@%p", t, f1, f1)
1239                 }
1240                 n.Selection = f1
1241                 n.SetType(f1.Type)
1242                 if t.IsInterface() {
1243                         if n.X.Type().IsPtr() {
1244                                 star := ir.NewStarExpr(base.Pos, n.X)
1245                                 star.SetImplicit(true)
1246                                 n.X = Expr(star)
1247                         }
1248
1249                         n.SetOp(ir.ODOTINTER)
1250                 }
1251                 return f1
1252         }
1253
1254         if f2 != nil {
1255                 if dostrcmp > 1 {
1256                         // Already in the process of diagnosing an error.
1257                         return f2
1258                 }
1259                 orig := n.X
1260                 tt := n.X.Type()
1261                 types.CalcSize(tt)
1262                 rcvr := f2.Type.Recv().Type
1263                 if !types.Identical(rcvr, tt) {
1264                         if rcvr.IsPtr() && types.Identical(rcvr.Elem(), tt) {
1265                                 checklvalue(n.X, "call pointer method on")
1266                                 addr := NodAddr(n.X)
1267                                 addr.SetImplicit(true)
1268                                 n.X = typecheck(addr, ctxType|ctxExpr)
1269                         } else if tt.IsPtr() && (!rcvr.IsPtr() || rcvr.IsPtr() && rcvr.Elem().NotInHeap()) && types.Identical(tt.Elem(), rcvr) {
1270                                 star := ir.NewStarExpr(base.Pos, n.X)
1271                                 star.SetImplicit(true)
1272                                 n.X = typecheck(star, ctxType|ctxExpr)
1273                         } else if tt.IsPtr() && tt.Elem().IsPtr() && types.Identical(derefall(tt), derefall(rcvr)) {
1274                                 base.Errorf("calling method %v with receiver %L requires explicit dereference", n.Sel, n.X)
1275                                 for tt.IsPtr() {
1276                                         // Stop one level early for method with pointer receiver.
1277                                         if rcvr.IsPtr() && !tt.Elem().IsPtr() {
1278                                                 break
1279                                         }
1280                                         star := ir.NewStarExpr(base.Pos, n.X)
1281                                         star.SetImplicit(true)
1282                                         n.X = typecheck(star, ctxType|ctxExpr)
1283                                         tt = tt.Elem()
1284                                 }
1285                         } else {
1286                                 base.Fatalf("method mismatch: %v for %v", rcvr, tt)
1287                         }
1288                 }
1289
1290                 // Check that we haven't implicitly dereferenced any defined pointer types.
1291                 for x := n.X; ; {
1292                         var inner ir.Node
1293                         implicit := false
1294                         switch x := x.(type) {
1295                         case *ir.AddrExpr:
1296                                 inner, implicit = x.X, x.Implicit()
1297                         case *ir.SelectorExpr:
1298                                 inner, implicit = x.X, x.Implicit()
1299                         case *ir.StarExpr:
1300                                 inner, implicit = x.X, x.Implicit()
1301                         }
1302                         if !implicit {
1303                                 break
1304                         }
1305                         if inner.Type().Sym() != nil && (x.Op() == ir.ODEREF || x.Op() == ir.ODOTPTR) {
1306                                 // Found an implicit dereference of a defined pointer type.
1307                                 // Restore n.X for better error message.
1308                                 n.X = orig
1309                                 return nil
1310                         }
1311                         x = inner
1312                 }
1313
1314                 n.Selection = f2
1315                 n.SetType(f2.Type)
1316                 n.SetOp(ir.ODOTMETH)
1317
1318                 return f2
1319         }
1320
1321         return nil
1322 }
1323
1324 func nokeys(l ir.Nodes) bool {
1325         for _, n := range l {
1326                 if n.Op() == ir.OKEY || n.Op() == ir.OSTRUCTKEY {
1327                         return false
1328                 }
1329         }
1330         return true
1331 }
1332
1333 func hasddd(t *types.Type) bool {
1334         for _, tl := range t.Fields().Slice() {
1335                 if tl.IsDDD() {
1336                         return true
1337                 }
1338         }
1339
1340         return false
1341 }
1342
1343 // typecheck assignment: type list = expression list
1344 func typecheckaste(op ir.Op, call ir.Node, isddd bool, tstruct *types.Type, nl ir.Nodes, desc func() string) {
1345         var t *types.Type
1346         var i int
1347
1348         lno := base.Pos
1349         defer func() { base.Pos = lno }()
1350
1351         if tstruct.Broke() {
1352                 return
1353         }
1354
1355         var n ir.Node
1356         if len(nl) == 1 {
1357                 n = nl[0]
1358         }
1359
1360         n1 := tstruct.NumFields()
1361         n2 := len(nl)
1362         if !hasddd(tstruct) {
1363                 if isddd {
1364                         goto invalidddd
1365                 }
1366                 if n2 > n1 {
1367                         goto toomany
1368                 }
1369                 if n2 < n1 {
1370                         goto notenough
1371                 }
1372         } else {
1373                 if !isddd {
1374                         if n2 < n1-1 {
1375                                 goto notenough
1376                         }
1377                 } else {
1378                         if n2 > n1 {
1379                                 goto toomany
1380                         }
1381                         if n2 < n1 {
1382                                 goto notenough
1383                         }
1384                 }
1385         }
1386
1387         i = 0
1388         for _, tl := range tstruct.Fields().Slice() {
1389                 t = tl.Type
1390                 if tl.IsDDD() {
1391                         if isddd {
1392                                 if i >= len(nl) {
1393                                         goto notenough
1394                                 }
1395                                 if len(nl)-i > 1 {
1396                                         goto toomany
1397                                 }
1398                                 n = nl[i]
1399                                 ir.SetPos(n)
1400                                 if n.Type() != nil {
1401                                         nl[i] = assignconvfn(n, t, desc)
1402                                 }
1403                                 return
1404                         }
1405
1406                         // TODO(mdempsky): Make into ... call with implicit slice.
1407                         for ; i < len(nl); i++ {
1408                                 n = nl[i]
1409                                 ir.SetPos(n)
1410                                 if n.Type() != nil {
1411                                         nl[i] = assignconvfn(n, t.Elem(), desc)
1412                                 }
1413                         }
1414                         return
1415                 }
1416
1417                 if i >= len(nl) {
1418                         goto notenough
1419                 }
1420                 n = nl[i]
1421                 ir.SetPos(n)
1422                 if n.Type() != nil {
1423                         nl[i] = assignconvfn(n, t, desc)
1424                 }
1425                 i++
1426         }
1427
1428         if i < len(nl) {
1429                 goto toomany
1430         }
1431
1432 invalidddd:
1433         if isddd {
1434                 if call != nil {
1435                         base.Errorf("invalid use of ... in call to %v", call)
1436                 } else {
1437                         base.Errorf("invalid use of ... in %v", op)
1438                 }
1439         }
1440         return
1441
1442 notenough:
1443         if n == nil || (!n.Diag() && n.Type() != nil) {
1444                 details := errorDetails(nl, tstruct, isddd)
1445                 if call != nil {
1446                         // call is the expression being called, not the overall call.
1447                         // Method expressions have the form T.M, and the compiler has
1448                         // rewritten those to ONAME nodes but left T in Left.
1449                         if call.Op() == ir.OMETHEXPR {
1450                                 call := call.(*ir.SelectorExpr)
1451                                 base.Errorf("not enough arguments in call to method expression %v%s", call, details)
1452                         } else {
1453                                 base.Errorf("not enough arguments in call to %v%s", call, details)
1454                         }
1455                 } else {
1456                         base.Errorf("not enough arguments to %v%s", op, details)
1457                 }
1458                 if n != nil {
1459                         n.SetDiag(true)
1460                 }
1461         }
1462         return
1463
1464 toomany:
1465         details := errorDetails(nl, tstruct, isddd)
1466         if call != nil {
1467                 base.Errorf("too many arguments in call to %v%s", call, details)
1468         } else {
1469                 base.Errorf("too many arguments to %v%s", op, details)
1470         }
1471 }
1472
1473 func errorDetails(nl ir.Nodes, tstruct *types.Type, isddd bool) string {
1474         // Suppress any return message signatures if:
1475         //
1476         // (1) We don't know any type at a call site (see #19012).
1477         // (2) Any node has an unknown type.
1478         // (3) Invalid type for variadic parameter (see #46957).
1479         if tstruct == nil {
1480                 return "" // case 1
1481         }
1482
1483         if isddd && !nl[len(nl)-1].Type().IsSlice() {
1484                 return "" // case 3
1485         }
1486
1487         for _, n := range nl {
1488                 if n.Type() == nil {
1489                         return "" // case 2
1490                 }
1491         }
1492         return fmt.Sprintf("\n\thave %s\n\twant %v", fmtSignature(nl, isddd), tstruct)
1493 }
1494
1495 // sigrepr is a type's representation to the outside world,
1496 // in string representations of return signatures
1497 // e.g in error messages about wrong arguments to return.
1498 func sigrepr(t *types.Type, isddd bool) string {
1499         switch t {
1500         case types.UntypedString:
1501                 return "string"
1502         case types.UntypedBool:
1503                 return "bool"
1504         }
1505
1506         if t.Kind() == types.TIDEAL {
1507                 // "untyped number" is not commonly used
1508                 // outside of the compiler, so let's use "number".
1509                 // TODO(mdempsky): Revisit this.
1510                 return "number"
1511         }
1512
1513         // Turn []T... argument to ...T for clearer error message.
1514         if isddd {
1515                 if !t.IsSlice() {
1516                         base.Fatalf("bad type for ... argument: %v", t)
1517                 }
1518                 return "..." + t.Elem().String()
1519         }
1520         return t.String()
1521 }
1522
1523 // sigerr returns the signature of the types at the call or return.
1524 func fmtSignature(nl ir.Nodes, isddd bool) string {
1525         if len(nl) < 1 {
1526                 return "()"
1527         }
1528
1529         var typeStrings []string
1530         for i, n := range nl {
1531                 isdddArg := isddd && i == len(nl)-1
1532                 typeStrings = append(typeStrings, sigrepr(n.Type(), isdddArg))
1533         }
1534
1535         return fmt.Sprintf("(%s)", strings.Join(typeStrings, ", "))
1536 }
1537
1538 // type check composite
1539 func fielddup(name string, hash map[string]bool) {
1540         if hash[name] {
1541                 base.Errorf("duplicate field name in struct literal: %s", name)
1542                 return
1543         }
1544         hash[name] = true
1545 }
1546
1547 // iscomptype reports whether type t is a composite literal type.
1548 func iscomptype(t *types.Type) bool {
1549         switch t.Kind() {
1550         case types.TARRAY, types.TSLICE, types.TSTRUCT, types.TMAP:
1551                 return true
1552         default:
1553                 return false
1554         }
1555 }
1556
1557 // pushtype adds elided type information for composite literals if
1558 // appropriate, and returns the resulting expression.
1559 func pushtype(nn ir.Node, t *types.Type) ir.Node {
1560         if nn == nil || nn.Op() != ir.OCOMPLIT {
1561                 return nn
1562         }
1563         n := nn.(*ir.CompLitExpr)
1564         if n.Ntype != nil {
1565                 return n
1566         }
1567
1568         switch {
1569         case iscomptype(t):
1570                 // For T, return T{...}.
1571                 n.Ntype = ir.TypeNode(t)
1572
1573         case t.IsPtr() && iscomptype(t.Elem()):
1574                 // For *T, return &T{...}.
1575                 n.Ntype = ir.TypeNode(t.Elem())
1576
1577                 addr := NodAddrAt(n.Pos(), n)
1578                 addr.SetImplicit(true)
1579                 return addr
1580         }
1581         return n
1582 }
1583
1584 // typecheckarraylit type-checks a sequence of slice/array literal elements.
1585 func typecheckarraylit(elemType *types.Type, bound int64, elts []ir.Node, ctx string) int64 {
1586         // If there are key/value pairs, create a map to keep seen
1587         // keys so we can check for duplicate indices.
1588         var indices map[int64]bool
1589         for _, elt := range elts {
1590                 if elt.Op() == ir.OKEY {
1591                         indices = make(map[int64]bool)
1592                         break
1593                 }
1594         }
1595
1596         var key, length int64
1597         for i, elt := range elts {
1598                 ir.SetPos(elt)
1599                 r := elts[i]
1600                 var kv *ir.KeyExpr
1601                 if elt.Op() == ir.OKEY {
1602                         elt := elt.(*ir.KeyExpr)
1603                         elt.Key = Expr(elt.Key)
1604                         key = IndexConst(elt.Key)
1605                         if key < 0 {
1606                                 if !elt.Key.Diag() {
1607                                         if key == -2 {
1608                                                 base.Errorf("index too large")
1609                                         } else {
1610                                                 base.Errorf("index must be non-negative integer constant")
1611                                         }
1612                                         elt.Key.SetDiag(true)
1613                                 }
1614                                 key = -(1 << 30) // stay negative for a while
1615                         }
1616                         kv = elt
1617                         r = elt.Value
1618                 }
1619
1620                 r = pushtype(r, elemType)
1621                 r = Expr(r)
1622                 r = AssignConv(r, elemType, ctx)
1623                 if kv != nil {
1624                         kv.Value = r
1625                 } else {
1626                         elts[i] = r
1627                 }
1628
1629                 if key >= 0 {
1630                         if indices != nil {
1631                                 if indices[key] {
1632                                         base.Errorf("duplicate index in %s: %d", ctx, key)
1633                                 } else {
1634                                         indices[key] = true
1635                                 }
1636                         }
1637
1638                         if bound >= 0 && key >= bound {
1639                                 base.Errorf("array index %d out of bounds [0:%d]", key, bound)
1640                                 bound = -1
1641                         }
1642                 }
1643
1644                 key++
1645                 if key > length {
1646                         length = key
1647                 }
1648         }
1649
1650         return length
1651 }
1652
1653 // visible reports whether sym is exported or locally defined.
1654 func visible(sym *types.Sym) bool {
1655         return sym != nil && (types.IsExported(sym.Name) || sym.Pkg == types.LocalPkg)
1656 }
1657
1658 // nonexported reports whether sym is an unexported field.
1659 func nonexported(sym *types.Sym) bool {
1660         return sym != nil && !types.IsExported(sym.Name)
1661 }
1662
1663 func checklvalue(n ir.Node, verb string) {
1664         if !ir.IsAddressable(n) {
1665                 base.Errorf("cannot %s %v", verb, n)
1666         }
1667 }
1668
1669 func checkassign(stmt ir.Node, n ir.Node) {
1670         // have already complained about n being invalid
1671         if n.Type() == nil {
1672                 if base.Errors() == 0 {
1673                         base.Fatalf("expected an error about %v", n)
1674                 }
1675                 return
1676         }
1677
1678         if ir.IsAddressable(n) {
1679                 return
1680         }
1681         if n.Op() == ir.OINDEXMAP {
1682                 n := n.(*ir.IndexExpr)
1683                 n.Assigned = true
1684                 return
1685         }
1686
1687         defer n.SetType(nil)
1688         if n.Diag() {
1689                 return
1690         }
1691         switch {
1692         case n.Op() == ir.ODOT && n.(*ir.SelectorExpr).X.Op() == ir.OINDEXMAP:
1693                 base.Errorf("cannot assign to struct field %v in map", n)
1694         case (n.Op() == ir.OINDEX && n.(*ir.IndexExpr).X.Type().IsString()) || n.Op() == ir.OSLICESTR:
1695                 base.Errorf("cannot assign to %v (strings are immutable)", n)
1696         case n.Op() == ir.OLITERAL && n.Sym() != nil && ir.IsConstNode(n):
1697                 base.Errorf("cannot assign to %v (declared const)", n)
1698         default:
1699                 base.Errorf("cannot assign to %v", n)
1700         }
1701 }
1702
1703 func checkassignto(src *types.Type, dst ir.Node) {
1704         // TODO(mdempsky): Handle all untyped types correctly.
1705         if src == types.UntypedBool && dst.Type().IsBoolean() {
1706                 return
1707         }
1708
1709         if op, why := Assignop(src, dst.Type()); op == ir.OXXX {
1710                 base.Errorf("cannot assign %v to %L in multiple assignment%s", src, dst, why)
1711                 return
1712         }
1713 }
1714
1715 // The result of stringtoruneslit MUST be assigned back to n, e.g.
1716 //      n.Left = stringtoruneslit(n.Left)
1717 func stringtoruneslit(n *ir.ConvExpr) ir.Node {
1718         if n.X.Op() != ir.OLITERAL || n.X.Val().Kind() != constant.String {
1719                 base.Fatalf("stringtoarraylit %v", n)
1720         }
1721
1722         var l []ir.Node
1723         i := 0
1724         for _, r := range ir.StringVal(n.X) {
1725                 l = append(l, ir.NewKeyExpr(base.Pos, ir.NewInt(int64(i)), ir.NewInt(int64(r))))
1726                 i++
1727         }
1728
1729         nn := ir.NewCompLitExpr(base.Pos, ir.OCOMPLIT, ir.TypeNode(n.Type()), nil)
1730         nn.List = l
1731         return Expr(nn)
1732 }
1733
1734 var mapqueue []*ir.MapType
1735
1736 func CheckMapKeys() {
1737         for _, n := range mapqueue {
1738                 k := n.Type().MapType().Key
1739                 if !k.Broke() && !types.IsComparable(k) {
1740                         base.ErrorfAt(n.Pos(), "invalid map key type %v", k)
1741                 }
1742         }
1743         mapqueue = nil
1744 }
1745
1746 // TypeGen tracks the number of function-scoped defined types that
1747 // have been declared. It's used to generate unique linker symbols for
1748 // their runtime type descriptors.
1749 var TypeGen int32
1750
1751 func typecheckdeftype(n *ir.Name) {
1752         if base.EnableTrace && base.Flag.LowerT {
1753                 defer tracePrint("typecheckdeftype", n)(nil)
1754         }
1755
1756         t := types.NewNamed(n)
1757         if n.Curfn != nil {
1758                 TypeGen++
1759                 t.Vargen = TypeGen
1760         }
1761
1762         if n.Pragma()&ir.NotInHeap != 0 {
1763                 t.SetNotInHeap(true)
1764         }
1765
1766         n.SetType(t)
1767         n.SetTypecheck(1)
1768         n.SetWalkdef(1)
1769
1770         types.DeferCheckSize()
1771         errorsBefore := base.Errors()
1772         n.Ntype = typecheckNtype(n.Ntype)
1773         if underlying := n.Ntype.Type(); underlying != nil {
1774                 t.SetUnderlying(underlying)
1775         } else {
1776                 n.SetDiag(true)
1777                 n.SetType(nil)
1778         }
1779         if t.Kind() == types.TFORW && base.Errors() > errorsBefore {
1780                 // Something went wrong during type-checking,
1781                 // but it was reported. Silence future errors.
1782                 t.SetBroke(true)
1783         }
1784         types.ResumeCheckSize()
1785 }
1786
1787 func typecheckdef(n *ir.Name) {
1788         if base.EnableTrace && base.Flag.LowerT {
1789                 defer tracePrint("typecheckdef", n)(nil)
1790         }
1791
1792         if n.Walkdef() == 1 {
1793                 return
1794         }
1795
1796         if n.Type() != nil { // builtin
1797                 // Mark as Walkdef so that if n.SetType(nil) is called later, we
1798                 // won't try walking again.
1799                 if got := n.Walkdef(); got != 0 {
1800                         base.Fatalf("unexpected walkdef: %v", got)
1801                 }
1802                 n.SetWalkdef(1)
1803                 return
1804         }
1805
1806         lno := ir.SetPos(n)
1807         typecheckdefstack = append(typecheckdefstack, n)
1808         if n.Walkdef() == 2 {
1809                 base.FlushErrors()
1810                 fmt.Printf("typecheckdef loop:")
1811                 for i := len(typecheckdefstack) - 1; i >= 0; i-- {
1812                         n := typecheckdefstack[i]
1813                         fmt.Printf(" %v", n.Sym())
1814                 }
1815                 fmt.Printf("\n")
1816                 base.Fatalf("typecheckdef loop")
1817         }
1818
1819         n.SetWalkdef(2)
1820
1821         switch n.Op() {
1822         default:
1823                 base.Fatalf("typecheckdef %v", n.Op())
1824
1825         case ir.OLITERAL:
1826                 if n.Ntype != nil {
1827                         n.Ntype = typecheckNtype(n.Ntype)
1828                         n.SetType(n.Ntype.Type())
1829                         n.Ntype = nil
1830                         if n.Type() == nil {
1831                                 n.SetDiag(true)
1832                                 goto ret
1833                         }
1834                 }
1835
1836                 e := n.Defn
1837                 n.Defn = nil
1838                 if e == nil {
1839                         ir.Dump("typecheckdef nil defn", n)
1840                         base.ErrorfAt(n.Pos(), "xxx")
1841                 }
1842
1843                 e = Expr(e)
1844                 if e.Type() == nil {
1845                         goto ret
1846                 }
1847                 if !ir.IsConstNode(e) {
1848                         if !e.Diag() {
1849                                 if e.Op() == ir.ONIL {
1850                                         base.ErrorfAt(n.Pos(), "const initializer cannot be nil")
1851                                 } else {
1852                                         base.ErrorfAt(n.Pos(), "const initializer %v is not a constant", e)
1853                                 }
1854                                 e.SetDiag(true)
1855                         }
1856                         goto ret
1857                 }
1858
1859                 t := n.Type()
1860                 if t != nil {
1861                         if !ir.OKForConst[t.Kind()] {
1862                                 base.ErrorfAt(n.Pos(), "invalid constant type %v", t)
1863                                 goto ret
1864                         }
1865
1866                         if !e.Type().IsUntyped() && !types.Identical(t, e.Type()) {
1867                                 base.ErrorfAt(n.Pos(), "cannot use %L as type %v in const initializer", e, t)
1868                                 goto ret
1869                         }
1870
1871                         e = convlit(e, t)
1872                 }
1873
1874                 n.SetType(e.Type())
1875                 if n.Type() != nil {
1876                         n.SetVal(e.Val())
1877                 }
1878
1879         case ir.ONAME:
1880                 if n.Ntype != nil {
1881                         n.Ntype = typecheckNtype(n.Ntype)
1882                         n.SetType(n.Ntype.Type())
1883                         if n.Type() == nil {
1884                                 n.SetDiag(true)
1885                                 goto ret
1886                         }
1887                 }
1888
1889                 if n.Type() != nil {
1890                         break
1891                 }
1892                 if n.Defn == nil {
1893                         if n.BuiltinOp != 0 { // like OPRINTN
1894                                 break
1895                         }
1896                         if base.Errors() > 0 {
1897                                 // Can have undefined variables in x := foo
1898                                 // that make x have an n.name.Defn == nil.
1899                                 // If there are other errors anyway, don't
1900                                 // bother adding to the noise.
1901                                 break
1902                         }
1903
1904                         base.Fatalf("var without type, init: %v", n.Sym())
1905                 }
1906
1907                 if n.Defn.Op() == ir.ONAME {
1908                         n.Defn = Expr(n.Defn)
1909                         n.SetType(n.Defn.Type())
1910                         break
1911                 }
1912
1913                 n.Defn = Stmt(n.Defn) // fills in n.Type
1914
1915         case ir.OTYPE:
1916                 if n.Alias() {
1917                         // Type alias declaration: Simply use the rhs type - no need
1918                         // to create a new type.
1919                         // If we have a syntax error, name.Ntype may be nil.
1920                         if n.Ntype != nil {
1921                                 n.Ntype = typecheckNtype(n.Ntype)
1922                                 n.SetType(n.Ntype.Type())
1923                                 if n.Type() == nil {
1924                                         n.SetDiag(true)
1925                                         goto ret
1926                                 }
1927                         }
1928                         break
1929                 }
1930
1931                 // regular type declaration
1932                 typecheckdeftype(n)
1933         }
1934
1935 ret:
1936         if n.Op() != ir.OLITERAL && n.Type() != nil && n.Type().IsUntyped() {
1937                 base.Fatalf("got %v for %v", n.Type(), n)
1938         }
1939         last := len(typecheckdefstack) - 1
1940         if typecheckdefstack[last] != n {
1941                 base.Fatalf("typecheckdefstack mismatch")
1942         }
1943         typecheckdefstack[last] = nil
1944         typecheckdefstack = typecheckdefstack[:last]
1945
1946         base.Pos = lno
1947         n.SetWalkdef(1)
1948 }
1949
1950 func checkmake(t *types.Type, arg string, np *ir.Node) bool {
1951         n := *np
1952         if !n.Type().IsInteger() && n.Type().Kind() != types.TIDEAL {
1953                 base.Errorf("non-integer %s argument in make(%v) - %v", arg, t, n.Type())
1954                 return false
1955         }
1956
1957         // Do range checks for constants before DefaultLit
1958         // to avoid redundant "constant NNN overflows int" errors.
1959         if n.Op() == ir.OLITERAL {
1960                 v := toint(n.Val())
1961                 if constant.Sign(v) < 0 {
1962                         base.Errorf("negative %s argument in make(%v)", arg, t)
1963                         return false
1964                 }
1965                 if ir.ConstOverflow(v, types.Types[types.TINT]) {
1966                         base.Errorf("%s argument too large in make(%v)", arg, t)
1967                         return false
1968                 }
1969         }
1970
1971         // DefaultLit is necessary for non-constants too: n might be 1.1<<k.
1972         // TODO(gri) The length argument requirements for (array/slice) make
1973         // are the same as for index expressions. Factor the code better;
1974         // for instance, indexlit might be called here and incorporate some
1975         // of the bounds checks done for make.
1976         n = DefaultLit(n, types.Types[types.TINT])
1977         *np = n
1978
1979         return true
1980 }
1981
1982 // checkunsafeslice is like checkmake but for unsafe.Slice.
1983 func checkunsafeslice(np *ir.Node) bool {
1984         n := *np
1985         if !n.Type().IsInteger() && n.Type().Kind() != types.TIDEAL {
1986                 base.Errorf("non-integer len argument in unsafe.Slice - %v", n.Type())
1987                 return false
1988         }
1989
1990         // Do range checks for constants before DefaultLit
1991         // to avoid redundant "constant NNN overflows int" errors.
1992         if n.Op() == ir.OLITERAL {
1993                 v := toint(n.Val())
1994                 if constant.Sign(v) < 0 {
1995                         base.Errorf("negative len argument in unsafe.Slice")
1996                         return false
1997                 }
1998                 if ir.ConstOverflow(v, types.Types[types.TINT]) {
1999                         base.Errorf("len argument too large in unsafe.Slice")
2000                         return false
2001                 }
2002         }
2003
2004         // DefaultLit is necessary for non-constants too: n might be 1.1<<k.
2005         n = DefaultLit(n, types.Types[types.TINT])
2006         *np = n
2007
2008         return true
2009 }
2010
2011 // markBreak marks control statements containing break statements with SetHasBreak(true).
2012 func markBreak(fn *ir.Func) {
2013         var labels map[*types.Sym]ir.Node
2014         var implicit ir.Node
2015
2016         var mark func(ir.Node) bool
2017         mark = func(n ir.Node) bool {
2018                 switch n.Op() {
2019                 default:
2020                         ir.DoChildren(n, mark)
2021
2022                 case ir.OBREAK:
2023                         n := n.(*ir.BranchStmt)
2024                         if n.Label == nil {
2025                                 setHasBreak(implicit)
2026                         } else {
2027                                 setHasBreak(labels[n.Label])
2028                         }
2029
2030                 case ir.OFOR, ir.OFORUNTIL, ir.OSWITCH, ir.OSELECT, ir.ORANGE:
2031                         old := implicit
2032                         implicit = n
2033                         var sym *types.Sym
2034                         switch n := n.(type) {
2035                         case *ir.ForStmt:
2036                                 sym = n.Label
2037                         case *ir.RangeStmt:
2038                                 sym = n.Label
2039                         case *ir.SelectStmt:
2040                                 sym = n.Label
2041                         case *ir.SwitchStmt:
2042                                 sym = n.Label
2043                         }
2044                         if sym != nil {
2045                                 if labels == nil {
2046                                         // Map creation delayed until we need it - most functions don't.
2047                                         labels = make(map[*types.Sym]ir.Node)
2048                                 }
2049                                 labels[sym] = n
2050                         }
2051                         ir.DoChildren(n, mark)
2052                         if sym != nil {
2053                                 delete(labels, sym)
2054                         }
2055                         implicit = old
2056                 }
2057                 return false
2058         }
2059
2060         mark(fn)
2061 }
2062
2063 func controlLabel(n ir.Node) *types.Sym {
2064         switch n := n.(type) {
2065         default:
2066                 base.Fatalf("controlLabel %+v", n.Op())
2067                 return nil
2068         case *ir.ForStmt:
2069                 return n.Label
2070         case *ir.RangeStmt:
2071                 return n.Label
2072         case *ir.SelectStmt:
2073                 return n.Label
2074         case *ir.SwitchStmt:
2075                 return n.Label
2076         }
2077 }
2078
2079 func setHasBreak(n ir.Node) {
2080         switch n := n.(type) {
2081         default:
2082                 base.Fatalf("setHasBreak %+v", n.Op())
2083         case nil:
2084                 // ignore
2085         case *ir.ForStmt:
2086                 n.HasBreak = true
2087         case *ir.RangeStmt:
2088                 n.HasBreak = true
2089         case *ir.SelectStmt:
2090                 n.HasBreak = true
2091         case *ir.SwitchStmt:
2092                 n.HasBreak = true
2093         }
2094 }
2095
2096 // isTermNodes reports whether the Nodes list ends with a terminating statement.
2097 func isTermNodes(l ir.Nodes) bool {
2098         s := l
2099         c := len(s)
2100         if c == 0 {
2101                 return false
2102         }
2103         return isTermNode(s[c-1])
2104 }
2105
2106 // isTermNode reports whether the node n, the last one in a
2107 // statement list, is a terminating statement.
2108 func isTermNode(n ir.Node) bool {
2109         switch n.Op() {
2110         // NOTE: OLABEL is treated as a separate statement,
2111         // not a separate prefix, so skipping to the last statement
2112         // in the block handles the labeled statement case by
2113         // skipping over the label. No case OLABEL here.
2114
2115         case ir.OBLOCK:
2116                 n := n.(*ir.BlockStmt)
2117                 return isTermNodes(n.List)
2118
2119         case ir.OGOTO, ir.ORETURN, ir.OTAILCALL, ir.OPANIC, ir.OFALL:
2120                 return true
2121
2122         case ir.OFOR, ir.OFORUNTIL:
2123                 n := n.(*ir.ForStmt)
2124                 if n.Cond != nil {
2125                         return false
2126                 }
2127                 if n.HasBreak {
2128                         return false
2129                 }
2130                 return true
2131
2132         case ir.OIF:
2133                 n := n.(*ir.IfStmt)
2134                 return isTermNodes(n.Body) && isTermNodes(n.Else)
2135
2136         case ir.OSWITCH:
2137                 n := n.(*ir.SwitchStmt)
2138                 if n.HasBreak {
2139                         return false
2140                 }
2141                 def := false
2142                 for _, cas := range n.Cases {
2143                         if !isTermNodes(cas.Body) {
2144                                 return false
2145                         }
2146                         if len(cas.List) == 0 { // default
2147                                 def = true
2148                         }
2149                 }
2150                 return def
2151
2152         case ir.OSELECT:
2153                 n := n.(*ir.SelectStmt)
2154                 if n.HasBreak {
2155                         return false
2156                 }
2157                 for _, cas := range n.Cases {
2158                         if !isTermNodes(cas.Body) {
2159                                 return false
2160                         }
2161                 }
2162                 return true
2163         }
2164
2165         return false
2166 }
2167
2168 // CheckUnused checks for any declared variables that weren't used.
2169 func CheckUnused(fn *ir.Func) {
2170         // Only report unused variables if we haven't seen any type-checking
2171         // errors yet.
2172         if base.Errors() != 0 {
2173                 return
2174         }
2175
2176         // Propagate the used flag for typeswitch variables up to the NONAME in its definition.
2177         for _, ln := range fn.Dcl {
2178                 if ln.Op() == ir.ONAME && ln.Class == ir.PAUTO && ln.Used() {
2179                         if guard, ok := ln.Defn.(*ir.TypeSwitchGuard); ok {
2180                                 guard.Used = true
2181                         }
2182                 }
2183         }
2184
2185         for _, ln := range fn.Dcl {
2186                 if ln.Op() != ir.ONAME || ln.Class != ir.PAUTO || ln.Used() {
2187                         continue
2188                 }
2189                 if defn, ok := ln.Defn.(*ir.TypeSwitchGuard); ok {
2190                         if defn.Used {
2191                                 continue
2192                         }
2193                         base.ErrorfAt(defn.Tag.Pos(), "%v declared but not used", ln.Sym())
2194                         defn.Used = true // suppress repeats
2195                 } else {
2196                         base.ErrorfAt(ln.Pos(), "%v declared but not used", ln.Sym())
2197                 }
2198         }
2199 }
2200
2201 // CheckReturn makes sure that fn terminates appropriately.
2202 func CheckReturn(fn *ir.Func) {
2203         if fn.Type() != nil && fn.Type().NumResults() != 0 && len(fn.Body) != 0 {
2204                 markBreak(fn)
2205                 if !isTermNodes(fn.Body) {
2206                         base.ErrorfAt(fn.Endlineno, "missing return at end of function")
2207                 }
2208         }
2209 }
2210
2211 // getIotaValue returns the current value for "iota",
2212 // or -1 if not within a ConstSpec.
2213 func getIotaValue() int64 {
2214         if i := len(typecheckdefstack); i > 0 {
2215                 if x := typecheckdefstack[i-1]; x.Op() == ir.OLITERAL {
2216                         return x.Iota()
2217                 }
2218         }
2219
2220         if ir.CurFunc != nil && ir.CurFunc.Iota >= 0 {
2221                 return ir.CurFunc.Iota
2222         }
2223
2224         return -1
2225 }
2226
2227 // curpkg returns the current package, based on Curfn.
2228 func curpkg() *types.Pkg {
2229         fn := ir.CurFunc
2230         if fn == nil {
2231                 // Initialization expressions for package-scope variables.
2232                 return types.LocalPkg
2233         }
2234         return fnpkg(fn.Nname)
2235 }
2236
2237 func Conv(n ir.Node, t *types.Type) ir.Node {
2238         if types.Identical(n.Type(), t) {
2239                 return n
2240         }
2241         n = ir.NewConvExpr(base.Pos, ir.OCONV, nil, n)
2242         n.SetType(t)
2243         n = Expr(n)
2244         return n
2245 }
2246
2247 // ConvNop converts node n to type t using the OCONVNOP op
2248 // and typechecks the result with ctxExpr.
2249 func ConvNop(n ir.Node, t *types.Type) ir.Node {
2250         if types.Identical(n.Type(), t) {
2251                 return n
2252         }
2253         n = ir.NewConvExpr(base.Pos, ir.OCONVNOP, nil, n)
2254         n.SetType(t)
2255         n = Expr(n)
2256         return n
2257 }