1
0
mirror of https://github.com/golang/go synced 2024-11-26 06:57:56 -07:00

unsafe.Sizeof and unsafe.Offsetof

R=r
OCL=24639
CL=24639
This commit is contained in:
Ken Thompson 2009-02-07 12:34:45 -08:00
parent bcf48076e5
commit 8a70545b57
4 changed files with 57 additions and 1 deletions

View File

@ -1483,3 +1483,54 @@ loop:
c = listnext(&citer);
goto loop;
}
/*
* look for
* unsafe.Sizeof
* unsafe.Offsetof
* rewrite with a constant
*/
Node*
unsafenmagic(Node *l, Node *r)
{
Node *n;
Sym *s;
long v;
Val val;
if(l == N || r == N)
goto no;
if(l->op != ONAME)
goto no;
s = l->sym;
if(s == S)
goto no;
if(strcmp(s->opackage, "unsafe") != 0)
goto no;
if(strcmp(s->name, "Sizeof") == 0) {
walktype(r, Erv);
if(r->type == T)
goto no;
v = r->type->width;
goto yes;
}
if(strcmp(s->name, "Offsetof") == 0) {
if(r->op != ODOT && r->op != ODOTPTR)
goto no;
walktype(r, Erv);
v = n->xoffset;
goto yes;
}
no:
return N;
yes:
val.ctype = CTINT;
val.u.xval = mal(sizeof(*n->val.u.xval));
mpmovecfix(val.u.xval, v);
n = nod(OLITERAL, N, N);
n->val = val;
return n;
}

View File

@ -763,6 +763,7 @@ void constiter(Node*, Type*, Node*);
void funclit0(Type*);
Node* funclit1(Type*, Node*);
Node* unsafenmagic(Node*, Node*);
/*
* export.c

View File

@ -804,6 +804,8 @@ pexpr:
}
| pexpr '(' oexpr_list ')'
{
$$ = unsafenmagic($1, $3);
if($$ == N)
$$ = nod(OCALL, $1, $3);
}
| LLEN '(' expr ')'

View File

@ -6,3 +6,5 @@
package PACKAGE
type Pointer *any;
func Offsetof(any) int;
func Sizeof(any) int;