You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

521 lines
14 KiB

  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ssa
  5. // An optional pass for sanity-checking invariants of the SSA representation.
  6. // Currently it checks CFG invariants but little at the instruction level.
  7. import (
  8. "fmt"
  9. "go/types"
  10. "io"
  11. "os"
  12. "strings"
  13. )
  14. type sanity struct {
  15. reporter io.Writer
  16. fn *Function
  17. block *BasicBlock
  18. instrs map[Instruction]struct{}
  19. insane bool
  20. }
  21. // sanityCheck performs integrity checking of the SSA representation
  22. // of the function fn and returns true if it was valid. Diagnostics
  23. // are written to reporter if non-nil, os.Stderr otherwise. Some
  24. // diagnostics are only warnings and do not imply a negative result.
  25. //
  26. // Sanity-checking is intended to facilitate the debugging of code
  27. // transformation passes.
  28. //
  29. func sanityCheck(fn *Function, reporter io.Writer) bool {
  30. if reporter == nil {
  31. reporter = os.Stderr
  32. }
  33. return (&sanity{reporter: reporter}).checkFunction(fn)
  34. }
  35. // mustSanityCheck is like sanityCheck but panics instead of returning
  36. // a negative result.
  37. //
  38. func mustSanityCheck(fn *Function, reporter io.Writer) {
  39. if !sanityCheck(fn, reporter) {
  40. fn.WriteTo(os.Stderr)
  41. panic("SanityCheck failed")
  42. }
  43. }
  44. func (s *sanity) diagnostic(prefix, format string, args ...interface{}) {
  45. fmt.Fprintf(s.reporter, "%s: function %s", prefix, s.fn)
  46. if s.block != nil {
  47. fmt.Fprintf(s.reporter, ", block %s", s.block)
  48. }
  49. io.WriteString(s.reporter, ": ")
  50. fmt.Fprintf(s.reporter, format, args...)
  51. io.WriteString(s.reporter, "\n")
  52. }
  53. func (s *sanity) errorf(format string, args ...interface{}) {
  54. s.insane = true
  55. s.diagnostic("Error", format, args...)
  56. }
  57. func (s *sanity) warnf(format string, args ...interface{}) {
  58. s.diagnostic("Warning", format, args...)
  59. }
  60. // findDuplicate returns an arbitrary basic block that appeared more
  61. // than once in blocks, or nil if all were unique.
  62. func findDuplicate(blocks []*BasicBlock) *BasicBlock {
  63. if len(blocks) < 2 {
  64. return nil
  65. }
  66. if blocks[0] == blocks[1] {
  67. return blocks[0]
  68. }
  69. // Slow path:
  70. m := make(map[*BasicBlock]bool)
  71. for _, b := range blocks {
  72. if m[b] {
  73. return b
  74. }
  75. m[b] = true
  76. }
  77. return nil
  78. }
  79. func (s *sanity) checkInstr(idx int, instr Instruction) {
  80. switch instr := instr.(type) {
  81. case *If, *Jump, *Return, *Panic:
  82. s.errorf("control flow instruction not at end of block")
  83. case *Phi:
  84. if idx == 0 {
  85. // It suffices to apply this check to just the first phi node.
  86. if dup := findDuplicate(s.block.Preds); dup != nil {
  87. s.errorf("phi node in block with duplicate predecessor %s", dup)
  88. }
  89. } else {
  90. prev := s.block.Instrs[idx-1]
  91. if _, ok := prev.(*Phi); !ok {
  92. s.errorf("Phi instruction follows a non-Phi: %T", prev)
  93. }
  94. }
  95. if ne, np := len(instr.Edges), len(s.block.Preds); ne != np {
  96. s.errorf("phi node has %d edges but %d predecessors", ne, np)
  97. } else {
  98. for i, e := range instr.Edges {
  99. if e == nil {
  100. s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment, i, s.block.Preds[i])
  101. }
  102. }
  103. }
  104. case *Alloc:
  105. if !instr.Heap {
  106. found := false
  107. for _, l := range s.fn.Locals {
  108. if l == instr {
  109. found = true
  110. break
  111. }
  112. }
  113. if !found {
  114. s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr)
  115. }
  116. }
  117. case *BinOp:
  118. case *Call:
  119. case *ChangeInterface:
  120. case *ChangeType:
  121. case *Convert:
  122. if _, ok := instr.X.Type().Underlying().(*types.Basic); !ok {
  123. if _, ok := instr.Type().Underlying().(*types.Basic); !ok {
  124. s.errorf("convert %s -> %s: at least one type must be basic", instr.X.Type(), instr.Type())
  125. }
  126. }
  127. case *Defer:
  128. case *Extract:
  129. case *Field:
  130. case *FieldAddr:
  131. case *Go:
  132. case *Index:
  133. case *IndexAddr:
  134. case *Lookup:
  135. case *MakeChan:
  136. case *MakeClosure:
  137. numFree := len(instr.Fn.(*Function).FreeVars)
  138. numBind := len(instr.Bindings)
  139. if numFree != numBind {
  140. s.errorf("MakeClosure has %d Bindings for function %s with %d free vars",
  141. numBind, instr.Fn, numFree)
  142. }
  143. if recv := instr.Type().(*types.Signature).Recv(); recv != nil {
  144. s.errorf("MakeClosure's type includes receiver %s", recv.Type())
  145. }
  146. case *MakeInterface:
  147. case *MakeMap:
  148. case *MakeSlice:
  149. case *MapUpdate:
  150. case *Next:
  151. case *Range:
  152. case *RunDefers:
  153. case *Select:
  154. case *Send:
  155. case *Slice:
  156. case *Store:
  157. case *TypeAssert:
  158. case *UnOp:
  159. case *DebugRef:
  160. // TODO(adonovan): implement checks.
  161. default:
  162. panic(fmt.Sprintf("Unknown instruction type: %T", instr))
  163. }
  164. if call, ok := instr.(CallInstruction); ok {
  165. if call.Common().Signature() == nil {
  166. s.errorf("nil signature: %s", call)
  167. }
  168. }
  169. // Check that value-defining instructions have valid types
  170. // and a valid referrer list.
  171. if v, ok := instr.(Value); ok {
  172. t := v.Type()
  173. if t == nil {
  174. s.errorf("no type: %s = %s", v.Name(), v)
  175. } else if t == tRangeIter {
  176. // not a proper type; ignore.
  177. } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
  178. s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t)
  179. }
  180. s.checkReferrerList(v)
  181. }
  182. // Untyped constants are legal as instruction Operands(),
  183. // for example:
  184. // _ = "foo"[0]
  185. // or:
  186. // if wordsize==64 {...}
  187. // All other non-Instruction Values can be found via their
  188. // enclosing Function or Package.
  189. }
  190. func (s *sanity) checkFinalInstr(idx int, instr Instruction) {
  191. switch instr := instr.(type) {
  192. case *If:
  193. if nsuccs := len(s.block.Succs); nsuccs != 2 {
  194. s.errorf("If-terminated block has %d successors; expected 2", nsuccs)
  195. return
  196. }
  197. if s.block.Succs[0] == s.block.Succs[1] {
  198. s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0])
  199. return
  200. }
  201. case *Jump:
  202. if nsuccs := len(s.block.Succs); nsuccs != 1 {
  203. s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs)
  204. return
  205. }
  206. case *Return:
  207. if nsuccs := len(s.block.Succs); nsuccs != 0 {
  208. s.errorf("Return-terminated block has %d successors; expected none", nsuccs)
  209. return
  210. }
  211. if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na {
  212. s.errorf("%d-ary return in %d-ary function", na, nf)
  213. }
  214. case *Panic:
  215. if nsuccs := len(s.block.Succs); nsuccs != 0 {
  216. s.errorf("Panic-terminated block has %d successors; expected none", nsuccs)
  217. return
  218. }
  219. default:
  220. s.errorf("non-control flow instruction at end of block")
  221. }
  222. }
  223. func (s *sanity) checkBlock(b *BasicBlock, index int) {
  224. s.block = b
  225. if b.Index != index {
  226. s.errorf("block has incorrect Index %d", b.Index)
  227. }
  228. if b.parent != s.fn {
  229. s.errorf("block has incorrect parent %s", b.parent)
  230. }
  231. // Check all blocks are reachable.
  232. // (The entry block is always implicitly reachable,
  233. // as is the Recover block, if any.)
  234. if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 {
  235. s.warnf("unreachable block")
  236. if b.Instrs == nil {
  237. // Since this block is about to be pruned,
  238. // tolerating transient problems in it
  239. // simplifies other optimizations.
  240. return
  241. }
  242. }
  243. // Check predecessor and successor relations are dual,
  244. // and that all blocks in CFG belong to same function.
  245. for _, a := range b.Preds {
  246. found := false
  247. for _, bb := range a.Succs {
  248. if bb == b {
  249. found = true
  250. break
  251. }
  252. }
  253. if !found {
  254. s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs)
  255. }
  256. if a.parent != s.fn {
  257. s.errorf("predecessor %s belongs to different function %s", a, a.parent)
  258. }
  259. }
  260. for _, c := range b.Succs {
  261. found := false
  262. for _, bb := range c.Preds {
  263. if bb == b {
  264. found = true
  265. break
  266. }
  267. }
  268. if !found {
  269. s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds)
  270. }
  271. if c.parent != s.fn {
  272. s.errorf("successor %s belongs to different function %s", c, c.parent)
  273. }
  274. }
  275. // Check each instruction is sane.
  276. n := len(b.Instrs)
  277. if n == 0 {
  278. s.errorf("basic block contains no instructions")
  279. }
  280. var rands [10]*Value // reuse storage
  281. for j, instr := range b.Instrs {
  282. if instr == nil {
  283. s.errorf("nil instruction at index %d", j)
  284. continue
  285. }
  286. if b2 := instr.Block(); b2 == nil {
  287. s.errorf("nil Block() for instruction at index %d", j)
  288. continue
  289. } else if b2 != b {
  290. s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j)
  291. continue
  292. }
  293. if j < n-1 {
  294. s.checkInstr(j, instr)
  295. } else {
  296. s.checkFinalInstr(j, instr)
  297. }
  298. // Check Instruction.Operands.
  299. operands:
  300. for i, op := range instr.Operands(rands[:0]) {
  301. if op == nil {
  302. s.errorf("nil operand pointer %d of %s", i, instr)
  303. continue
  304. }
  305. val := *op
  306. if val == nil {
  307. continue // a nil operand is ok
  308. }
  309. // Check that "untyped" types only appear on constant operands.
  310. if _, ok := (*op).(*Const); !ok {
  311. if basic, ok := (*op).Type().(*types.Basic); ok {
  312. if basic.Info()&types.IsUntyped != 0 {
  313. s.errorf("operand #%d of %s is untyped: %s", i, instr, basic)
  314. }
  315. }
  316. }
  317. // Check that Operands that are also Instructions belong to same function.
  318. // TODO(adonovan): also check their block dominates block b.
  319. if val, ok := val.(Instruction); ok {
  320. if val.Block() == nil {
  321. s.errorf("operand %d of %s is an instruction (%s) that belongs to no block", i, instr, val)
  322. } else if val.Parent() != s.fn {
  323. s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent())
  324. }
  325. }
  326. // Check that each function-local operand of
  327. // instr refers back to instr. (NB: quadratic)
  328. switch val := val.(type) {
  329. case *Const, *Global, *Builtin:
  330. continue // not local
  331. case *Function:
  332. if val.parent == nil {
  333. continue // only anon functions are local
  334. }
  335. }
  336. // TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined.
  337. if refs := val.Referrers(); refs != nil {
  338. for _, ref := range *refs {
  339. if ref == instr {
  340. continue operands
  341. }
  342. }
  343. s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val)
  344. } else {
  345. s.errorf("operand %d of %s (%s) has no referrers", i, instr, val)
  346. }
  347. }
  348. }
  349. }
  350. func (s *sanity) checkReferrerList(v Value) {
  351. refs := v.Referrers()
  352. if refs == nil {
  353. s.errorf("%s has missing referrer list", v.Name())
  354. return
  355. }
  356. for i, ref := range *refs {
  357. if _, ok := s.instrs[ref]; !ok {
  358. s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref)
  359. }
  360. }
  361. }
  362. func (s *sanity) checkFunction(fn *Function) bool {
  363. // TODO(adonovan): check Function invariants:
  364. // - check params match signature
  365. // - check transient fields are nil
  366. // - warn if any fn.Locals do not appear among block instructions.
  367. s.fn = fn
  368. if fn.Prog == nil {
  369. s.errorf("nil Prog")
  370. }
  371. fn.String() // must not crash
  372. fn.RelString(fn.pkg()) // must not crash
  373. // All functions have a package, except delegates (which are
  374. // shared across packages, or duplicated as weak symbols in a
  375. // separate-compilation model), and error.Error.
  376. if fn.Pkg == nil {
  377. if strings.HasPrefix(fn.Synthetic, "wrapper ") ||
  378. strings.HasPrefix(fn.Synthetic, "bound ") ||
  379. strings.HasPrefix(fn.Synthetic, "thunk ") ||
  380. strings.HasSuffix(fn.name, "Error") {
  381. // ok
  382. } else {
  383. s.errorf("nil Pkg")
  384. }
  385. }
  386. if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn {
  387. s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn)
  388. }
  389. for i, l := range fn.Locals {
  390. if l.Parent() != fn {
  391. s.errorf("Local %s at index %d has wrong parent", l.Name(), i)
  392. }
  393. if l.Heap {
  394. s.errorf("Local %s at index %d has Heap flag set", l.Name(), i)
  395. }
  396. }
  397. // Build the set of valid referrers.
  398. s.instrs = make(map[Instruction]struct{})
  399. for _, b := range fn.Blocks {
  400. for _, instr := range b.Instrs {
  401. s.instrs[instr] = struct{}{}
  402. }
  403. }
  404. for i, p := range fn.Params {
  405. if p.Parent() != fn {
  406. s.errorf("Param %s at index %d has wrong parent", p.Name(), i)
  407. }
  408. s.checkReferrerList(p)
  409. }
  410. for i, fv := range fn.FreeVars {
  411. if fv.Parent() != fn {
  412. s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i)
  413. }
  414. s.checkReferrerList(fv)
  415. }
  416. if fn.Blocks != nil && len(fn.Blocks) == 0 {
  417. // Function _had_ blocks (so it's not external) but
  418. // they were "optimized" away, even the entry block.
  419. s.errorf("Blocks slice is non-nil but empty")
  420. }
  421. for i, b := range fn.Blocks {
  422. if b == nil {
  423. s.warnf("nil *BasicBlock at f.Blocks[%d]", i)
  424. continue
  425. }
  426. s.checkBlock(b, i)
  427. }
  428. if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover {
  429. s.errorf("Recover block is not in Blocks slice")
  430. }
  431. s.block = nil
  432. for i, anon := range fn.AnonFuncs {
  433. if anon.Parent() != fn {
  434. s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent())
  435. }
  436. }
  437. s.fn = nil
  438. return !s.insane
  439. }
  440. // sanityCheckPackage checks invariants of packages upon creation.
  441. // It does not require that the package is built.
  442. // Unlike sanityCheck (for functions), it just panics at the first error.
  443. func sanityCheckPackage(pkg *Package) {
  444. if pkg.Pkg == nil {
  445. panic(fmt.Sprintf("Package %s has no Object", pkg))
  446. }
  447. pkg.String() // must not crash
  448. for name, mem := range pkg.Members {
  449. if name != mem.Name() {
  450. panic(fmt.Sprintf("%s: %T.Name() = %s, want %s",
  451. pkg.Pkg.Path(), mem, mem.Name(), name))
  452. }
  453. obj := mem.Object()
  454. if obj == nil {
  455. // This check is sound because fields
  456. // {Global,Function}.object have type
  457. // types.Object. (If they were declared as
  458. // *types.{Var,Func}, we'd have a non-empty
  459. // interface containing a nil pointer.)
  460. continue // not all members have typechecker objects
  461. }
  462. if obj.Name() != name {
  463. if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") {
  464. // Ok. The name of a declared init function varies between
  465. // its types.Func ("init") and its ssa.Function ("init#%d").
  466. } else {
  467. panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s",
  468. pkg.Pkg.Path(), mem, obj.Name(), name))
  469. }
  470. }
  471. if obj.Pos() != mem.Pos() {
  472. panic(fmt.Sprintf("%s Pos=%d obj.Pos=%d", mem, mem.Pos(), obj.Pos()))
  473. }
  474. }
  475. }