Example #1
0
// defineLocal defines a variable at a function scope.
func (c *compiler) defineLocal(v *types.Var, lv *arch.LV) {
	val := c.cg.Label()
	lv.Addr = val
	c.cg.Data()

	intSize := c.cg.Int()
	ptrSize := c.cg.Pointer()
	size := 1

	typ := v.Type().Underlying()
	prim := primType(typ)
	array, isArray := typ.(*types.Array)
	isRecord := isRecord(typ, true)

	if isArray {
		size = int(array.Len())
	}

	init := 0
	if x := v.Value(); x != nil {
		init, _ = strconv.Atoi(x.String())
	}

	if !isArray && !isRecord {
		c.cg.Lab(val)
	}

	switch {
	case isRecord:
		c.cg.BSS(c.cg.Labname(val), c.cg.Sizeof(typ), true)

	case prim == types.Typ[types.Char]:
		if isArray {
			c.cg.BSS(c.cg.Labname(val), size, true)
		} else {
			c.cg.Defb(init)
			c.cg.Align(1, intSize)
		}

	case prim == types.Typ[types.Int]:
		if isArray {
			c.cg.BSS(c.cg.Labname(val), size*intSize, true)
		} else {
			c.cg.Defw(init)
		}

	default:
		if isArray {
			c.cg.BSS(c.cg.Labname(val), size*ptrSize, true)
		} else {
			c.cg.Defp(init)
		}
	}
}
Example #2
0
// defineGlobal defines a variable at the file scope level.
func (c *compiler) defineGlobal(v *types.Var) {
	storage := v.Storage()
	if storage != types.Public && storage != types.GlobalStatic {
		return
	}

	c.cg.Data()

	intSize := c.cg.Int()
	ptrSize := c.cg.Pointer()

	name := v.Name()
	gname := c.cg.Gsym(name)
	isStatic := storage == types.GlobalStatic
	if storage == types.Public {
		c.cg.Public(name)
	}

	typ := v.Type().Underlying()
	prim := primType(typ)
	array, isArray := typ.(*types.Array)
	isRecord := isRecord(typ, true)

	if !isArray && !isRecord {
		c.cg.Name(name)
	}

	size := 1
	if isArray {
		size = int(array.Len())
	}

	val := 0
	if x := v.Value(); x != nil {
		val, _ = strconv.Atoi(x.String())
	}

	switch {
	case isRecord:
		c.cg.BSS(gname, c.cg.Sizeof(typ), isStatic)
	case prim == types.Typ[types.Char]:
		if isArray {
			c.cg.BSS(gname, size, isStatic)
		} else {
			c.cg.Defb(val)
			c.cg.Align(1, intSize)
		}
	case prim == types.Typ[types.Int]:
		if isArray {
			c.cg.BSS(gname, size*intSize, isStatic)
		} else {
			c.cg.Defw(val)
		}
	default:
		if isArray {
			c.cg.BSS(gname, size*ptrSize, isStatic)
		} else {
			c.cg.Defp(val)
		}
	}
}