Skip to content

Commit bbfa601

Browse files
aykevldeadprogram
authored andcommitted
compiler: avoid nil pointer checks with unsafe.Pointer
The unsafe.Pointer type is used for many low-level operations, especially in the runtime. It can for example be used to copy the contents of a slice (in the copy builtin) independent of the slice element type.
1 parent 19f8874 commit bbfa601

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

compiler/asserts.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,12 +158,21 @@ func (b *builder) createNilCheck(inst ssa.Value, ptr llvm.Value, blockPrefix str
158158
return
159159
}
160160

161-
switch inst.(type) {
161+
switch inst := inst.(type) {
162162
case *ssa.IndexAddr:
163163
// This pointer is the result of an index operation into a slice or
164164
// array. Such slices/arrays are already bounds checked so the pointer
165165
// must be a valid (non-nil) pointer. No nil checking is necessary.
166166
return
167+
case *ssa.Convert:
168+
// This is a pointer that comes from a conversion from unsafe.Pointer.
169+
// Don't do nil checking because this is unsafe code and the code should
170+
// know what it is doing.
171+
// Note: all *ssa.Convert instructions that result in a pointer must
172+
// come from unsafe.Pointer. Testing here for unsafe.Pointer to be sure.
173+
if inst.X.Type() == types.Typ[types.UnsafePointer] {
174+
return
175+
}
167176
}
168177

169178
// Compare against nil.

0 commit comments

Comments
 (0)