Coverage Report

Created: 2026-10-26 06:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/solidity/libsolidity/codegen/CompilerUtils.h
Line
Count
Source
1
/*
2
  This file is part of solidity.
3
4
  solidity is free software: you can redistribute it and/or modify
5
  it under the terms of the GNU General Public License as published by
6
  the Free Software Foundation, either version 3 of the License, or
7
  (at your option) any later version.
8
9
  solidity is distributed in the hope that it will be useful,
10
  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
  GNU General Public License for more details.
13
14
  You should have received a copy of the GNU General Public License
15
  along with solidity.  If not, see <http://www.gnu.org/licenses/>.
16
*/
17
// SPDX-License-Identifier: GPL-3.0
18
/**
19
 * @author Christian <c@ethdev.com>
20
 * @date 2014
21
 * Routines used by both the compiler and the expression compiler.
22
 */
23
24
#pragma once
25
26
#include <libsolidity/ast/ASTForward.h>
27
#include <libsolidity/ast/TypeProvider.h>
28
#include <libsolidity/interface/DebugSettings.h>
29
#include <libsolidity/codegen/CompilerContext.h>
30
#include <libsolidity/codegen/CompilerContext.h>
31
32
namespace solidity::frontend
33
{
34
35
class Type; // forward
36
37
class CompilerUtils
38
{
39
public:
40
1.60M
  explicit CompilerUtils(CompilerContext& _context): m_context(_context)
41
1.60M
  {}
42
43
  /// Stores the initial value of the free-memory-pointer at its position;
44
  void initialiseFreeMemoryPointer();
45
  /// Copies the free memory pointer to the stack.
46
  /// Stack pre:
47
  /// Stack post: <mem_start>
48
  void fetchFreeMemoryPointer();
49
  /// Stores the free memory pointer from the stack.
50
  /// Stack pre: <mem_end>
51
  /// Stack post:
52
  void storeFreeMemoryPointer();
53
  /// Allocates a number of bytes in memory as given on the stack.
54
  /// Stack pre: <size>
55
  /// Stack post: <mem_start>
56
  void allocateMemory();
57
  /// Allocates a number of bytes in memory as given on the stack.
58
  /// Stack pre:
59
  /// Stack post: <mem_start>
60
  void allocateMemory(u256 const& size);
61
  /// Appends code that transforms memptr to (memptr - free_memptr) memptr
62
  /// Stack pre: <mem_end>
63
  /// Stack post: <size> <mem_start>
64
  void toSizeAfterFreeMemoryPointer();
65
66
  /// Appends code that performs a revert, providing the given string data.
67
  /// Will also append an error signature corresponding to Error(string).
68
  /// @param _argumentType the type of the string argument, will be converted to memory string.
69
  /// Stack pre: string data
70
  /// Stack post:
71
  void revertWithStringData(Type const& _argumentType);
72
73
  void revertWithError(
74
    std::string const& _errorName,
75
    std::vector<Type const*> const& _parameterTypes,
76
    std::vector<Type const*> const& _argumentTypes
77
  );
78
79
  /// Allocates a new array and copies the return data to it.
80
  /// If the EVM does not support return data, creates an empty array.
81
  void returnDataToArray();
82
83
  /// Computes the absolute calldata offset of a tail given a base reference and the (absolute)
84
  /// offset of the tail pointer. Performs bounds checks. If @a _type is a dynamically sized array it also
85
  /// returns the array length on the stack.
86
  /// Stack pre: base_ref tail_ptr
87
  /// Stack post: tail_ref [length]
88
  void accessCalldataTail(Type const& _type);
89
90
  /// Loads data from memory to the stack.
91
  /// @param _offset offset in memory (or calldata)
92
  /// @param _type data type to load
93
  /// @param _fromCalldata if true, load from calldata, not from memory
94
  /// @param _padToWords if true, assume the data is padded to full words (32 bytes)
95
  /// @returns the number of bytes consumed in memory.
96
  unsigned loadFromMemory(
97
    unsigned _offset,
98
    Type const& _type,
99
    bool _fromCalldata,
100
    bool _padToWords
101
  );
102
  /// Dynamic version of @see loadFromMemory, expects the memory offset on the stack.
103
  /// Stack pre: memory_offset
104
  /// Stack post: value... (memory_offset+length)
105
  void loadFromMemoryDynamic(
106
    Type const& _type,
107
    bool _fromCalldata = false,
108
    bool _padToWords = true,
109
    bool _keepUpdatedMemoryOffset = true
110
  );
111
  /// Stores a 256 bit integer from stack in memory.
112
  /// @param _offset offset in memory
113
  void storeInMemory(unsigned _offset);
114
115
  /// Dynamic version of @see storeInMemory, expects the memory offset below the value on the stack
116
  /// and also updates that. For reference types, only copies the data pointer. Fails for
117
  /// non-memory-references. For string literals no value is available on the stack.
118
  /// CAUTION: Even with @a _padToWords set to false, this may write a full 32-byte word and only
119
  /// advance the offset by the unpadded size, i.e., up to 31 bytes past the reported end of the
120
  /// stored value are overwritten.
121
  /// @param _padToWords if true, adds zeros to pad to multiple of 32 bytes. Array elements
122
  ///                    are always padded (except for byte arrays), regardless of this parameter.
123
  /// @param _cleanup if true, adds code to cleanup the value before storing it.
124
  /// Stack pre: memory_offset value...
125
  /// Stack post: (memory_offset+length)
126
  void storeInMemoryDynamic(Type const& _type, bool _padToWords = true, bool _cleanup = true);
127
128
  /// Creates code that unpacks the arguments according to their types specified by a vector of TypePointers.
129
  /// From memory if @a _fromMemory is true, otherwise from call data.
130
  /// Calls revert if the supplied size is shorter than the static data requirements
131
  /// or if dynamic data pointers reach outside of the area.
132
  /// Also has a hard cap of 0x100000000 for any given length/offset field.
133
  /// Stack pre: <source_offset> <length>
134
  /// Stack post: <value0> <value1> ... <valuen>
135
  void abiDecode(TypePointers const& _typeParameters, bool _fromMemory = false);
136
137
  /// Copies values (of types @a _givenTypes) given on the stack to a location in memory given
138
  /// at the stack top, encoding them according to the ABI as the given types @a _targetTypes.
139
  /// Removes the values from the stack and leaves the updated memory pointer.
140
  /// Stack pre: <v1> <v2> ... <vn> <memptr>
141
  /// Stack post: <memptr_updated>
142
  /// Does not touch the memory-free pointer.
143
  /// @param _padToWords if false, all values are concatenated without padding.
144
  /// @param _copyDynamicDataInPlace if true, dynamic types is stored (without length)
145
  /// together with fixed-length data.
146
  /// @param _encodeAsLibraryTypes if true, encodes for a library function, e.g. does not
147
  /// convert storage pointer types to memory types.
148
  /// @note the locations of target reference types are ignored, because it will always be
149
  /// memory.
150
  void encodeToMemory(
151
    TypePointers const& _givenTypes,
152
    TypePointers const& _targetTypes,
153
    bool _padToWords,
154
    bool _copyDynamicDataInPlace,
155
    bool _encodeAsLibraryTypes = false
156
  );
157
158
  /// Special case of @a encodeToMemory which assumes tight packing, e.g. no zero padding
159
  /// and dynamic data is encoded in-place.
160
  /// Stack pre: <value0> <value1> ... <valueN-1> <head_start>
161
  /// Stack post: <mem_ptr>
162
  void packedEncode(
163
    TypePointers const& _givenTypes,
164
    TypePointers const& _targetTypes,
165
    bool _encodeAsLibraryTypes = false
166
  )
167
321
  {
168
321
    encodeToMemory(_givenTypes, _targetTypes, false, true, _encodeAsLibraryTypes);
169
321
  }
170
171
  /// Special case of @a encodeToMemory which assumes that everything is padded to words
172
  /// and dynamic data is not copied in place (i.e. a proper ABI encoding).
173
  /// Stack pre: <value0> <value1> ... <valueN-1> <head_start>
174
  /// Stack post: <mem_ptr>
175
  void abiEncode(
176
    TypePointers const& _givenTypes,
177
    TypePointers const& _targetTypes,
178
    bool _encodeAsLibraryTypes = false
179
  )
180
10.7k
  {
181
10.7k
    encodeToMemory(_givenTypes, _targetTypes, true, false, _encodeAsLibraryTypes);
182
10.7k
  }
183
184
  /// Special case of @a encodeToMemory which assumes that everything is padded to words
185
  /// and dynamic data is not copied in place (i.e. a proper ABI encoding).
186
  /// Uses a new, less tested encoder implementation.
187
  /// Stack pre: <value0> <value1> ... <valueN-1> <head_start>
188
  /// Stack post: <mem_ptr>
189
  void abiEncodeV2(
190
    TypePointers const& _givenTypes,
191
    TypePointers const& _targetTypes,
192
    bool _encodeAsLibraryTypes = false,
193
    bool _padToWordBoundaries = true
194
  );
195
196
  /// Decodes data from ABI encoding into internal encoding. If @a _fromMemory is set to true,
197
  /// the data is taken from memory instead of from calldata.
198
  /// Can allocate memory.
199
  /// Stack pre: <source_offset> <length>
200
  /// Stack post: <value0> <value1> ... <valuen>
201
  void abiDecodeV2(TypePointers const& _parameterTypes, bool _fromMemory = false);
202
203
  /// Zero-initialises (the data part of) an already allocated memory array.
204
  /// Length has to be nonzero!
205
  /// Stack pre: <length> <memptr>
206
  /// Stack post: <updated_memptr>
207
  void zeroInitialiseMemoryArray(ArrayType const& _type);
208
209
  /// Copies full 32 byte words in memory (regions cannot overlap), i.e. may copy more than length.
210
  /// Length can be zero, in this case, it copies nothing.
211
  /// Stack pre: <size> <target> <source>
212
  /// Stack post:
213
  void memoryCopy32();
214
  /// Copies data in memory (regions cannot overlap).
215
  /// Length can be zero, in this case, it copies nothing.
216
  /// Stack pre: <size> <target> <source>
217
  /// Stack post:
218
  void memoryCopy();
219
220
  /// Stores the given string in memory.
221
  /// Stack pre: mempos
222
  /// Stack post:
223
  void storeStringData(bytesConstRef _data);
224
225
  /// Converts the combined and left-aligned (right-aligned if @a _rightAligned is true)
226
  /// external function type <address><function identifier> into two stack slots:
227
  /// address (right aligned), function identifier (right aligned)
228
  void splitExternalFunctionType(bool _rightAligned);
229
  /// Performs the opposite operation of splitExternalFunctionType(_rightAligned)
230
  void combineExternalFunctionType(bool _rightAligned);
231
  /// Appends code that combines the construction-time (if available) and runtime function
232
  /// entry label of the given function into a single stack slot.
233
  /// Note: This might cause the compilation queue of the runtime context to be extended.
234
  /// If @a _runtimeOnly, the entry label will include the runtime assembly tag.
235
  void pushCombinedFunctionEntryLabel(Declaration const& _function, bool _runtimeOnly = true);
236
237
  /// Appends code for an implicit or explicit type conversion. This includes erasing higher
238
  /// order bits (@see appendHighBitCleanup) when widening integer but also copy to memory
239
  /// if a reference type is converted from calldata or storage to memory.
240
  /// If @a _cleanupNeeded, high order bits cleanup is also done if no type conversion would be
241
  /// necessary.
242
  /// If @a _chopSignBits, the function resets the signed bits out of the width of the signed integer.
243
  /// If @a _asPartOfArgumentDecoding is true, failed conversions are flagged via REVERT,
244
  /// otherwise they are flagged with INVALID.
245
  void convertType(
246
    Type const& _typeOnStack,
247
    Type const& _targetType,
248
    bool _cleanupNeeded = false,
249
    bool _chopSignBits = false,
250
    bool _asPartOfArgumentDecoding = false
251
  );
252
253
  /// Creates a zero-value for the given type and puts it onto the stack. This might allocate
254
  /// memory for memory references.
255
  void pushZeroValue(Type const& _type);
256
  /// Pushes a pointer to the stack that points to a (potentially shared) location in memory
257
  /// that always contains a zero. It is not allowed to write there.
258
  void pushZeroPointer();
259
260
  /// Moves the value that is at the top of the stack to a stack variable.
261
  void moveToStackVariable(VariableDeclaration const& _variable);
262
  /// Copies an item that occupies @a _itemSize stack slots from a stack depth of @a _stackDepth
263
  /// to the top of the stack.
264
  void copyToStackTop(unsigned _stackDepth, unsigned _itemSize);
265
  /// Moves an item that occupies @a _itemSize stack slots and has items occupying @a _stackDepth
266
  /// slots above it to the top of the stack.
267
  void moveToStackTop(unsigned _stackDepth, unsigned _itemSize = 1);
268
  /// Moves @a _itemSize elements past @a _stackDepth other stack elements
269
  void moveIntoStack(unsigned _stackDepth, unsigned _itemSize = 1);
270
  /// Rotates the topmost @a _items items on the stack, such that the previously topmost element
271
  /// is bottom-most.
272
  void rotateStackUp(unsigned _items);
273
  /// Rotates the topmost @a _items items on the stack, such that the previously bottom-most element
274
  /// is now topmost.
275
  void rotateStackDown(unsigned _items);
276
  /// Removes the current value from the top of the stack.
277
  void popStackElement(Type const& _type);
278
  /// Removes element from the top of the stack _amount times.
279
  void popStackSlots(size_t _amount);
280
  /// Pops slots from the stack such that its height is _toHeight.
281
  /// Adds jump to _jumpTo.
282
  /// Readjusts the stack offset to the original value.
283
  void popAndJump(unsigned _toHeight, evmasm::AssemblyItem const& _jumpTo);
284
285
  template <class T>
286
  static unsigned sizeOnStack(std::vector<T> const& _variables);
287
  static unsigned sizeOnStack(std::vector<Type const*> const& _variableTypes);
288
289
  /// Helper function to shift top value on the stack to the left.
290
  /// Stack pre: <value> <shift_by_bits>
291
  /// Stack post: <shifted_value>
292
  void leftShiftNumberOnStack(unsigned _bits);
293
294
  /// Helper function to shift top value on the stack to the right.
295
  /// Stack pre: <value> <shift_by_bits>
296
  /// Stack post: <shifted_value>
297
  void rightShiftNumberOnStack(unsigned _bits);
298
299
  /// Appends code that computes the Keccak-256 hash of the topmost stack element of 32 byte type.
300
  void computeHashStatic();
301
302
  /// Appends code that copies the code of the given contract to memory.
303
  /// Stack pre: Memory position
304
  /// Stack post: Updated memory position
305
  /// @param _creationCode if true, copies creation code, if false copies runtime code.
306
  /// @note the contract has to be compiled already, so beware of cyclic dependencies!
307
  void copyContractCodeToMemory(ContractDefinition const& contract, bool _creationCode);
308
309
  /// Bytes we need to the start of call data.
310
  ///  - The size in bytes of the function (hash) identifier.
311
  static unsigned const dataStartOffset;
312
313
  /// Position of the free-memory-pointer in memory;
314
  static size_t const freeMemoryPointer;
315
  /// Position of the memory slot that is always zero.
316
  static size_t const zeroPointer;
317
  /// Starting offset for memory available to the user (aka the contract).
318
  static size_t const generalPurposeMemoryStart;
319
320
private:
321
  /// Appends code that cleans higher-order bits for integer types.
322
  void cleanHigherOrderBits(IntegerType const& _typeOnStack);
323
324
  /// Prepares the given type for storing in memory by shifting it if necessary.
325
  /// @param _cleanup if true, also cleanup the value when preparing to store it in memory
326
  unsigned prepareMemoryStore(Type const& _type, bool _padToWords, bool _cleanup = true);
327
  /// Loads type from memory assuming memory offset is on stack top.
328
  unsigned loadFromMemoryHelper(Type const& _type, bool _fromCalldata, bool _padToWords);
329
330
  CompilerContext& m_context;
331
};
332
333
334
template <class T>
335
unsigned CompilerUtils::sizeOnStack(std::vector<T> const& _variables)
336
52.3k
{
337
52.3k
  unsigned size = 0;
338
52.3k
  for (T const& variable: _variables)
339
36.2k
    size += variable->annotation().type->sizeOnStack();
340
52.3k
  return size;
341
52.3k
}
342
343
}