Skip to content

Commit

Permalink
feat: optimize bytestrings
Browse files Browse the repository at this point in the history
optimize bytestrings in both codesize and gas

store them in code, and CODECOPY to memory when needed instead of
inlining
  • Loading branch information
charles-cooper committed Jul 25, 2023
1 parent 408929f commit c5ad1d8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 21 deletions.
36 changes: 15 additions & 21 deletions vyper/codegen/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from vyper import ast as vy_ast
from vyper.codegen import external_call, self_call
from vyper.codegen.core import (
_freshname,
clamp,
ensure_in_memory,
get_dyn_array_count,
Expand Down Expand Up @@ -50,13 +51,7 @@
)
from vyper.semantics.types.bytestrings import _BytestringT
from vyper.semantics.types.shortcuts import BYTES32_T, UINT256_T
from vyper.utils import (
DECIMAL_DIVISOR,
bytes_to_int,
is_checksum_encoded,
string_to_bytes,
vyper_warn,
)
from vyper.utils import DECIMAL_DIVISOR, is_checksum_encoded, string_to_bytes, vyper_warn

ENVIRONMENT_VARIABLES = {"block", "msg", "tx", "chain"}

Expand Down Expand Up @@ -137,21 +132,20 @@ def parse_Bytes(self):

def _make_bytelike(self, btype, bytez, bytez_length):
placeholder = self.context.new_internal_variable(btype)
seq = []
seq.append(["mstore", placeholder, bytez_length])
for i in range(0, len(bytez), 32):
seq.append(
[
"mstore",
["add", placeholder, i + 32],
bytes_to_int((bytez + b"\x00" * 31)[i : i + 32]),
]
)
ret = ["seq"]
assert isinstance(bytez, bytes)
label = _freshname("bytesdata")
len_ = len(bytez)
# NOTE: addl opportunities for optimization:
# - intern repeated bytestrings
# - instantiate into memory lazily, pass around bytestring
# literals in IR.
ret.append(["data", label, bytez])
ret.append(["codecopy", placeholder + 32, ["symbol", label], len_])
ret.append(["mstore", placeholder, len_])
ret.append(placeholder)
return IRnode.from_list(
["seq"] + seq + [placeholder],
typ=btype,
location=MEMORY,
annotation=f"Create {btype}: {bytez}",
ret, typ=btype, location=MEMORY, annotation=f"Create {btype}: {repr(bytez)}"
)

# True, False, None constants
Expand Down
1 change: 1 addition & 0 deletions vyper/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ def hex_to_int(inp):


# Converts bytes to an integer
# TODO: use int.from_bytes
def bytes_to_int(bytez):
o = 0
for b in bytez:
Expand Down

0 comments on commit c5ad1d8

Please sign in to comment.