|
| 1 | +/* |
| 2 | + * Copyright 2026 WebAssembly Community Group participants |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +// |
| 18 | +// Pools repeated constants into immutable globals. A constant that is used |
| 19 | +// multiple times can often be stored in a global, replacing the bytes of |
| 20 | +// encoding the constant each time with the (usually smaller) bytes of a |
| 21 | +// global.get. We only do this when the estimated binary size strictly |
| 22 | +// decreases, so small constants (which are already very cheap) are left alone. |
| 23 | +// |
| 24 | +// WARNING: like const-hoisting, this shrinks raw size but can increase gzip |
| 25 | +// size, as removing repeated constants removes redundancy that |
| 26 | +// compressors use. |
| 27 | +// |
| 28 | + |
| 29 | +#include <cstring> |
| 30 | +#include <map> |
| 31 | +#include <string> |
| 32 | + |
| 33 | +#include "ir/module-utils.h" |
| 34 | +#include "pass.h" |
| 35 | +#include "wasm-binary.h" |
| 36 | +#include "wasm-builder.h" |
| 37 | +#include "wasm.h" |
| 38 | + |
| 39 | +namespace wasm { |
| 40 | + |
| 41 | +namespace { |
| 42 | + |
| 43 | +// The types of constants we consider pooling. More types are possible, but |
| 44 | +// these are the ones where pooling can typically pay off. |
| 45 | +bool isPoolable(Type type) { |
| 46 | + return type == Type::i32 || type == Type::i64 || type == Type::f32 || |
| 47 | + type == Type::f64 || type == Type::v128; |
| 48 | +} |
| 49 | + |
| 50 | +// The number of bytes an unsigned LEB128 takes. |
| 51 | +Index sizeULEB(uint64_t value) { |
| 52 | + Index size = 1; |
| 53 | + while (value >= 0x80) { |
| 54 | + value >>= 7; |
| 55 | + size++; |
| 56 | + } |
| 57 | + return size; |
| 58 | +} |
| 59 | + |
| 60 | +template<typename T> Index getWrittenSize(const T& thing) { |
| 61 | + BufferWithRandomAccess buffer; |
| 62 | + buffer << thing; |
| 63 | + return buffer.size(); |
| 64 | +} |
| 65 | + |
| 66 | +// The number of bytes a constant instruction takes in the binary, including |
| 67 | +// the opcode. |
| 68 | +Index getConstSize(const Literal& value) { |
| 69 | + auto type = value.type; |
| 70 | + if (type == Type::i32) { |
| 71 | + return 1 + getWrittenSize(S32LEB(value.geti32())); |
| 72 | + } |
| 73 | + if (type == Type::i64) { |
| 74 | + return 1 + getWrittenSize(S64LEB(value.geti64())); |
| 75 | + } |
| 76 | + if (type == Type::f32) { |
| 77 | + return 1 + 4; |
| 78 | + } |
| 79 | + if (type == Type::f64) { |
| 80 | + return 1 + 8; |
| 81 | + } |
| 82 | + assert(type == Type::v128); |
| 83 | + // v128.const has a two-byte prefixed opcode (0xfd 0x0c), unlike the other |
| 84 | + // constant instructions, followed by the 16 bytes of the value. |
| 85 | + return 2 + 16; |
| 86 | +} |
| 87 | + |
| 88 | +// A deterministic key for a constant: the basic type and the raw bits. We |
| 89 | +// cannot use Literal directly as its comparison depends on Type IDs, which are |
| 90 | +// not stable between runs. |
| 91 | +struct PoolKey { |
| 92 | + Type::BasicType type; |
| 93 | + uint8_t bits[16]; |
| 94 | + |
| 95 | + bool operator<(const PoolKey& other) const { |
| 96 | + if (type != other.type) { |
| 97 | + return type < other.type; |
| 98 | + } |
| 99 | + return memcmp(bits, other.bits, 16) < 0; |
| 100 | + } |
| 101 | +}; |
| 102 | + |
| 103 | +struct ConstantPooling : public Pass { |
| 104 | + // We add globals, but do not change any of the locals in the module. |
| 105 | + bool requiresNonNullableLocalFixups() override { return false; } |
| 106 | + |
| 107 | + void run(Module* module) override { |
| 108 | + using Ptrs = std::vector<Expression**>; |
| 109 | + |
| 110 | + // Scan all the function bodies. We cannot handle constants in const- |
| 111 | + // expression positions (global initializers, segment offsets, etc.), as |
| 112 | + // those cannot contain a global.get (of a non-imported global), so we only |
| 113 | + // walk function bodies. |
| 114 | + struct Scanner : public PostWalker<Scanner> { |
| 115 | + Ptrs& ptrs; |
| 116 | + |
| 117 | + Scanner(Ptrs& ptrs) : ptrs(ptrs) {} |
| 118 | + |
| 119 | + void visitConst(Const* curr) { |
| 120 | + if (isPoolable(curr->type)) { |
| 121 | + ptrs.push_back(getCurrentPointer()); |
| 122 | + } |
| 123 | + } |
| 124 | + }; |
| 125 | + |
| 126 | + ModuleUtils::ParallelFunctionAnalysis<Ptrs> analysis( |
| 127 | + *module, [&](Function* func, Ptrs& ptrs) { |
| 128 | + if (!func->imported()) { |
| 129 | + Scanner(ptrs).walk(func->body); |
| 130 | + } |
| 131 | + }); |
| 132 | + |
| 133 | + // Group the constants by their value. |
| 134 | + std::map<PoolKey, Ptrs> groups; |
| 135 | + for (auto& [func, ptrs] : analysis.map) { |
| 136 | + for (auto** ptr : ptrs) { |
| 137 | + auto* curr = (*ptr)->cast<Const>(); |
| 138 | + PoolKey key; |
| 139 | + key.type = curr->type.getBasic(); |
| 140 | + curr->value.getBits(key.bits); |
| 141 | + groups[key].push_back(ptr); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + // Decide which constants to pool. A pooled constant adds one global |
| 146 | + // (whose entry encodes the constant plus overhead) and replaces each use |
| 147 | + // with a global.get. |
| 148 | + Index existingGlobals = module->globals.size(); |
| 149 | + auto globalGetSize = [&](Index index) { return 1 + sizeULEB(index); }; |
| 150 | + |
| 151 | + struct ToPool { |
| 152 | + Const* value; |
| 153 | + Ptrs* ptrs; |
| 154 | + Name name; |
| 155 | + }; |
| 156 | + std::vector<ToPool> toPool; |
| 157 | + |
| 158 | + // The index a pooled global will get. We do not know that for sure, but we |
| 159 | + // compute a conservative bound: if there will be more than 128 globals |
| 160 | + // then some may need two bytes to encode, so assume that. |
| 161 | + Index numGlobals = existingGlobals + groups.size(); |
| 162 | + Index getSize = globalGetSize(numGlobals > 0 ? numGlobals - 1 : 0); |
| 163 | + |
| 164 | + // If the module has no globals at all, we must also pay for the global |
| 165 | + // section itself when we add the first one. |
| 166 | + bool firstPooled = true; |
| 167 | + |
| 168 | + for (auto& [key, ptrs] : groups) { |
| 169 | + auto* value = (*ptrs[0])->cast<Const>(); |
| 170 | + Index constSize = getConstSize(value->value); |
| 171 | + Index count = ptrs.size(); |
| 172 | + // This is only valid if the global.get is smaller than the constant. |
| 173 | + if (constSize <= getSize) { |
| 174 | + continue; |
| 175 | + } |
| 176 | + int64_t savings = |
| 177 | + int64_t(count) * (constSize - getSize) - (constSize + 3); |
| 178 | + if (existingGlobals == 0 && firstPooled) { |
| 179 | + savings -= 3; |
| 180 | + } |
| 181 | + if (savings > 0) { |
| 182 | + toPool.push_back({value, &ptrs, Name()}); |
| 183 | + firstPooled = false; |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + if (toPool.empty()) { |
| 188 | + return; |
| 189 | + } |
| 190 | + |
| 191 | + // Create the globals, then replace the uses. |
| 192 | + Builder builder(*module); |
| 193 | + Index counter = 0; |
| 194 | + for (auto& entry : toPool) { |
| 195 | + Name name; |
| 196 | + while (true) { |
| 197 | + name = std::string("const$") + std::to_string(counter++); |
| 198 | + if (!module->getGlobalOrNull(name)) { |
| 199 | + break; |
| 200 | + } |
| 201 | + } |
| 202 | + entry.name = name; |
| 203 | + auto global = builder.makeGlobal( |
| 204 | + name, entry.value->type, entry.value, Builder::Immutable); |
| 205 | + module->addGlobal(std::move(global)); |
| 206 | + } |
| 207 | + |
| 208 | + for (auto& entry : toPool) { |
| 209 | + for (auto** ptr : *entry.ptrs) { |
| 210 | + *ptr = builder.makeGlobalGet(entry.name, entry.value->type); |
| 211 | + } |
| 212 | + } |
| 213 | + } |
| 214 | +}; |
| 215 | + |
| 216 | +} // anonymous namespace |
| 217 | + |
| 218 | +Pass* createConstantPoolingPass() { return new ConstantPooling(); } |
| 219 | + |
| 220 | +} // namespace wasm |
0 commit comments