Debian Codegraph @

src/cmd/compile/internal/ssa/prove.go

raw
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ssa
6
7 import (
8 "cmd/internal/src"
9 "cmp"
10 "fmt"
11 "math"
12 "math/bits"
13 "slices"
14 )
15
16 type branch int
17
18 const (
19 unknown branch = iota
20 positive
21 negative
22 // The outedges from a jump table are jumpTable0,
23 // jumpTable0+1, jumpTable0+2, etc. There could be an
24 // arbitrary number so we can't list them all here.
25 jumpTable0
26 )
27
28 func (b branch) String() string {
29 switch b {
30 case unknown:
31 return "unk"
32 case positive:
33 return "pos"
34 case negative:
35 return "neg"
36 default:
37 return fmt.Sprintf("jmp%d", b-jumpTable0)
38 }
39 }
40
41 // relation represents the set of possible relations between
42 // pairs of variables (v, w). Without a priori knowledge the
43 // mask is lt | eq | gt meaning v can be less than, equal to or
44 // greater than w. When the execution path branches on the condition
45 // `v op w` the set of relations is updated to exclude any
46 // relation not possible due to `v op w` being true (or false).
47 //
48 // E.g.
49 //
50 // r := relation(...)
51 //
52 // if v < w {
53 // newR := r & lt
54 // }
55 // if v >= w {
56 // newR := r & (eq|gt)
57 // }
58 // if v != w {
59 // newR := r & (lt|gt)
60 // }
61 type relation uint
62
63 const (
64 lt relation = 1 << iota
65 eq
66 gt
67 )
68
69 var relationStrings = [...]string{
70 0: "none", lt: "<", eq: "==", lt | eq: "<=",
71 gt: ">", gt | lt: "!=", gt | eq: ">=", gt | eq | lt: "any",
72 }
73
74 func (r relation) String() string {
75 if r < relation(len(relationStrings)) {
76 return relationStrings[r]
77 }
78 return fmt.Sprintf("relation(%d)", uint(r))
79 }
80
81 // domain represents the domain of a variable pair in which a set
82 // of relations is known. For example, relations learned for unsigned
83 // pairs cannot be transferred to signed pairs because the same bit
84 // representation can mean something else.
85 type domain uint
86
87 const (
88 signed domain = 1 << iota
89 unsigned
90 pointer
91 boolean
92 )
93
94 var domainStrings = [...]string{
95 "signed", "unsigned", "pointer", "boolean",
96 }
97
98 func (d domain) String() string {
99 s := ""
100 for i, ds := range domainStrings {
101 if d&(1<<uint(i)) != 0 {
102 if len(s) != 0 {
103 s += "|"
104 }
105 s += ds
106 d &^= 1 << uint(i)
107 }
108 }
109 if d != 0 {
110 if len(s) != 0 {
111 s += "|"
112 }
113 s += fmt.Sprintf("0x%x", uint(d))
114 }
115 return s
116 }
117
118 // a limit records known upper and lower bounds for a value.
119 //
120 // If we have min>max or umin>umax, then this limit is
121 // called "unsatisfiable". When we encounter such a limit, we
122 // know that any code for which that limit applies is unreachable.
123 // We don't particularly care how unsatisfiable limits propagate,
124 // including becoming satisfiable, because any optimization
125 // decisions based on those limits only apply to unreachable code.
126 type limit struct {
127 min, max int64 // min <= value <= max, signed
128 umin, umax uint64 // umin <= value <= umax, unsigned
129 // For booleans, we use 0==false, 1==true for both ranges
130 // For pointers, we use 0,0,0,0 for nil and minInt64,maxInt64,1,maxUint64 for nonnil
131 }
132
133 func (l limit) String() string {
134 return fmt.Sprintf("sm,SM,um,UM=%d,%d,%d,%d", l.min, l.max, l.umin, l.umax)
135 }
136
137 func (l limit) intersect(l2 limit) limit {
138 l.min = max(l.min, l2.min)
139 l.umin = max(l.umin, l2.umin)
140 l.max = min(l.max, l2.max)
141 l.umax = min(l.umax, l2.umax)
142 return l
143 }
144
145 func (l limit) signedMin(m int64) limit {
146 l.min = max(l.min, m)
147 return l
148 }
149 func (l limit) signedMax(m int64) limit {
150 l.max = min(l.max, m)
151 return l
152 }
153 func (l limit) signedMinMax(minimum, maximum int64) limit {
154 l.min = max(l.min, minimum)
155 l.max = min(l.max, maximum)
156 return l
157 }
158
159 func (l limit) unsignedMin(m uint64) limit {
160 l.umin = max(l.umin, m)
161 return l
162 }
163 func (l limit) unsignedMax(m uint64) limit {
164 l.umax = min(l.umax, m)
165 return l
166 }
167 func (l limit) unsignedMinMax(minimum, maximum uint64) limit {
168 l.umin = max(l.umin, minimum)
169 l.umax = min(l.umax, maximum)
170 return l
171 }
172
173 func (l limit) nonzero() bool {
174 return l.min > 0 || l.umin > 0 || l.max < 0
175 }
176 func (l limit) nonnegative() bool {
177 return l.min >= 0
178 }
179 func (l limit) unsat() bool {
180 return l.min > l.max || l.umin > l.umax
181 }
182
183 // If x and y can add without overflow or underflow
184 // (using b bits), safeAdd returns x+y, true.
185 // Otherwise, returns 0, false.
186 func safeAdd(x, y int64, b uint) (int64, bool) {
187 s := x + y
188 if x >= 0 && y >= 0 && s < 0 {
189 return 0, false // 64-bit overflow
190 }
191 if x < 0 && y < 0 && s >= 0 {
192 return 0, false // 64-bit underflow
193 }
194 if !fitsInBits(s, b) {
195 return 0, false
196 }
197 return s, true
198 }
199
200 // same as safeAdd for unsigned arithmetic.
201 func safeAddU(x, y uint64, b uint) (uint64, bool) {
202 s := x + y
203 if s < x || s < y {
204 return 0, false // 64-bit overflow
205 }
206 if !fitsInBitsU(s, b) {
207 return 0, false
208 }
209 return s, true
210 }
211
212 // same as safeAdd but for subtraction.
213 func safeSub(x, y int64, b uint) (int64, bool) {
214 if y == math.MinInt64 {
215 if x == math.MaxInt64 {
216 return 0, false // 64-bit overflow
217 }
218 x++
219 y++
220 }
221 return safeAdd(x, -y, b)
222 }
223
224 // same as safeAddU but for subtraction.
225 func safeSubU(x, y uint64, b uint) (uint64, bool) {
226 if x < y {
227 return 0, false // 64-bit underflow
228 }
229 s := x - y
230 if !fitsInBitsU(s, b) {
231 return 0, false
232 }
233 return s, true
234 }
235
236 // fitsInBits reports whether x fits in b bits (signed).
237 func fitsInBits(x int64, b uint) bool {
238 if b == 64 {
239 return true
240 }
241 m := int64(-1) << (b - 1)
242 M := -m - 1
243 return x >= m && x <= M
244 }
245
246 // fitsInBitsU reports whether x fits in b bits (unsigned).
247 func fitsInBitsU(x uint64, b uint) bool {
248 return x>>b == 0
249 }
250
251 // add returns the limit obtained by adding a value with limit l
252 // to a value with limit l2. The result must fit in b bits.
253 func (l limit) add(l2 limit, b uint) limit {
254 r := noLimit
255 min, minOk := safeAdd(l.min, l2.min, b)
256 max, maxOk := safeAdd(l.max, l2.max, b)
257 if minOk && maxOk {
258 r.min = min
259 r.max = max
260 }
261 umin, uminOk := safeAddU(l.umin, l2.umin, b)
262 umax, umaxOk := safeAddU(l.umax, l2.umax, b)
263 if uminOk && umaxOk {
264 r.umin = umin
265 r.umax = umax
266 }
267 return r
268 }
269
270 // same as add but for subtraction.
271 func (l limit) sub(l2 limit, b uint) limit {
272 r := noLimit
273 min, minOk := safeSub(l.min, l2.max, b)
274 max, maxOk := safeSub(l.max, l2.min, b)
275 if minOk && maxOk {
276 r.min = min
277 r.max = max
278 }
279 umin, uminOk := safeSubU(l.umin, l2.umax, b)
280 umax, umaxOk := safeSubU(l.umax, l2.umin, b)
281 if uminOk && umaxOk {
282 r.umin = umin
283 r.umax = umax
284 }
285 return r
286 }
287
288 // same as add but for multiplication.
289 func (l limit) mul(l2 limit, b uint) limit {
290 r := noLimit
291 umaxhi, umaxlo := bits.Mul64(l.umax, l2.umax)
292 if umaxhi == 0 && fitsInBitsU(umaxlo, b) {
293 r.umax = umaxlo
294 r.umin = l.umin * l2.umin
295 // Note: if the code containing this multiply is
296 // unreachable, then we may have umin>umax, and this
297 // multiply may overflow. But that's ok for
298 // unreachable code. If this code is reachable, we
299 // know umin<=umax, so this multiply will not overflow
300 // because the max multiply didn't.
301 }
302 // Signed is harder, so don't bother. The only useful
303 // case is when we know both multiplicands are nonnegative,
304 // but that case is handled above because we would have then
305 // previously propagated signed info to the unsigned domain,
306 // and will propagate it back after the multiply.
307 return r
308 }
309
310 // Similar to add, but compute 1 << l if it fits without overflow in b bits.
311 func (l limit) exp2(b uint) limit {
312 r := noLimit
313 if l.umax < uint64(b) {
314 r.umin = 1 << l.umin
315 r.umax = 1 << l.umax
316 // Same as above in mul, signed<->unsigned propagation
317 // will handle the signed case for us.
318 }
319 return r
320 }
321
322 // Similar to add, but computes the complement of the limit for bitsize b.
323 func (l limit) com(b uint) limit {
324 switch b {
325 case 64:
326 return limit{
327 min: ^l.max,
328 max: ^l.min,
329 umin: ^l.umax,
330 umax: ^l.umin,
331 }
332 case 32:
333 return limit{
334 min: int64(^int32(l.max)),
335 max: int64(^int32(l.min)),
336 umin: uint64(^uint32(l.umax)),
337 umax: uint64(^uint32(l.umin)),
338 }
339 case 16:
340 return limit{
341 min: int64(^int16(l.max)),
342 max: int64(^int16(l.min)),
343 umin: uint64(^uint16(l.umax)),
344 umax: uint64(^uint16(l.umin)),
345 }
346 case 8:
347 return limit{
348 min: int64(^int8(l.max)),
349 max: int64(^int8(l.min)),
350 umin: uint64(^uint8(l.umax)),
351 umax: uint64(^uint8(l.umin)),
352 }
353 default:
354 panic("unreachable")
355 }
356 }
357
358 var noLimit = limit{math.MinInt64, math.MaxInt64, 0, math.MaxUint64}
359
360 // a limitFact is a limit known for a particular value.
361 type limitFact struct {
362 vid ID
363 limit limit
364 }
365
366 // An ordering encodes facts like v < w.
367 type ordering struct {
368 next *ordering // linked list of all known orderings for v.
369 // Note: v is implicit here, determined by which linked list it is in.
370 w *Value
371 d domain
372 r relation // one of ==,!=,<,<=,>,>=
373 // if d is boolean or pointer, r can only be ==, !=
374 }
375
376 // factsTable keeps track of relations between pairs of values.
377 //
378 // The fact table logic is sound, but incomplete. Outside of a few
379 // special cases, it performs no deduction or arithmetic. While there
380 // are known decision procedures for this, the ad hoc approach taken
381 // by the facts table is effective for real code while remaining very
382 // efficient.
383 type factsTable struct {
384 // unsat is true if facts contains a contradiction.
385 //
386 // Note that the factsTable logic is incomplete, so if unsat
387 // is false, the assertions in factsTable could be satisfiable
388 // *or* unsatisfiable.
389 unsat bool // true if facts contains a contradiction
390 unsatDepth int // number of unsat checkpoints
391
392 // order* is a couple of partial order sets that record information
393 // about relations between SSA values in the signed and unsigned
394 // domain.
395 orderS *poset
396 orderU *poset
397
398 // orderings contains a list of known orderings between values.
399 // These lists are indexed by v.ID.
400 // We do not record transitive orderings. Only explicitly learned
401 // orderings are recorded. Transitive orderings can be obtained
402 // by walking along the individual orderings.
403 orderings map[ID]*ordering
404 // stack of IDs which have had an entry added in orderings.
405 // In addition, ID==0 are checkpoint markers.
406 orderingsStack []ID
407 orderingCache *ordering // unused ordering records
408
409 // known lower and upper constant bounds on individual values.
410 limits []limit // indexed by value ID
411 limitStack []limitFact // previous entries
412 recurseCheck []bool // recursion detector for limit propagation
413
414 // For each slice s, a map from s to a len(s)/cap(s) value (if any)
415 // TODO: check if there are cases that matter where we have
416 // more than one len(s) for a slice. We could keep a list if necessary.
417 lens map[ID]*Value
418 caps map[ID]*Value
419
420 // reusedTopoSortScoresTable recycle allocations for topo-sort
421 reusedTopoSortScoresTable []uint
422 }
423
424 // checkpointBound is an invalid value used for checkpointing
425 // and restoring factsTable.
426 var checkpointBound = limitFact{}
427
428 func newFactsTable(f *Func) *factsTable {
429 ft := &factsTable{}
430 ft.orderS = f.newPoset()
431 ft.orderU = f.newPoset()
432 ft.orderS.SetUnsigned(false)
433 ft.orderU.SetUnsigned(true)
434 ft.orderings = make(map[ID]*ordering)
435 ft.limits = f.Cache.allocLimitSlice(f.NumValues())
436 for _, b := range f.Blocks {
437 for _, v := range b.Values {
438 ft.limits[v.ID] = initLimit(v)
439 }
440 }
441 ft.limitStack = make([]limitFact, 4)
442 ft.recurseCheck = f.Cache.allocBoolSlice(f.NumValues())
443 return ft
444 }
445
446 // initLimitForNewValue initializes the limits for newly created values,
447 // possibly needing to expand the limits slice. Currently used by
448 // simplifyBlock when certain provably constant results are folded.
449 func (ft *factsTable) initLimitForNewValue(v *Value) {
450 if int(v.ID) >= len(ft.limits) {
451 f := v.Block.Func
452 n := f.NumValues()
453 if cap(ft.limits) >= n {
454 ft.limits = ft.limits[:n]
455 } else {
456 old := ft.limits
457 ft.limits = f.Cache.allocLimitSlice(n)
458 copy(ft.limits, old)
459 f.Cache.freeLimitSlice(old)
460 }
461 }
462 ft.limits[v.ID] = initLimit(v)
463 }
464
465 // signedMin records the fact that we know v is at least
466 // min in the signed domain.
467 func (ft *factsTable) signedMin(v *Value, min int64) bool {
468 return ft.newLimit(v, limit{min: min, max: math.MaxInt64, umin: 0, umax: math.MaxUint64})
469 }
470
471 // signedMax records the fact that we know v is at most
472 // max in the signed domain.
473 func (ft *factsTable) signedMax(v *Value, max int64) bool {
474 return ft.newLimit(v, limit{min: math.MinInt64, max: max, umin: 0, umax: math.MaxUint64})
475 }
476 func (ft *factsTable) signedMinMax(v *Value, min, max int64) bool {
477 return ft.newLimit(v, limit{min: min, max: max, umin: 0, umax: math.MaxUint64})
478 }
479
480 // setNonNegative records the fact that v is known to be non-negative.
481 func (ft *factsTable) setNonNegative(v *Value) bool {
482 return ft.signedMin(v, 0)
483 }
484
485 // unsignedMin records the fact that we know v is at least
486 // min in the unsigned domain.
487 func (ft *factsTable) unsignedMin(v *Value, min uint64) bool {
488 return ft.newLimit(v, limit{min: math.MinInt64, max: math.MaxInt64, umin: min, umax: math.MaxUint64})
489 }
490
491 // unsignedMax records the fact that we know v is at most
492 // max in the unsigned domain.
493 func (ft *factsTable) unsignedMax(v *Value, max uint64) bool {
494 return ft.newLimit(v, limit{min: math.MinInt64, max: math.MaxInt64, umin: 0, umax: max})
495 }
496 func (ft *factsTable) unsignedMinMax(v *Value, min, max uint64) bool {
497 return ft.newLimit(v, limit{min: math.MinInt64, max: math.MaxInt64, umin: min, umax: max})
498 }
499
500 func (ft *factsTable) booleanFalse(v *Value) bool {
501 return ft.newLimit(v, limit{min: 0, max: 0, umin: 0, umax: 0})
502 }
503 func (ft *factsTable) booleanTrue(v *Value) bool {
504 return ft.newLimit(v, limit{min: 1, max: 1, umin: 1, umax: 1})
505 }
506 func (ft *factsTable) pointerNil(v *Value) bool {
507 return ft.newLimit(v, limit{min: 0, max: 0, umin: 0, umax: 0})
508 }
509 func (ft *factsTable) pointerNonNil(v *Value) bool {
510 l := noLimit
511 l.umin = 1
512 return ft.newLimit(v, l)
513 }
514
515 // newLimit adds new limiting information for v.
516 // Returns true if the new limit added any new information.
517 func (ft *factsTable) newLimit(v *Value, newLim limit) bool {
518 oldLim := ft.limits[v.ID]
519
520 // Merge old and new information.
521 lim := oldLim.intersect(newLim)
522
523 // signed <-> unsigned propagation
524 if lim.min >= 0 {
525 lim = lim.unsignedMinMax(uint64(lim.min), uint64(lim.max))
526 }
527 if fitsInBitsU(lim.umax, uint(8*v.Type.Size()-1)) {
528 lim = lim.signedMinMax(int64(lim.umin), int64(lim.umax))
529 }
530
531 if lim == oldLim {
532 return false // nothing new to record
533 }
534
535 if lim.unsat() {
536 r := !ft.unsat
537 ft.unsat = true
538 return r
539 }
540
541 // Check for recursion. This normally happens because in unsatisfiable
542 // cases we have a < b < a, and every update to a's limits returns
543 // here again with the limit increased by 2.
544 // Normally this is caught early by the orderS/orderU posets, but in
545 // cases where the comparisons jump between signed and unsigned domains,
546 // the posets will not notice.
547 if ft.recurseCheck[v.ID] {
548 // This should only happen for unsatisfiable cases. TODO: check
549 return false
550 }
551 ft.recurseCheck[v.ID] = true
552 defer func() {
553 ft.recurseCheck[v.ID] = false
554 }()
555
556 // Record undo information.
557 ft.limitStack = append(ft.limitStack, limitFact{v.ID, oldLim})
558 // Record new information.
559 ft.limits[v.ID] = lim
560 if v.Block.Func.pass.debug > 2 {
561 // TODO: pos is probably wrong. This is the position where v is defined,
562 // not the position where we learned the fact about it (which was
563 // probably some subsequent compare+branch).
564 v.Block.Func.Warnl(v.Pos, "new limit %s %s unsat=%v", v, lim.String(), ft.unsat)
565 }
566
567 // Propagate this new constant range to other values
568 // that we know are ordered with respect to this one.
569 // Note overflow/underflow in the arithmetic below is ok,
570 // it will just lead to imprecision (undetected unsatisfiability).
571 for o := ft.orderings[v.ID]; o != nil; o = o.next {
572 switch o.d {
573 case signed:
574 switch o.r {
575 case eq: // v == w
576 ft.signedMinMax(o.w, lim.min, lim.max)
577 case lt | eq: // v <= w
578 ft.signedMin(o.w, lim.min)
579 case lt: // v < w
580 ft.signedMin(o.w, lim.min+1)
581 case gt | eq: // v >= w
582 ft.signedMax(o.w, lim.max)
583 case gt: // v > w
584 ft.signedMax(o.w, lim.max-1)
585 case lt | gt: // v != w
586 if lim.min == lim.max { // v is a constant
587 c := lim.min
588 if ft.limits[o.w.ID].min == c {
589 ft.signedMin(o.w, c+1)
590 }
591 if ft.limits[o.w.ID].max == c {
592 ft.signedMax(o.w, c-1)
593 }
594 }
595 }
596 case unsigned:
597 switch o.r {
598 case eq: // v == w
599 ft.unsignedMinMax(o.w, lim.umin, lim.umax)
600 case lt | eq: // v <= w
601 ft.unsignedMin(o.w, lim.umin)
602 case lt: // v < w
603 ft.unsignedMin(o.w, lim.umin+1)
604 case gt | eq: // v >= w
605 ft.unsignedMax(o.w, lim.umax)
606 case gt: // v > w
607 ft.unsignedMax(o.w, lim.umax-1)
608 case lt | gt: // v != w
609 if lim.umin == lim.umax { // v is a constant
610 c := lim.umin
611 if ft.limits[o.w.ID].umin == c {
612 ft.unsignedMin(o.w, c+1)
613 }
614 if ft.limits[o.w.ID].umax == c {
615 ft.unsignedMax(o.w, c-1)
616 }
617 }
618 }
619 case boolean:
620 switch o.r {
621 case eq:
622 if lim.min == 0 && lim.max == 0 { // constant false
623 ft.booleanFalse(o.w)
624 }
625 if lim.min == 1 && lim.max == 1 { // constant true
626 ft.booleanTrue(o.w)
627 }
628 case lt | gt:
629 if lim.min == 0 && lim.max == 0 { // constant false
630 ft.booleanTrue(o.w)
631 }
632 if lim.min == 1 && lim.max == 1 { // constant true
633 ft.booleanFalse(o.w)
634 }
635 }
636 case pointer:
637 switch o.r {
638 case eq:
639 if lim.umax == 0 { // nil
640 ft.pointerNil(o.w)
641 }
642 if lim.umin > 0 { // non-nil
643 ft.pointerNonNil(o.w)
644 }
645 case lt | gt:
646 if lim.umax == 0 { // nil
647 ft.pointerNonNil(o.w)
648 }
649 // note: not equal to non-nil doesn't tell us anything.
650 }
651 }
652 }
653
654 // If this is new known constant for a boolean value,
655 // extract relation between its args. For example, if
656 // We learn v is false, and v is defined as a<b, then we learn a>=b.
657 if v.Type.IsBoolean() {
658 // If we reach here, it is because we have a more restrictive
659 // value for v than the default. The only two such values
660 // are constant true or constant false.
661 if lim.min != lim.max {
662 v.Block.Func.Fatalf("boolean not constant %v", v)
663 }
664 isTrue := lim.min == 1
665 if dr, ok := domainRelationTable[v.Op]; ok && v.Op != OpIsInBounds && v.Op != OpIsSliceInBounds {
666 d := dr.d
667 r := dr.r
668 if d == signed && ft.isNonNegative(v.Args[0]) && ft.isNonNegative(v.Args[1]) {
669 d |= unsigned
670 }
671 if !isTrue {
672 r ^= lt | gt | eq
673 }
674 // TODO: v.Block is wrong?
675 addRestrictions(v.Block, ft, d, v.Args[0], v.Args[1], r)
676 }
677 switch v.Op {
678 case OpIsNonNil:
679 if isTrue {
680 ft.pointerNonNil(v.Args[0])
681 } else {
682 ft.pointerNil(v.Args[0])
683 }
684 case OpIsInBounds, OpIsSliceInBounds:
685 // 0 <= a0 < a1 (or 0 <= a0 <= a1)
686 r := lt
687 if v.Op == OpIsSliceInBounds {
688 r |= eq
689 }
690 if isTrue {
691 // On the positive branch, we learn:
692 // signed: 0 <= a0 < a1 (or 0 <= a0 <= a1)
693 // unsigned: a0 < a1 (or a0 <= a1)
694 ft.setNonNegative(v.Args[0])
695 ft.update(v.Block, v.Args[0], v.Args[1], signed, r)
696 ft.update(v.Block, v.Args[0], v.Args[1], unsigned, r)
697 } else {
698 // On the negative branch, we learn (0 > a0 ||
699 // a0 >= a1). In the unsigned domain, this is
700 // simply a0 >= a1 (which is the reverse of the
701 // positive branch, so nothing surprising).
702 // But in the signed domain, we can't express the ||
703 // condition, so check if a0 is non-negative instead,
704 // to be able to learn something.
705 r ^= lt | gt | eq // >= (index) or > (slice)
706 if ft.isNonNegative(v.Args[0]) {
707 ft.update(v.Block, v.Args[0], v.Args[1], signed, r)
708 }
709 ft.update(v.Block, v.Args[0], v.Args[1], unsigned, r)
710 // TODO: v.Block is wrong here
711 }
712 }
713 }
714
715 return true
716 }
717
718 func (ft *factsTable) addOrdering(v, w *Value, d domain, r relation) {
719 o := ft.orderingCache
720 if o == nil {
721 o = &ordering{}
722 } else {
723 ft.orderingCache = o.next
724 }
725 o.w = w
726 o.d = d
727 o.r = r
728 o.next = ft.orderings[v.ID]
729 ft.orderings[v.ID] = o
730 ft.orderingsStack = append(ft.orderingsStack, v.ID)
731 }
732
733 // update updates the set of relations between v and w in domain d
734 // restricting it to r.
735 func (ft *factsTable) update(parent *Block, v, w *Value, d domain, r relation) {
736 if parent.Func.pass.debug > 2 {
737 parent.Func.Warnl(parent.Pos, "parent=%s, update %s %s %s", parent, v, w, r)
738 }
739 // No need to do anything else if we already found unsat.
740 if ft.unsat {
741 return
742 }
743
744 // Self-fact. It's wasteful to register it into the facts
745 // table, so just note whether it's satisfiable
746 if v == w {
747 if r&eq == 0 {
748 ft.unsat = true
749 }
750 return
751 }
752
753 if d == signed || d == unsigned {
754 var ok bool
755 order := ft.orderS
756 if d == unsigned {
757 order = ft.orderU
758 }
759 switch r {
760 case lt:
761 ok = order.SetOrder(v, w)
762 case gt:
763 ok = order.SetOrder(w, v)
764 case lt | eq:
765 ok = order.SetOrderOrEqual(v, w)
766 case gt | eq:
767 ok = order.SetOrderOrEqual(w, v)
768 case eq:
769 ok = order.SetEqual(v, w)
770 case lt | gt:
771 ok = order.SetNonEqual(v, w)
772 default:
773 panic("unknown relation")
774 }
775 ft.addOrdering(v, w, d, r)
776 ft.addOrdering(w, v, d, reverseBits[r])
777
778 if !ok {
779 if parent.Func.pass.debug > 2 {
780 parent.Func.Warnl(parent.Pos, "unsat %s %s %s", v, w, r)
781 }
782 ft.unsat = true
783 return
784 }
785 }
786 if d == boolean || d == pointer {
787 for o := ft.orderings[v.ID]; o != nil; o = o.next {
788 if o.d == d && o.w == w {
789 // We already know a relationship between v and w.
790 // Either it is a duplicate, or it is a contradiction,
791 // as we only allow eq and lt|gt for these domains,
792 if o.r != r {
793 ft.unsat = true
794 }
795 return
796 }
797 }
798 // TODO: this does not do transitive equality.
799 // We could use a poset like above, but somewhat degenerate (==,!= only).
800 ft.addOrdering(v, w, d, r)
801 ft.addOrdering(w, v, d, r) // note: reverseBits unnecessary for eq and lt|gt.
802 }
803
804 // Extract new constant limits based on the comparison.
805 vLimit := ft.limits[v.ID]
806 wLimit := ft.limits[w.ID]
807 // Note: all the +1/-1 below could overflow/underflow. Either will
808 // still generate correct results, it will just lead to imprecision.
809 // In fact if there is overflow/underflow, the corresponding
810 // code is unreachable because the known range is outside the range
811 // of the value's type.
812 switch d {
813 case signed:
814 switch r {
815 case eq: // v == w
816 ft.signedMinMax(v, wLimit.min, wLimit.max)
817 ft.signedMinMax(w, vLimit.min, vLimit.max)
818 case lt: // v < w
819 ft.signedMax(v, wLimit.max-1)
820 ft.signedMin(w, vLimit.min+1)
821 case lt | eq: // v <= w
822 ft.signedMax(v, wLimit.max)
823 ft.signedMin(w, vLimit.min)
824 case gt: // v > w
825 ft.signedMin(v, wLimit.min+1)
826 ft.signedMax(w, vLimit.max-1)
827 case gt | eq: // v >= w
828 ft.signedMin(v, wLimit.min)
829 ft.signedMax(w, vLimit.max)
830 case lt | gt: // v != w
831 if vLimit.min == vLimit.max { // v is a constant
832 c := vLimit.min
833 if wLimit.min == c {
834 ft.signedMin(w, c+1)
835 }
836 if wLimit.max == c {
837 ft.signedMax(w, c-1)
838 }
839 }
840 if wLimit.min == wLimit.max { // w is a constant
841 c := wLimit.min
842 if vLimit.min == c {
843 ft.signedMin(v, c+1)
844 }
845 if vLimit.max == c {
846 ft.signedMax(v, c-1)
847 }
848 }
849 }
850 case unsigned:
851 switch r {
852 case eq: // v == w
853 ft.unsignedMinMax(v, wLimit.umin, wLimit.umax)
854 ft.unsignedMinMax(w, vLimit.umin, vLimit.umax)
855 case lt: // v < w
856 ft.unsignedMax(v, wLimit.umax-1)
857 ft.unsignedMin(w, vLimit.umin+1)
858 case lt | eq: // v <= w
859 ft.unsignedMax(v, wLimit.umax)
860 ft.unsignedMin(w, vLimit.umin)
861 case gt: // v > w
862 ft.unsignedMin(v, wLimit.umin+1)
863 ft.unsignedMax(w, vLimit.umax-1)
864 case gt | eq: // v >= w
865 ft.unsignedMin(v, wLimit.umin)
866 ft.unsignedMax(w, vLimit.umax)
867 case lt | gt: // v != w
868 if vLimit.umin == vLimit.umax { // v is a constant
869 c := vLimit.umin
870 if wLimit.umin == c {
871 ft.unsignedMin(w, c+1)
872 }
873 if wLimit.umax == c {
874 ft.unsignedMax(w, c-1)
875 }
876 }
877 if wLimit.umin == wLimit.umax { // w is a constant
878 c := wLimit.umin
879 if vLimit.umin == c {
880 ft.unsignedMin(v, c+1)
881 }
882 if vLimit.umax == c {
883 ft.unsignedMax(v, c-1)
884 }
885 }
886 }
887 case boolean:
888 switch r {
889 case eq: // v == w
890 if vLimit.min == 1 { // v is true
891 ft.booleanTrue(w)
892 }
893 if vLimit.max == 0 { // v is false
894 ft.booleanFalse(w)
895 }
896 if wLimit.min == 1 { // w is true
897 ft.booleanTrue(v)
898 }
899 if wLimit.max == 0 { // w is false
900 ft.booleanFalse(v)
901 }
902 case lt | gt: // v != w
903 if vLimit.min == 1 { // v is true
904 ft.booleanFalse(w)
905 }
906 if vLimit.max == 0 { // v is false
907 ft.booleanTrue(w)
908 }
909 if wLimit.min == 1 { // w is true
910 ft.booleanFalse(v)
911 }
912 if wLimit.max == 0 { // w is false
913 ft.booleanTrue(v)
914 }
915 }
916 case pointer:
917 switch r {
918 case eq: // v == w
919 if vLimit.umax == 0 { // v is nil
920 ft.pointerNil(w)
921 }
922 if vLimit.umin > 0 { // v is non-nil
923 ft.pointerNonNil(w)
924 }
925 if wLimit.umax == 0 { // w is nil
926 ft.pointerNil(v)
927 }
928 if wLimit.umin > 0 { // w is non-nil
929 ft.pointerNonNil(v)
930 }
931 case lt | gt: // v != w
932 if vLimit.umax == 0 { // v is nil
933 ft.pointerNonNil(w)
934 }
935 if wLimit.umax == 0 { // w is nil
936 ft.pointerNonNil(v)
937 }
938 // Note: the other direction doesn't work.
939 // Being not equal to a non-nil pointer doesn't
940 // make you (necessarily) a nil pointer.
941 }
942 }
943
944 // Derived facts below here are only about numbers.
945 if d != signed && d != unsigned {
946 return
947 }
948
949 // Additional facts we know given the relationship between len and cap.
950 //
951 // TODO: Since prove now derives transitive relations, it
952 // should be sufficient to learn that len(w) <= cap(w) at the
953 // beginning of prove where we look for all len/cap ops.
954 if v.Op == OpSliceLen && r&lt == 0 && ft.caps[v.Args[0].ID] != nil {
955 // len(s) > w implies cap(s) > w
956 // len(s) >= w implies cap(s) >= w
957 // len(s) == w implies cap(s) >= w
958 ft.update(parent, ft.caps[v.Args[0].ID], w, d, r|gt)
959 }
960 if w.Op == OpSliceLen && r&gt == 0 && ft.caps[w.Args[0].ID] != nil {
961 // same, length on the RHS.
962 ft.update(parent, v, ft.caps[w.Args[0].ID], d, r|lt)
963 }
964 if v.Op == OpSliceCap && r&gt == 0 && ft.lens[v.Args[0].ID] != nil {
965 // cap(s) < w implies len(s) < w
966 // cap(s) <= w implies len(s) <= w
967 // cap(s) == w implies len(s) <= w
968 ft.update(parent, ft.lens[v.Args[0].ID], w, d, r|lt)
969 }
970 if w.Op == OpSliceCap && r&lt == 0 && ft.lens[w.Args[0].ID] != nil {
971 // same, capacity on the RHS.
972 ft.update(parent, v, ft.lens[w.Args[0].ID], d, r|gt)
973 }
974
975 // Process fence-post implications.
976 //
977 // First, make the condition > or >=.
978 if r == lt || r == lt|eq {
979 v, w = w, v
980 r = reverseBits[r]
981 }
982 switch r {
983 case gt:
984 if x, delta := isConstDelta(v); x != nil && delta == 1 {
985 // x+1 > w ⇒ x >= w
986 //
987 // This is useful for eliminating the
988 // growslice branch of append.
989 ft.update(parent, x, w, d, gt|eq)
990 } else if x, delta := isConstDelta(w); x != nil && delta == -1 {
991 // v > x-1 ⇒ v >= x
992 ft.update(parent, v, x, d, gt|eq)
993 }
994 case gt | eq:
995 if x, delta := isConstDelta(v); x != nil && delta == -1 {
996 // x-1 >= w && x > min ⇒ x > w
997 //
998 // Useful for i > 0; s[i-1].
999 lim := ft.limits[x.ID]
1000 if (d == signed && lim.min > opMin[v.Op]) || (d == unsigned && lim.umin > 0) {
1001 ft.update(parent, x, w, d, gt)
1002 }
1003 } else if x, delta := isConstDelta(w); x != nil && delta == 1 {
1004 // v >= x+1 && x < max ⇒ v > x
1005 lim := ft.limits[x.ID]
1006 if (d == signed && lim.max < opMax[w.Op]) || (d == unsigned && lim.umax < opUMax[w.Op]) {
1007 ft.update(parent, v, x, d, gt)
1008 }
1009 }
1010 }
1011
1012 // Process: x+delta > w (with delta constant)
1013 // Only signed domain for now (useful for accesses to slices in loops).
1014 if r == gt || r == gt|eq {
1015 if x, delta := isConstDelta(v); x != nil && d == signed {
1016 if parent.Func.pass.debug > 1 {
1017 parent.Func.Warnl(parent.Pos, "x+d %s w; x:%v %v delta:%v w:%v d:%v", r, x, parent.String(), delta, w.AuxInt, d)
1018 }
1019 underflow := true
1020 if delta < 0 {
1021 l := ft.limits[x.ID]
1022 if (x.Type.Size() == 8 && l.min >= math.MinInt64-delta) ||
1023 (x.Type.Size() == 4 && l.min >= math.MinInt32-delta) {
1024 underflow = false
1025 }
1026 }
1027 if delta < 0 && !underflow {
1028 // If delta < 0 and x+delta cannot underflow then x > x+delta (that is, x > v)
1029 ft.update(parent, x, v, signed, gt)
1030 }
1031 if !w.isGenericIntConst() {
1032 // If we know that x+delta > w but w is not constant, we can derive:
1033 // if delta < 0 and x+delta cannot underflow, then x > w
1034 // This is useful for loops with bounds "len(slice)-K" (delta = -K)
1035 if delta < 0 && !underflow {
1036 ft.update(parent, x, w, signed, r)
1037 }
1038 } else {
1039 // With w,delta constants, we want to derive: x+delta > w ⇒ x > w-delta
1040 //
1041 // We compute (using integers of the correct size):
1042 // min = w - delta
1043 // max = MaxInt - delta
1044 //
1045 // And we prove that:
1046 // if min<max: min < x AND x <= max
1047 // if min>max: min < x OR x <= max
1048 //
1049 // This is always correct, even in case of overflow.
1050 //
1051 // If the initial fact is x+delta >= w instead, the derived conditions are:
1052 // if min<max: min <= x AND x <= max
1053 // if min>max: min <= x OR x <= max
1054 //
1055 // Notice the conditions for max are still <=, as they handle overflows.
1056 var min, max int64
1057 switch x.Type.Size() {
1058 case 8:
1059 min = w.AuxInt - delta
1060 max = int64(^uint64(0)>>1) - delta
1061 case 4:
1062 min = int64(int32(w.AuxInt) - int32(delta))
1063 max = int64(int32(^uint32(0)>>1) - int32(delta))
1064 case 2:
1065 min = int64(int16(w.AuxInt) - int16(delta))
1066 max = int64(int16(^uint16(0)>>1) - int16(delta))
1067 case 1:
1068 min = int64(int8(w.AuxInt) - int8(delta))
1069 max = int64(int8(^uint8(0)>>1) - int8(delta))
1070 default:
1071 panic("unimplemented")
1072 }
1073
1074 if min < max {
1075 // Record that x > min and max >= x
1076 if r == gt {
1077 min++
1078 }
1079 ft.signedMinMax(x, min, max)
1080 } else {
1081 // We know that either x>min OR x<=max. factsTable cannot record OR conditions,
1082 // so let's see if we can already prove that one of them is false, in which case
1083 // the other must be true
1084 l := ft.limits[x.ID]
1085 if l.max <= min {
1086 if r&eq == 0 || l.max < min {
1087 // x>min (x>=min) is impossible, so it must be x<=max
1088 ft.signedMax(x, max)
1089 }
1090 } else if l.min > max {
1091 // x<=max is impossible, so it must be x>min
1092 if r == gt {
1093 min++
1094 }
1095 ft.signedMin(x, min)
1096 }
1097 }
1098 }
1099 }
1100 }
1101
1102 // Look through value-preserving extensions.
1103 // If the domain is appropriate for the pre-extension Type,
1104 // repeat the update with the pre-extension Value.
1105 if isCleanExt(v) {
1106 switch {
1107 case d == signed && v.Args[0].Type.IsSigned():
1108 fallthrough
1109 case d == unsigned && !v.Args[0].Type.IsSigned():
1110 ft.update(parent, v.Args[0], w, d, r)
1111 }
1112 }
1113 if isCleanExt(w) {
1114 switch {
1115 case d == signed && w.Args[0].Type.IsSigned():
1116 fallthrough
1117 case d == unsigned && !w.Args[0].Type.IsSigned():
1118 ft.update(parent, v, w.Args[0], d, r)
1119 }
1120 }
1121 }
1122
1123 var opMin = map[Op]int64{
1124 OpAdd64: math.MinInt64, OpSub64: math.MinInt64,
1125 OpAdd32: math.MinInt32, OpSub32: math.MinInt32,
1126 }
1127
1128 var opMax = map[Op]int64{
1129 OpAdd64: math.MaxInt64, OpSub64: math.MaxInt64,
1130 OpAdd32: math.MaxInt32, OpSub32: math.MaxInt32,
1131 }
1132
1133 var opUMax = map[Op]uint64{
1134 OpAdd64: math.MaxUint64, OpSub64: math.MaxUint64,
1135 OpAdd32: math.MaxUint32, OpSub32: math.MaxUint32,
1136 }
1137
1138 // isNonNegative reports whether v is known to be non-negative.
1139 func (ft *factsTable) isNonNegative(v *Value) bool {
1140 return ft.limits[v.ID].min >= 0
1141 }
1142
1143 // checkpoint saves the current state of known relations.
1144 // Called when descending on a branch.
1145 func (ft *factsTable) checkpoint() {
1146 if ft.unsat {
1147 ft.unsatDepth++
1148 }
1149 ft.limitStack = append(ft.limitStack, checkpointBound)
1150 ft.orderS.Checkpoint()
1151 ft.orderU.Checkpoint()
1152 ft.orderingsStack = append(ft.orderingsStack, 0)
1153 }
1154
1155 // restore restores known relation to the state just
1156 // before the previous checkpoint.
1157 // Called when backing up on a branch.
1158 func (ft *factsTable) restore() {
1159 if ft.unsatDepth > 0 {
1160 ft.unsatDepth--
1161 } else {
1162 ft.unsat = false
1163 }
1164 for {
1165 old := ft.limitStack[len(ft.limitStack)-1]
1166 ft.limitStack = ft.limitStack[:len(ft.limitStack)-1]
1167 if old.vid == 0 { // checkpointBound
1168 break
1169 }
1170 ft.limits[old.vid] = old.limit
1171 }
1172 ft.orderS.Undo()
1173 ft.orderU.Undo()
1174 for {
1175 id := ft.orderingsStack[len(ft.orderingsStack)-1]
1176 ft.orderingsStack = ft.orderingsStack[:len(ft.orderingsStack)-1]
1177 if id == 0 { // checkpoint marker
1178 break
1179 }
1180 o := ft.orderings[id]
1181 ft.orderings[id] = o.next
1182 o.next = ft.orderingCache
1183 ft.orderingCache = o
1184 }
1185 }
1186
1187 var (
1188 reverseBits = [...]relation{0, 4, 2, 6, 1, 5, 3, 7}
1189
1190 // maps what we learn when the positive branch is taken.
1191 // For example:
1192 // OpLess8: {signed, lt},
1193 // v1 = (OpLess8 v2 v3).
1194 // If we learn that v1 is true, then we can deduce that v2<v3
1195 // in the signed domain.
1196 domainRelationTable = map[Op]struct {
1197 d domain
1198 r relation
1199 }{
1200 OpEq8: {signed | unsigned, eq},
1201 OpEq16: {signed | unsigned, eq},
1202 OpEq32: {signed | unsigned, eq},
1203 OpEq64: {signed | unsigned, eq},
1204 OpEqPtr: {pointer, eq},
1205 OpEqB: {boolean, eq},
1206
1207 OpNeq8: {signed | unsigned, lt | gt},
1208 OpNeq16: {signed | unsigned, lt | gt},
1209 OpNeq32: {signed | unsigned, lt | gt},
1210 OpNeq64: {signed | unsigned, lt | gt},
1211 OpNeqPtr: {pointer, lt | gt},
1212 OpNeqB: {boolean, lt | gt},
1213
1214 OpLess8: {signed, lt},
1215 OpLess8U: {unsigned, lt},
1216 OpLess16: {signed, lt},
1217 OpLess16U: {unsigned, lt},
1218 OpLess32: {signed, lt},
1219 OpLess32U: {unsigned, lt},
1220 OpLess64: {signed, lt},
1221 OpLess64U: {unsigned, lt},
1222
1223 OpLeq8: {signed, lt | eq},
1224 OpLeq8U: {unsigned, lt | eq},
1225 OpLeq16: {signed, lt | eq},
1226 OpLeq16U: {unsigned, lt | eq},
1227 OpLeq32: {signed, lt | eq},
1228 OpLeq32U: {unsigned, lt | eq},
1229 OpLeq64: {signed, lt | eq},
1230 OpLeq64U: {unsigned, lt | eq},
1231 }
1232 )
1233
1234 // cleanup returns the posets to the free list
1235 func (ft *factsTable) cleanup(f *Func) {
1236 for _, po := range []*poset{ft.orderS, ft.orderU} {
1237 // Make sure it's empty as it should be. A non-empty poset
1238 // might cause errors and miscompilations if reused.
1239 if checkEnabled {
1240 if err := po.CheckEmpty(); err != nil {
1241 f.Fatalf("poset not empty after function %s: %v", f.Name, err)
1242 }
1243 }
1244 f.retPoset(po)
1245 }
1246 f.Cache.freeLimitSlice(ft.limits)
1247 f.Cache.freeBoolSlice(ft.recurseCheck)
1248 if cap(ft.reusedTopoSortScoresTable) > 0 {
1249 f.Cache.freeUintSlice(ft.reusedTopoSortScoresTable)
1250 }
1251 }
1252
1253 // prove removes redundant BlockIf branches that can be inferred
1254 // from previous dominating comparisons.
1255 //
1256 // By far, the most common redundant pair are generated by bounds checking.
1257 // For example for the code:
1258 //
1259 // a[i] = 4
1260 // foo(a[i])
1261 //
1262 // The compiler will generate the following code:
1263 //
1264 // if i >= len(a) {
1265 // panic("not in bounds")
1266 // }
1267 // a[i] = 4
1268 // if i >= len(a) {
1269 // panic("not in bounds")
1270 // }
1271 // foo(a[i])
1272 //
1273 // The second comparison i >= len(a) is clearly redundant because if the
1274 // else branch of the first comparison is executed, we already know that i < len(a).
1275 // The code for the second panic can be removed.
1276 //
1277 // prove works by finding contradictions and trimming branches whose
1278 // conditions are unsatisfiable given the branches leading up to them.
1279 // It tracks a "fact table" of branch conditions. For each branching
1280 // block, it asserts the branch conditions that uniquely dominate that
1281 // block, and then separately asserts the block's branch condition and
1282 // its negation. If either leads to a contradiction, it can trim that
1283 // successor.
1284 func prove(f *Func) {
1285 // Find induction variables. Currently, findIndVars
1286 // is limited to one induction variable per block.
1287 var indVars map[*Block]indVar
1288 for _, v := range findIndVar(f) {
1289 ind := v.ind
1290 if len(ind.Args) != 2 {
1291 // the rewrite code assumes there is only ever two parents to loops
1292 panic("unexpected induction with too many parents")
1293 }
1294
1295 nxt := v.nxt
1296 if !(ind.Uses == 2 && // 2 used by comparison and next
1297 nxt.Uses == 1) { // 1 used by induction
1298 // ind or nxt is used inside the loop, add it for the facts table
1299 if indVars == nil {
1300 indVars = make(map[*Block]indVar)
1301 }
1302 indVars[v.entry] = v
1303 continue
1304 } else {
1305 // Since this induction variable is not used for anything but counting the iterations,
1306 // no point in putting it into the facts table.
1307 }
1308 }
1309
1310 ft := newFactsTable(f)
1311 ft.checkpoint()
1312
1313 // Find length and capacity ops.
1314 for _, b := range f.Blocks {
1315 for _, v := range b.Values {
1316 if v.Uses == 0 {
1317 // We don't care about dead values.
1318 // (There can be some that are CSEd but not removed yet.)
1319 continue
1320 }
1321 switch v.Op {
1322 case OpSliceLen:
1323 if ft.lens == nil {
1324 ft.lens = map[ID]*Value{}
1325 }
1326 // Set all len Values for the same slice as equal in the poset.
1327 // The poset handles transitive relations, so Values related to
1328 // any OpSliceLen for this slice will be correctly related to others.
1329 if l, ok := ft.lens[v.Args[0].ID]; ok {
1330 ft.update(b, v, l, signed, eq)
1331 } else {
1332 ft.lens[v.Args[0].ID] = v
1333 }
1334 case OpSliceCap:
1335 if ft.caps == nil {
1336 ft.caps = map[ID]*Value{}
1337 }
1338 // Same as case OpSliceLen above, but for slice cap.
1339 if c, ok := ft.caps[v.Args[0].ID]; ok {
1340 ft.update(b, v, c, signed, eq)
1341 } else {
1342 ft.caps[v.Args[0].ID] = v
1343 }
1344 }
1345 }
1346 }
1347
1348 // current node state
1349 type walkState int
1350 const (
1351 descend walkState = iota
1352 restore
1353 )
1354 // work maintains the DFS stack.
1355 type bp struct {
1356 block *Block // current handled block
1357 state walkState // what's to do
1358 }
1359 work := make([]bp, 0, 256)
1360 work = append(work, bp{
1361 block: f.Entry,
1362 state: descend,
1363 })
1364
1365 idom := f.Idom()
1366 sdom := f.Sdom()
1367
1368 // DFS on the dominator tree.
1369 //
1370 // For efficiency, we consider only the dominator tree rather
1371 // than the entire flow graph. On the way down, we consider
1372 // incoming branches and accumulate conditions that uniquely
1373 // dominate the current block. If we discover a contradiction,
1374 // we can eliminate the entire block and all of its children.
1375 // On the way back up, we consider outgoing branches that
1376 // haven't already been considered. This way we consider each
1377 // branch condition only once.
1378 for len(work) > 0 {
1379 node := work[len(work)-1]
1380 work = work[:len(work)-1]
1381 parent := idom[node.block.ID]
1382 branch := getBranch(sdom, parent, node.block)
1383
1384 switch node.state {
1385 case descend:
1386 ft.checkpoint()
1387
1388 // Entering the block, add facts about the induction variable
1389 // that is bound to this block.
1390 if iv, ok := indVars[node.block]; ok {
1391 addIndVarRestrictions(ft, parent, iv)
1392 }
1393
1394 // Add results of reaching this block via a branch from
1395 // its immediate dominator (if any).
1396 if branch != unknown {
1397 addBranchRestrictions(ft, parent, branch)
1398 }
1399
1400 if ft.unsat {
1401 // node.block is unreachable.
1402 // Remove it and don't visit
1403 // its children.
1404 removeBranch(parent, branch)
1405 ft.restore()
1406 break
1407 }
1408 // Otherwise, we can now commit to
1409 // taking this branch. We'll restore
1410 // ft when we unwind.
1411
1412 ft.topoSortValuesInBlock(node.block)
1413
1414 for _, v := range node.block.Values {
1415 ft.flowLimit(v)
1416 // constant fold arguments before addValueFact to avoid v's v.Args learned facts time traveling into v's arguments.
1417 // in other words if v teaches us something about it's arguments,
1418 // we can't use that to optimize v's arguments since v hasn't ran yet.
1419 ft.constantFoldArguments(v)
1420 ft.addValueFact(node.block, v)
1421 ft.simplifyValue(node.block, v)
1422 }
1423
1424 ft.simplifyBlock(sdom, node.block)
1425
1426 work = append(work, bp{
1427 block: node.block,
1428 state: restore,
1429 })
1430 for s := sdom.Child(node.block); s != nil; s = sdom.Sibling(s) {
1431 work = append(work, bp{
1432 block: s,
1433 state: descend,
1434 })
1435 }
1436
1437 case restore:
1438 ft.restore()
1439 }
1440 }
1441
1442 ft.restore()
1443
1444 ft.cleanup(f)
1445 }
1446
1447 // initLimit sets initial constant limit for v. This limit is based
1448 // only on the operation itself, not any of its input arguments. This
1449 // method is only used in two places, once when the prove pass startup
1450 // and the other when a new ssa value is created, both for init. (unlike
1451 // flowLimit, below, which computes additional constraints based on
1452 // ranges of opcode arguments).
1453 func initLimit(v *Value) limit {
1454 if v.Type.IsBoolean() {
1455 switch v.Op {
1456 case OpConstBool:
1457 b := v.AuxInt
1458 return limit{min: b, max: b, umin: uint64(b), umax: uint64(b)}
1459 default:
1460 return limit{min: 0, max: 1, umin: 0, umax: 1}
1461 }
1462 }
1463 if v.Type.IsPtrShaped() { // These are the types that EqPtr/NeqPtr operate on, except uintptr.
1464 switch v.Op {
1465 case OpConstNil:
1466 return limit{min: 0, max: 0, umin: 0, umax: 0}
1467 case OpAddr, OpLocalAddr: // TODO: others?
1468 l := noLimit
1469 l.umin = 1
1470 return l
1471 default:
1472 return noLimit
1473 }
1474 }
1475 if !v.Type.IsInteger() {
1476 return noLimit
1477 }
1478
1479 // Default limits based on type.
1480 bitsize := v.Type.Size() * 8
1481 lim := limit{min: -(1 << (bitsize - 1)), max: 1<<(bitsize-1) - 1, umin: 0, umax: 1<<bitsize - 1}
1482
1483 // Tighter limits on some opcodes.
1484 switch v.Op {
1485 // constants
1486 case OpConst64:
1487 lim = limit{min: v.AuxInt, max: v.AuxInt, umin: uint64(v.AuxInt), umax: uint64(v.AuxInt)}
1488 case OpConst32:
1489 lim = limit{min: v.AuxInt, max: v.AuxInt, umin: uint64(uint32(v.AuxInt)), umax: uint64(uint32(v.AuxInt))}
1490 case OpConst16:
1491 lim = limit{min: v.AuxInt, max: v.AuxInt, umin: uint64(uint16(v.AuxInt)), umax: uint64(uint16(v.AuxInt))}
1492 case OpConst8:
1493 lim = limit{min: v.AuxInt, max: v.AuxInt, umin: uint64(uint8(v.AuxInt)), umax: uint64(uint8(v.AuxInt))}
1494
1495 // extensions
1496 case OpZeroExt8to64, OpZeroExt8to32, OpZeroExt8to16:
1497 lim = lim.signedMinMax(0, 1<<8-1)
1498 lim = lim.unsignedMax(1<<8 - 1)
1499 case OpZeroExt16to64, OpZeroExt16to32:
1500 lim = lim.signedMinMax(0, 1<<16-1)
1501 lim = lim.unsignedMax(1<<16 - 1)
1502 case OpZeroExt32to64:
1503 lim = lim.signedMinMax(0, 1<<32-1)
1504 lim = lim.unsignedMax(1<<32 - 1)
1505 case OpSignExt8to64, OpSignExt8to32, OpSignExt8to16:
1506 lim = lim.signedMinMax(math.MinInt8, math.MaxInt8)
1507 case OpSignExt16to64, OpSignExt16to32:
1508 lim = lim.signedMinMax(math.MinInt16, math.MaxInt16)
1509 case OpSignExt32to64:
1510 lim = lim.signedMinMax(math.MinInt32, math.MaxInt32)
1511
1512 // math/bits intrinsics
1513 case OpCtz64, OpBitLen64, OpPopCount64,
1514 OpCtz32, OpBitLen32, OpPopCount32,
1515 OpCtz16, OpBitLen16, OpPopCount16,
1516 OpCtz8, OpBitLen8, OpPopCount8:
1517 lim = lim.unsignedMax(uint64(v.Args[0].Type.Size() * 8))
1518
1519 // bool to uint8 conversion
1520 case OpCvtBoolToUint8:
1521 lim = lim.unsignedMax(1)
1522
1523 // length operations
1524 case OpStringLen, OpSliceLen, OpSliceCap:
1525 lim = lim.signedMin(0)
1526 }
1527
1528 // signed <-> unsigned propagation
1529 if lim.min >= 0 {
1530 lim = lim.unsignedMinMax(uint64(lim.min), uint64(lim.max))
1531 }
1532 if fitsInBitsU(lim.umax, uint(8*v.Type.Size()-1)) {
1533 lim = lim.signedMinMax(int64(lim.umin), int64(lim.umax))
1534 }
1535
1536 return lim
1537 }
1538
1539 // flowLimit updates the known limits of v in ft. Returns true if anything changed.
1540 // flowLimit can use the ranges of input arguments.
1541 //
1542 // Note: this calculation only happens at the point the value is defined. We do not reevaluate
1543 // it later. So for example:
1544 //
1545 // v := x + y
1546 // if 0 <= x && x < 5 && 0 <= y && y < 5 { ... use v ... }
1547 //
1548 // we don't discover that the range of v is bounded in the conditioned
1549 // block. We could recompute the range of v once we enter the block so
1550 // we know that it is 0 <= v <= 8, but we don't have a mechanism to do
1551 // that right now.
1552 func (ft *factsTable) flowLimit(v *Value) bool {
1553 if !v.Type.IsInteger() {
1554 // TODO: boolean?
1555 return false
1556 }
1557
1558 // Additional limits based on opcode and argument.
1559 // No need to repeat things here already done in initLimit.
1560 switch v.Op {
1561
1562 // extensions
1563 case OpZeroExt8to64, OpZeroExt8to32, OpZeroExt8to16, OpZeroExt16to64, OpZeroExt16to32, OpZeroExt32to64:
1564 a := ft.limits[v.Args[0].ID]
1565 return ft.unsignedMinMax(v, a.umin, a.umax)
1566 case OpSignExt8to64, OpSignExt8to32, OpSignExt8to16, OpSignExt16to64, OpSignExt16to32, OpSignExt32to64:
1567 a := ft.limits[v.Args[0].ID]
1568 return ft.signedMinMax(v, a.min, a.max)
1569 case OpTrunc64to8, OpTrunc64to16, OpTrunc64to32, OpTrunc32to8, OpTrunc32to16, OpTrunc16to8:
1570 a := ft.limits[v.Args[0].ID]
1571 if a.umax <= 1<<(uint64(v.Type.Size())*8)-1 {
1572 return ft.unsignedMinMax(v, a.umin, a.umax)
1573 }
1574
1575 // math/bits
1576 case OpCtz64:
1577 a := ft.limits[v.Args[0].ID]
1578 if a.nonzero() {
1579 return ft.unsignedMax(v, uint64(bits.Len64(a.umax)-1))
1580 }
1581 case OpCtz32:
1582 a := ft.limits[v.Args[0].ID]
1583 if a.nonzero() {
1584 return ft.unsignedMax(v, uint64(bits.Len32(uint32(a.umax))-1))
1585 }
1586 case OpCtz16:
1587 a := ft.limits[v.Args[0].ID]
1588 if a.nonzero() {
1589 return ft.unsignedMax(v, uint64(bits.Len16(uint16(a.umax))-1))
1590 }
1591 case OpCtz8:
1592 a := ft.limits[v.Args[0].ID]
1593 if a.nonzero() {
1594 return ft.unsignedMax(v, uint64(bits.Len8(uint8(a.umax))-1))
1595 }
1596
1597 case OpPopCount64, OpPopCount32, OpPopCount16, OpPopCount8:
1598 a := ft.limits[v.Args[0].ID]
1599 changingBitsCount := uint64(bits.Len64(a.umax ^ a.umin))
1600 sharedLeadingMask := ^(uint64(1)<<changingBitsCount - 1)
1601 fixedBits := a.umax & sharedLeadingMask
1602 min := uint64(bits.OnesCount64(fixedBits))
1603 return ft.unsignedMinMax(v, min, min+changingBitsCount)
1604
1605 case OpBitLen64:
1606 a := ft.limits[v.Args[0].ID]
1607 return ft.unsignedMinMax(v,
1608 uint64(bits.Len64(a.umin)),
1609 uint64(bits.Len64(a.umax)))
1610 case OpBitLen32:
1611 a := ft.limits[v.Args[0].ID]
1612 return ft.unsignedMinMax(v,
1613 uint64(bits.Len32(uint32(a.umin))),
1614 uint64(bits.Len32(uint32(a.umax))))
1615 case OpBitLen16:
1616 a := ft.limits[v.Args[0].ID]
1617 return ft.unsignedMinMax(v,
1618 uint64(bits.Len16(uint16(a.umin))),
1619 uint64(bits.Len16(uint16(a.umax))))
1620 case OpBitLen8:
1621 a := ft.limits[v.Args[0].ID]
1622 return ft.unsignedMinMax(v,
1623 uint64(bits.Len8(uint8(a.umin))),
1624 uint64(bits.Len8(uint8(a.umax))))
1625
1626 // Masks.
1627
1628 // TODO: if y.umax and y.umin share a leading bit pattern, y also has that leading bit pattern.
1629 // we could compare the patterns of always set bits in a and b and learn more about minimum and maximum.
1630 // But I doubt this help any real world code.
1631 case OpAnd64, OpAnd32, OpAnd16, OpAnd8:
1632 // AND can only make the value smaller.
1633 a := ft.limits[v.Args[0].ID]
1634 b := ft.limits[v.Args[1].ID]
1635 return ft.unsignedMax(v, min(a.umax, b.umax))
1636 case OpOr64, OpOr32, OpOr16, OpOr8:
1637 // OR can only make the value bigger and can't flip bits proved to be zero in both inputs.
1638 a := ft.limits[v.Args[0].ID]
1639 b := ft.limits[v.Args[1].ID]
1640 return ft.unsignedMinMax(v,
1641 max(a.umin, b.umin),
1642 1<<bits.Len64(a.umax|b.umax)-1)
1643 case OpXor64, OpXor32, OpXor16, OpXor8:
1644 // XOR can't flip bits that are proved to be zero in both inputs.
1645 a := ft.limits[v.Args[0].ID]
1646 b := ft.limits[v.Args[1].ID]
1647 return ft.unsignedMax(v, 1<<bits.Len64(a.umax|b.umax)-1)
1648 case OpCom64, OpCom32, OpCom16, OpCom8:
1649 a := ft.limits[v.Args[0].ID]
1650 return ft.newLimit(v, a.com(uint(v.Type.Size())*8))
1651
1652 // Arithmetic.
1653 case OpAdd64, OpAdd32, OpAdd16, OpAdd8:
1654 a := ft.limits[v.Args[0].ID]
1655 b := ft.limits[v.Args[1].ID]
1656 return ft.newLimit(v, a.add(b, uint(v.Type.Size())*8))
1657 case OpSub64, OpSub32, OpSub16, OpSub8:
1658 a := ft.limits[v.Args[0].ID]
1659 b := ft.limits[v.Args[1].ID]
1660 sub := ft.newLimit(v, a.sub(b, uint(v.Type.Size())*8))
1661 mod := ft.detectSignedMod(v)
1662 return sub || mod
1663 case OpNeg64, OpNeg32, OpNeg16, OpNeg8:
1664 a := ft.limits[v.Args[0].ID]
1665 bitsize := uint(v.Type.Size()) * 8
1666 return ft.newLimit(v, a.com(bitsize).add(limit{min: 1, max: 1, umin: 1, umax: 1}, bitsize))
1667 case OpMul64, OpMul32, OpMul16, OpMul8:
1668 a := ft.limits[v.Args[0].ID]
1669 b := ft.limits[v.Args[1].ID]
1670 return ft.newLimit(v, a.mul(b, uint(v.Type.Size())*8))
1671 case OpLsh64x64, OpLsh64x32, OpLsh64x16, OpLsh64x8,
1672 OpLsh32x64, OpLsh32x32, OpLsh32x16, OpLsh32x8,
1673 OpLsh16x64, OpLsh16x32, OpLsh16x16, OpLsh16x8,
1674 OpLsh8x64, OpLsh8x32, OpLsh8x16, OpLsh8x8:
1675 a := ft.limits[v.Args[0].ID]
1676 b := ft.limits[v.Args[1].ID]
1677 bitsize := uint(v.Type.Size()) * 8
1678 return ft.newLimit(v, a.mul(b.exp2(bitsize), bitsize))
1679 case OpMod64, OpMod32, OpMod16, OpMod8:
1680 a := ft.limits[v.Args[0].ID]
1681 b := ft.limits[v.Args[1].ID]
1682 if !(a.nonnegative() && b.nonnegative()) {
1683 // TODO: we could handle signed limits but I didn't bother.
1684 break
1685 }
1686 fallthrough
1687 case OpMod64u, OpMod32u, OpMod16u, OpMod8u:
1688 a := ft.limits[v.Args[0].ID]
1689 b := ft.limits[v.Args[1].ID]
1690 // Underflow in the arithmetic below is ok, it gives to MaxUint64 which does nothing to the limit.
1691 return ft.unsignedMax(v, min(a.umax, b.umax-1))
1692 case OpDiv64, OpDiv32, OpDiv16, OpDiv8:
1693 a := ft.limits[v.Args[0].ID]
1694 b := ft.limits[v.Args[1].ID]
1695 if !(a.nonnegative() && b.nonnegative()) {
1696 // TODO: we could handle signed limits but I didn't bother.
1697 break
1698 }
1699 fallthrough
1700 case OpDiv64u, OpDiv32u, OpDiv16u, OpDiv8u:
1701 a := ft.limits[v.Args[0].ID]
1702 b := ft.limits[v.Args[1].ID]
1703 lim := noLimit
1704 if b.umax > 0 {
1705 lim = lim.unsignedMin(a.umin / b.umax)
1706 }
1707 if b.umin > 0 {
1708 lim = lim.unsignedMax(a.umax / b.umin)
1709 }
1710 return ft.newLimit(v, lim)
1711
1712 case OpPhi:
1713 {
1714 // Work around for go.dev/issue/68857, look for min(x, y) and max(x, y).
1715 b := v.Block
1716 if len(b.Preds) != 2 {
1717 goto notMinNorMax
1718 }
1719 // FIXME: this code searches for the following losange pattern
1720 // because that what ssagen produce for min and max builtins:
1721 // conditionBlock → (firstBlock, secondBlock) → v.Block
1722 // there are three non losange equivalent constructions
1723 // we could match for, but I didn't bother:
1724 // conditionBlock → (v.Block, secondBlock → v.Block)
1725 // conditionBlock → (firstBlock → v.Block, v.Block)
1726 // conditionBlock → (v.Block, v.Block)
1727 firstBlock, secondBlock := b.Preds[0].b, b.Preds[1].b
1728 if firstBlock.Kind != BlockPlain || secondBlock.Kind != BlockPlain {
1729 goto notMinNorMax
1730 }
1731 if len(firstBlock.Preds) != 1 || len(secondBlock.Preds) != 1 {
1732 goto notMinNorMax
1733 }
1734 conditionBlock := firstBlock.Preds[0].b
1735 if conditionBlock != secondBlock.Preds[0].b {
1736 goto notMinNorMax
1737 }
1738 if conditionBlock.Kind != BlockIf {
1739 goto notMinNorMax
1740 }
1741
1742 less := conditionBlock.Controls[0]
1743 var unsigned bool
1744 switch less.Op {
1745 case OpLess64U, OpLess32U, OpLess16U, OpLess8U,
1746 OpLeq64U, OpLeq32U, OpLeq16U, OpLeq8U:
1747 unsigned = true
1748 case OpLess64, OpLess32, OpLess16, OpLess8,
1749 OpLeq64, OpLeq32, OpLeq16, OpLeq8:
1750 default:
1751 goto notMinNorMax
1752 }
1753 small, big := less.Args[0], less.Args[1]
1754 truev, falsev := v.Args[0], v.Args[1]
1755 if conditionBlock.Succs[0].b == secondBlock {
1756 truev, falsev = falsev, truev
1757 }
1758
1759 bigl, smalll := ft.limits[big.ID], ft.limits[small.ID]
1760 if truev == big {
1761 if falsev == small {
1762 // v := big if small <¿=? big else small
1763 if unsigned {
1764 maximum := max(bigl.umax, smalll.umax)
1765 minimum := max(bigl.umin, smalll.umin)
1766 return ft.unsignedMinMax(v, minimum, maximum)
1767 } else {
1768 maximum := max(bigl.max, smalll.max)
1769 minimum := max(bigl.min, smalll.min)
1770 return ft.signedMinMax(v, minimum, maximum)
1771 }
1772 } else {
1773 goto notMinNorMax
1774 }
1775 } else if truev == small {
1776 if falsev == big {
1777 // v := small if small <¿=? big else big
1778 if unsigned {
1779 maximum := min(bigl.umax, smalll.umax)
1780 minimum := min(bigl.umin, smalll.umin)
1781 return ft.unsignedMinMax(v, minimum, maximum)
1782 } else {
1783 maximum := min(bigl.max, smalll.max)
1784 minimum := min(bigl.min, smalll.min)
1785 return ft.signedMinMax(v, minimum, maximum)
1786 }
1787 } else {
1788 goto notMinNorMax
1789 }
1790 } else {
1791 goto notMinNorMax
1792 }
1793 }
1794 notMinNorMax:
1795
1796 // Compute the union of all the input phis.
1797 // Often this will convey no information, because the block
1798 // is not dominated by its predecessors and hence the
1799 // phi arguments might not have been processed yet. But if
1800 // the values are declared earlier, it may help. e.g., for
1801 // v = phi(c3, c5)
1802 // where c3 = OpConst [3] and c5 = OpConst [5] are
1803 // defined in the entry block, we can derive [3,5]
1804 // as the limit for v.
1805 l := ft.limits[v.Args[0].ID]
1806 for _, a := range v.Args[1:] {
1807 l2 := ft.limits[a.ID]
1808 l.min = min(l.min, l2.min)
1809 l.max = max(l.max, l2.max)
1810 l.umin = min(l.umin, l2.umin)
1811 l.umax = max(l.umax, l2.umax)
1812 }
1813 return ft.newLimit(v, l)
1814 }
1815 return false
1816 }
1817
1818 // See if we can get any facts because v is the result of signed mod by a constant.
1819 // The mod operation has already been rewritten, so we have to try and reconstruct it.
1820 //
1821 // x % d
1822 //
1823 // is rewritten as
1824 //
1825 // x - (x / d) * d
1826 //
1827 // furthermore, the divide itself gets rewritten. If d is a power of 2 (d == 1<<k), we do
1828 //
1829 // (x / d) * d = ((x + adj) >> k) << k
1830 // = (x + adj) & (-1<<k)
1831 //
1832 // with adj being an adjustment in case x is negative (see below).
1833 // if d is not a power of 2, we do
1834 //
1835 // x / d = ... TODO ...
1836 func (ft *factsTable) detectSignedMod(v *Value) bool {
1837 if ft.detectSignedModByPowerOfTwo(v) {
1838 return true
1839 }
1840 // TODO: non-powers-of-2
1841 return false
1842 }
1843 func (ft *factsTable) detectSignedModByPowerOfTwo(v *Value) bool {
1844 // We're looking for:
1845 //
1846 // x % d ==
1847 // x - (x / d) * d
1848 //
1849 // which for d a power of 2, d == 1<<k, is done as
1850 //
1851 // x - ((x + (x>>(w-1))>>>(w-k)) & (-1<<k))
1852 //
1853 // w = bit width of x.
1854 // (>> = signed shift, >>> = unsigned shift).
1855 // See ./_gen/generic.rules, search for "Signed divide by power of 2".
1856
1857 var w int64
1858 var addOp, andOp, constOp, sshiftOp, ushiftOp Op
1859 switch v.Op {
1860 case OpSub64:
1861 w = 64
1862 addOp = OpAdd64
1863 andOp = OpAnd64
1864 constOp = OpConst64
1865 sshiftOp = OpRsh64x64
1866 ushiftOp = OpRsh64Ux64
1867 case OpSub32:
1868 w = 32
1869 addOp = OpAdd32
1870 andOp = OpAnd32
1871 constOp = OpConst32
1872 sshiftOp = OpRsh32x64
1873 ushiftOp = OpRsh32Ux64
1874 case OpSub16:
1875 w = 16
1876 addOp = OpAdd16
1877 andOp = OpAnd16
1878 constOp = OpConst16
1879 sshiftOp = OpRsh16x64
1880 ushiftOp = OpRsh16Ux64
1881 case OpSub8:
1882 w = 8
1883 addOp = OpAdd8
1884 andOp = OpAnd8
1885 constOp = OpConst8
1886 sshiftOp = OpRsh8x64
1887 ushiftOp = OpRsh8Ux64
1888 default:
1889 return false
1890 }
1891
1892 x := v.Args[0]
1893 and := v.Args[1]
1894 if and.Op != andOp {
1895 return false
1896 }
1897 var add, mask *Value
1898 if and.Args[0].Op == addOp && and.Args[1].Op == constOp {
1899 add = and.Args[0]
1900 mask = and.Args[1]
1901 } else if and.Args[1].Op == addOp && and.Args[0].Op == constOp {
1902 add = and.Args[1]
1903 mask = and.Args[0]
1904 } else {
1905 return false
1906 }
1907 var ushift *Value
1908 if add.Args[0] == x {
1909 ushift = add.Args[1]
1910 } else if add.Args[1] == x {
1911 ushift = add.Args[0]
1912 } else {
1913 return false
1914 }
1915 if ushift.Op != ushiftOp {
1916 return false
1917 }
1918 if ushift.Args[1].Op != OpConst64 {
1919 return false
1920 }
1921 k := w - ushift.Args[1].AuxInt // Now we know k!
1922 d := int64(1) << k // divisor
1923 sshift := ushift.Args[0]
1924 if sshift.Op != sshiftOp {
1925 return false
1926 }
1927 if sshift.Args[0] != x {
1928 return false
1929 }
1930 if sshift.Args[1].Op != OpConst64 || sshift.Args[1].AuxInt != w-1 {
1931 return false
1932 }
1933 if mask.AuxInt != -d {
1934 return false
1935 }
1936
1937 // All looks ok. x % d is at most +/- d-1.
1938 return ft.signedMinMax(v, -d+1, d-1)
1939 }
1940
1941 // getBranch returns the range restrictions added by p
1942 // when reaching b. p is the immediate dominator of b.
1943 func getBranch(sdom SparseTree, p *Block, b *Block) branch {
1944 if p == nil {
1945 return unknown
1946 }
1947 switch p.Kind {
1948 case BlockIf:
1949 // If p and p.Succs[0] are dominators it means that every path
1950 // from entry to b passes through p and p.Succs[0]. We care that
1951 // no path from entry to b passes through p.Succs[1]. If p.Succs[0]
1952 // has one predecessor then (apart from the degenerate case),
1953 // there is no path from entry that can reach b through p.Succs[1].
1954 // TODO: how about p->yes->b->yes, i.e. a loop in yes.
1955 if sdom.IsAncestorEq(p.Succs[0].b, b) && len(p.Succs[0].b.Preds) == 1 {
1956 return positive
1957 }
1958 if sdom.IsAncestorEq(p.Succs[1].b, b) && len(p.Succs[1].b.Preds) == 1 {
1959 return negative
1960 }
1961 case BlockJumpTable:
1962 // TODO: this loop can lead to quadratic behavior, as
1963 // getBranch can be called len(p.Succs) times.
1964 for i, e := range p.Succs {
1965 if sdom.IsAncestorEq(e.b, b) && len(e.b.Preds) == 1 {
1966 return jumpTable0 + branch(i)
1967 }
1968 }
1969 }
1970 return unknown
1971 }
1972
1973 // addIndVarRestrictions updates the factsTables ft with the facts
1974 // learned from the induction variable indVar which drives the loop
1975 // starting in Block b.
1976 func addIndVarRestrictions(ft *factsTable, b *Block, iv indVar) {
1977 d := signed
1978 if ft.isNonNegative(iv.min) && ft.isNonNegative(iv.max) {
1979 d |= unsigned
1980 }
1981
1982 if iv.flags&indVarMinExc == 0 {
1983 addRestrictions(b, ft, d, iv.min, iv.ind, lt|eq)
1984 } else {
1985 addRestrictions(b, ft, d, iv.min, iv.ind, lt)
1986 }
1987
1988 if iv.flags&indVarMaxInc == 0 {
1989 addRestrictions(b, ft, d, iv.ind, iv.max, lt)
1990 } else {
1991 addRestrictions(b, ft, d, iv.ind, iv.max, lt|eq)
1992 }
1993 }
1994
1995 // addBranchRestrictions updates the factsTables ft with the facts learned when
1996 // branching from Block b in direction br.
1997 func addBranchRestrictions(ft *factsTable, b *Block, br branch) {
1998 c := b.Controls[0]
1999 switch {
2000 case br == negative:
2001 ft.booleanFalse(c)
2002 case br == positive:
2003 ft.booleanTrue(c)
2004 case br >= jumpTable0:
2005 idx := br - jumpTable0
2006 val := int64(idx)
2007 if v, off := isConstDelta(c); v != nil {
2008 // Establish the bound on the underlying value we're switching on,
2009 // not on the offset-ed value used as the jump table index.
2010 c = v
2011 val -= off
2012 }
2013 ft.newLimit(c, limit{min: val, max: val, umin: uint64(val), umax: uint64(val)})
2014 default:
2015 panic("unknown branch")
2016 }
2017 }
2018
2019 // addRestrictions updates restrictions from the immediate
2020 // dominating block (p) using r.
2021 func addRestrictions(parent *Block, ft *factsTable, t domain, v, w *Value, r relation) {
2022 if t == 0 {
2023 // Trivial case: nothing to do.
2024 // Should not happen, but just in case.
2025 return
2026 }
2027 for i := domain(1); i <= t; i <<= 1 {
2028 if t&i == 0 {
2029 continue
2030 }
2031 ft.update(parent, v, w, i, r)
2032 }
2033 }
2034
2035 func (ft *factsTable) addValueFact(b *Block, v *Value) {
2036 switch v.Op {
2037 case OpAnd64, OpAnd32, OpAnd16, OpAnd8:
2038 ft.update(b, v, v.Args[0], unsigned, lt|eq)
2039 ft.update(b, v, v.Args[1], unsigned, lt|eq)
2040 if ft.isNonNegative(v.Args[0]) {
2041 ft.update(b, v, v.Args[0], signed, lt|eq)
2042 }
2043 if ft.isNonNegative(v.Args[1]) {
2044 ft.update(b, v, v.Args[1], signed, lt|eq)
2045 }
2046 case OpOr64, OpOr32, OpOr16, OpOr8:
2047 // TODO: investigate how to always add facts without much slowdown, see issue #57959
2048 //ft.update(b, v, v.Args[0], unsigned, gt|eq)
2049 //ft.update(b, v, v.Args[1], unsigned, gt|eq)
2050 case OpDiv64u, OpDiv32u, OpDiv16u, OpDiv8u,
2051 OpRsh8Ux64, OpRsh8Ux32, OpRsh8Ux16, OpRsh8Ux8,
2052 OpRsh16Ux64, OpRsh16Ux32, OpRsh16Ux16, OpRsh16Ux8,
2053 OpRsh32Ux64, OpRsh32Ux32, OpRsh32Ux16, OpRsh32Ux8,
2054 OpRsh64Ux64, OpRsh64Ux32, OpRsh64Ux16, OpRsh64Ux8:
2055 ft.update(b, v, v.Args[0], unsigned, lt|eq)
2056 case OpMod64u, OpMod32u, OpMod16u, OpMod8u:
2057 ft.update(b, v, v.Args[0], unsigned, lt|eq)
2058 // Note: we have to be careful that this doesn't imply
2059 // that the modulus is >0, which isn't true until *after*
2060 // the mod instruction executes (and thus panics if the
2061 // modulus is 0). See issue 67625.
2062 ft.update(b, v, v.Args[1], unsigned, lt)
2063 case OpSliceLen:
2064 if v.Args[0].Op == OpSliceMake {
2065 ft.update(b, v, v.Args[0].Args[1], signed, eq)
2066 }
2067 case OpSliceCap:
2068 if v.Args[0].Op == OpSliceMake {
2069 ft.update(b, v, v.Args[0].Args[2], signed, eq)
2070 }
2071 case OpPhi:
2072 addLocalFactsPhi(ft, v)
2073 }
2074 }
2075
2076 func addLocalFactsPhi(ft *factsTable, v *Value) {
2077 // Look for phis that implement min/max.
2078 // z:
2079 // c = Less64 x y (or other Less/Leq operation)
2080 // If c -> bx by
2081 // bx: <- z
2082 // -> b ...
2083 // by: <- z
2084 // -> b ...
2085 // b: <- bx by
2086 // v = Phi x y
2087 // Then v is either min or max of x,y.
2088 // If it is the min, then we deduce v <= x && v <= y.
2089 // If it is the max, then we deduce v >= x && v >= y.
2090 // The min case is useful for the copy builtin, see issue 16833.
2091 if len(v.Args) != 2 {
2092 return
2093 }
2094 b := v.Block
2095 x := v.Args[0]
2096 y := v.Args[1]
2097 bx := b.Preds[0].b
2098 by := b.Preds[1].b
2099 var z *Block // branch point
2100 switch {
2101 case bx == by: // bx == by == z case
2102 z = bx
2103 case by.uniquePred() == bx: // bx == z case
2104 z = bx
2105 case bx.uniquePred() == by: // by == z case
2106 z = by
2107 case bx.uniquePred() == by.uniquePred():
2108 z = bx.uniquePred()
2109 }
2110 if z == nil || z.Kind != BlockIf {
2111 return
2112 }
2113 c := z.Controls[0]
2114 if len(c.Args) != 2 {
2115 return
2116 }
2117 var isMin bool // if c, a less-than comparison, is true, phi chooses x.
2118 if bx == z {
2119 isMin = b.Preds[0].i == 0
2120 } else {
2121 isMin = bx.Preds[0].i == 0
2122 }
2123 if c.Args[0] == x && c.Args[1] == y {
2124 // ok
2125 } else if c.Args[0] == y && c.Args[1] == x {
2126 // Comparison is reversed from how the values are listed in the Phi.
2127 isMin = !isMin
2128 } else {
2129 // Not comparing x and y.
2130 return
2131 }
2132 var dom domain
2133 switch c.Op {
2134 case OpLess64, OpLess32, OpLess16, OpLess8, OpLeq64, OpLeq32, OpLeq16, OpLeq8:
2135 dom = signed
2136 case OpLess64U, OpLess32U, OpLess16U, OpLess8U, OpLeq64U, OpLeq32U, OpLeq16U, OpLeq8U:
2137 dom = unsigned
2138 default:
2139 return
2140 }
2141 var rel relation
2142 if isMin {
2143 rel = lt | eq
2144 } else {
2145 rel = gt | eq
2146 }
2147 ft.update(b, v, x, dom, rel)
2148 ft.update(b, v, y, dom, rel)
2149 }
2150
2151 var ctzNonZeroOp = map[Op]Op{OpCtz8: OpCtz8NonZero, OpCtz16: OpCtz16NonZero, OpCtz32: OpCtz32NonZero, OpCtz64: OpCtz64NonZero}
2152 var mostNegativeDividend = map[Op]int64{
2153 OpDiv16: -1 << 15,
2154 OpMod16: -1 << 15,
2155 OpDiv32: -1 << 31,
2156 OpMod32: -1 << 31,
2157 OpDiv64: -1 << 63,
2158 OpMod64: -1 << 63}
2159
2160 func (ft *factsTable) simplifyValue(b *Block, v *Value) {
2161 switch v.Op {
2162 case OpSlicemask:
2163 // Replace OpSlicemask operations in b with constants where possible.
2164 x, delta := isConstDelta(v.Args[0])
2165 if x == nil {
2166 break
2167 }
2168 // slicemask(x + y)
2169 // if x is larger than -y (y is negative), then slicemask is -1.
2170 lim := ft.limits[x.ID]
2171 if lim.umin > uint64(-delta) {
2172 if v.Type.Size() == 8 {
2173 v.reset(OpConst64)
2174 } else {
2175 v.reset(OpConst32)
2176 }
2177 if b.Func.pass.debug > 0 {
2178 b.Func.Warnl(v.Pos, "Proved slicemask not needed")
2179 }
2180 v.AuxInt = -1
2181 }
2182 case OpCtz8, OpCtz16, OpCtz32, OpCtz64:
2183 // On some architectures, notably amd64, we can generate much better
2184 // code for CtzNN if we know that the argument is non-zero.
2185 // Capture that information here for use in arch-specific optimizations.
2186 x := v.Args[0]
2187 lim := ft.limits[x.ID]
2188 if lim.umin > 0 || lim.min > 0 || lim.max < 0 {
2189 if b.Func.pass.debug > 0 {
2190 b.Func.Warnl(v.Pos, "Proved %v non-zero", v.Op)
2191 }
2192 v.Op = ctzNonZeroOp[v.Op]
2193 }
2194 case OpRsh8x8, OpRsh8x16, OpRsh8x32, OpRsh8x64,
2195 OpRsh16x8, OpRsh16x16, OpRsh16x32, OpRsh16x64,
2196 OpRsh32x8, OpRsh32x16, OpRsh32x32, OpRsh32x64,
2197 OpRsh64x8, OpRsh64x16, OpRsh64x32, OpRsh64x64:
2198 // Check whether, for a >> b, we know that a is non-negative
2199 // and b is all of a's bits except the MSB. If so, a is shifted to zero.
2200 bits := 8 * v.Args[0].Type.Size()
2201 if v.Args[1].isGenericIntConst() && v.Args[1].AuxInt >= bits-1 && ft.isNonNegative(v.Args[0]) {
2202 if b.Func.pass.debug > 0 {
2203 b.Func.Warnl(v.Pos, "Proved %v shifts to zero", v.Op)
2204 }
2205 switch bits {
2206 case 64:
2207 v.reset(OpConst64)
2208 case 32:
2209 v.reset(OpConst32)
2210 case 16:
2211 v.reset(OpConst16)
2212 case 8:
2213 v.reset(OpConst8)
2214 default:
2215 panic("unexpected integer size")
2216 }
2217 v.AuxInt = 0
2218 break // Be sure not to fallthrough - this is no longer OpRsh.
2219 }
2220 // If the Rsh hasn't been replaced with 0, still check if it is bounded.
2221 fallthrough
2222 case OpLsh8x8, OpLsh8x16, OpLsh8x32, OpLsh8x64,
2223 OpLsh16x8, OpLsh16x16, OpLsh16x32, OpLsh16x64,
2224 OpLsh32x8, OpLsh32x16, OpLsh32x32, OpLsh32x64,
2225 OpLsh64x8, OpLsh64x16, OpLsh64x32, OpLsh64x64,
2226 OpRsh8Ux8, OpRsh8Ux16, OpRsh8Ux32, OpRsh8Ux64,
2227 OpRsh16Ux8, OpRsh16Ux16, OpRsh16Ux32, OpRsh16Ux64,
2228 OpRsh32Ux8, OpRsh32Ux16, OpRsh32Ux32, OpRsh32Ux64,
2229 OpRsh64Ux8, OpRsh64Ux16, OpRsh64Ux32, OpRsh64Ux64:
2230 // Check whether, for a << b, we know that b
2231 // is strictly less than the number of bits in a.
2232 by := v.Args[1]
2233 lim := ft.limits[by.ID]
2234 bits := 8 * v.Args[0].Type.Size()
2235 if lim.umax < uint64(bits) || (lim.max < bits && ft.isNonNegative(by)) {
2236 v.AuxInt = 1 // see shiftIsBounded
2237 if b.Func.pass.debug > 0 && !by.isGenericIntConst() {
2238 b.Func.Warnl(v.Pos, "Proved %v bounded", v.Op)
2239 }
2240 }
2241 case OpDiv16, OpDiv32, OpDiv64, OpMod16, OpMod32, OpMod64:
2242 // On amd64 and 386 fix-up code can be avoided if we know
2243 // the divisor is not -1 or the dividend > MinIntNN.
2244 // Don't modify AuxInt on other architectures,
2245 // as that can interfere with CSE.
2246 // TODO: add other architectures?
2247 if b.Func.Config.arch != "386" && b.Func.Config.arch != "amd64" {
2248 break
2249 }
2250 divr := v.Args[1]
2251 divrLim := ft.limits[divr.ID]
2252 divd := v.Args[0]
2253 divdLim := ft.limits[divd.ID]
2254 if divrLim.max < -1 || divrLim.min > -1 || divdLim.min > mostNegativeDividend[v.Op] {
2255 // See DivisionNeedsFixUp in rewrite.go.
2256 // v.AuxInt = 1 means we have proved both that the divisor is not -1
2257 // and that the dividend is not the most negative integer,
2258 // so we do not need to add fix-up code.
2259 v.AuxInt = 1
2260 if b.Func.pass.debug > 0 {
2261 b.Func.Warnl(v.Pos, "Proved %v does not need fix-up", v.Op)
2262 }
2263 }
2264 }
2265 }
2266
2267 func (ft *factsTable) constantFoldArguments(v *Value) {
2268 for i, arg := range v.Args {
2269 lim := ft.limits[arg.ID]
2270 var constValue int64
2271 switch {
2272 case lim.min == lim.max:
2273 constValue = lim.min
2274 case lim.umin == lim.umax:
2275 constValue = int64(lim.umin)
2276 default:
2277 continue
2278 }
2279 switch arg.Op {
2280 case OpConst64, OpConst32, OpConst16, OpConst8, OpConstBool, OpConstNil:
2281 continue
2282 }
2283 typ := arg.Type
2284 f := v.Block.Func
2285 var c *Value
2286 switch {
2287 case typ.IsBoolean():
2288 c = f.ConstBool(typ, constValue != 0)
2289 case typ.IsInteger() && typ.Size() == 1:
2290 c = f.ConstInt8(typ, int8(constValue))
2291 case typ.IsInteger() && typ.Size() == 2:
2292 c = f.ConstInt16(typ, int16(constValue))
2293 case typ.IsInteger() && typ.Size() == 4:
2294 c = f.ConstInt32(typ, int32(constValue))
2295 case typ.IsInteger() && typ.Size() == 8:
2296 c = f.ConstInt64(typ, constValue)
2297 case typ.IsPtrShaped():
2298 if constValue == 0 {
2299 c = f.ConstNil(typ)
2300 } else {
2301 // Not sure how this might happen, but if it
2302 // does, just skip it.
2303 continue
2304 }
2305 default:
2306 // Not sure how this might happen, but if it
2307 // does, just skip it.
2308 continue
2309 }
2310 v.SetArg(i, c)
2311 ft.initLimitForNewValue(c)
2312 if f.pass.debug > 1 {
2313 f.Warnl(v.Pos, "Proved %v's arg %d (%v) is constant %d", v, i, arg, constValue)
2314 }
2315 }
2316 }
2317
2318 func (ft *factsTable) simplifyBlock(sdom SparseTree, b *Block) {
2319 if b.Kind != BlockIf {
2320 return
2321 }
2322
2323 // Consider outgoing edges from this block.
2324 parent := b
2325 for i, branch := range [...]branch{positive, negative} {
2326 child := parent.Succs[i].b
2327 if getBranch(sdom, parent, child) != unknown {
2328 // For edges to uniquely dominated blocks, we
2329 // already did this when we visited the child.
2330 continue
2331 }
2332 // For edges to other blocks, this can trim a branch
2333 // even if we couldn't get rid of the child itself.
2334 ft.checkpoint()
2335 addBranchRestrictions(ft, parent, branch)
2336 unsat := ft.unsat
2337 ft.restore()
2338 if unsat {
2339 // This branch is impossible, so remove it
2340 // from the block.
2341 removeBranch(parent, branch)
2342 // No point in considering the other branch.
2343 // (It *is* possible for both to be
2344 // unsatisfiable since the fact table is
2345 // incomplete. We could turn this into a
2346 // BlockExit, but it doesn't seem worth it.)
2347 break
2348 }
2349 }
2350 }
2351
2352 func removeBranch(b *Block, branch branch) {
2353 c := b.Controls[0]
2354 if b.Func.pass.debug > 0 {
2355 verb := "Proved"
2356 if branch == positive {
2357 verb = "Disproved"
2358 }
2359 if b.Func.pass.debug > 1 {
2360 b.Func.Warnl(b.Pos, "%s %s (%s)", verb, c.Op, c)
2361 } else {
2362 b.Func.Warnl(b.Pos, "%s %s", verb, c.Op)
2363 }
2364 }
2365 if c != nil && c.Pos.IsStmt() == src.PosIsStmt && c.Pos.SameFileAndLine(b.Pos) {
2366 // attempt to preserve statement marker.
2367 b.Pos = b.Pos.WithIsStmt()
2368 }
2369 if branch == positive || branch == negative {
2370 b.Kind = BlockFirst
2371 b.ResetControls()
2372 if branch == positive {
2373 b.swapSuccessors()
2374 }
2375 } else {
2376 // TODO: figure out how to remove an entry from a jump table
2377 }
2378 }
2379
2380 // isConstDelta returns non-nil if v is equivalent to w+delta (signed).
2381 func isConstDelta(v *Value) (w *Value, delta int64) {
2382 cop := OpConst64
2383 switch v.Op {
2384 case OpAdd32, OpSub32:
2385 cop = OpConst32
2386 case OpAdd16, OpSub16:
2387 cop = OpConst16
2388 case OpAdd8, OpSub8:
2389 cop = OpConst8
2390 }
2391 switch v.Op {
2392 case OpAdd64, OpAdd32, OpAdd16, OpAdd8:
2393 if v.Args[0].Op == cop {
2394 return v.Args[1], v.Args[0].AuxInt
2395 }
2396 if v.Args[1].Op == cop {
2397 return v.Args[0], v.Args[1].AuxInt
2398 }
2399 case OpSub64, OpSub32, OpSub16, OpSub8:
2400 if v.Args[1].Op == cop {
2401 aux := v.Args[1].AuxInt
2402 if aux != -aux { // Overflow; too bad
2403 return v.Args[0], -aux
2404 }
2405 }
2406 }
2407 return nil, 0
2408 }
2409
2410 // isCleanExt reports whether v is the result of a value-preserving
2411 // sign or zero extension.
2412 func isCleanExt(v *Value) bool {
2413 switch v.Op {
2414 case OpSignExt8to16, OpSignExt8to32, OpSignExt8to64,
2415 OpSignExt16to32, OpSignExt16to64, OpSignExt32to64:
2416 // signed -> signed is the only value-preserving sign extension
2417 return v.Args[0].Type.IsSigned() && v.Type.IsSigned()
2418
2419 case OpZeroExt8to16, OpZeroExt8to32, OpZeroExt8to64,
2420 OpZeroExt16to32, OpZeroExt16to64, OpZeroExt32to64:
2421 // unsigned -> signed/unsigned are value-preserving zero extensions
2422 return !v.Args[0].Type.IsSigned()
2423 }
2424 return false
2425 }
2426
2427 func getDependencyScore(scores []uint, v *Value) (score uint) {
2428 if score = scores[v.ID]; score != 0 {
2429 return score
2430 }
2431 defer func() {
2432 scores[v.ID] = score
2433 }()
2434 if v.Op == OpPhi {
2435 return 1
2436 }
2437 score = 2 // NIT(@Jorropo): always order phis first to make GOSSAFUNC pretty.
2438 for _, a := range v.Args {
2439 if a.Block != v.Block {
2440 continue
2441 }
2442 score = max(score, getDependencyScore(scores, a)+1)
2443 }
2444 return score
2445 }
2446
2447 // topoSortValuesInBlock ensure ranging over b.Values visit values before they are being used.
2448 // It does not consider dependencies with other blocks; thus Phi nodes are considered to not have any dependecies.
2449 // The result is always determistic and does not depend on the previous slice ordering.
2450 func (ft *factsTable) topoSortValuesInBlock(b *Block) {
2451 f := b.Func
2452 want := f.NumValues()
2453
2454 scores := ft.reusedTopoSortScoresTable
2455 if len(scores) < want {
2456 if want <= cap(scores) {
2457 scores = scores[:want]
2458 } else {
2459 if cap(scores) > 0 {
2460 f.Cache.freeUintSlice(scores)
2461 }
2462 scores = f.Cache.allocUintSlice(want)
2463 ft.reusedTopoSortScoresTable = scores
2464 }
2465 }
2466
2467 for _, v := range b.Values {
2468 scores[v.ID] = 0 // sentinel
2469 }
2470
2471 slices.SortFunc(b.Values, func(a, b *Value) int {
2472 dependencyScoreA := getDependencyScore(scores, a)
2473 dependencyScoreB := getDependencyScore(scores, b)
2474 if dependencyScoreA != dependencyScoreB {
2475 return cmp.Compare(dependencyScoreA, dependencyScoreB)
2476 }
2477 return cmp.Compare(a.ID, b.ID)
2478 })
2479 }