Add a wasm32 backend to cppgm and lowir2native. Compile the portable
course language profile to WebAssembly while preserving the existing native
targets. Reuse your frontend, typed LowIR and LowIR optimizer. Refactor your
machine representations where needed so shared analyses do not assume x86
registers, instruction forms or calling conventions.
Complete PA34 and the earlier cumulative assignments first. Continue working
in dev/ and shared modules under dev/src/.
Design notes suggest an approach. The
target and ABI contract defines the shared boundary.
Support wasm32-unknown-unknown for freestanding core modules and
wasm32-wasip1 for WASI Preview 1 commands. Preserve the existing targets,
default target and optimization levels. Support these forms:
cppgm --target=wasm32-wasip1 -O2 source.cpp -o program.wasm
cppgm --target=wasm32-wasip1 -O2 -c source.cpp -o source.o
cppgm --target=wasm32-wasip1 source.o other.o -o program.wasm
cppgm --target=wasm32-wasip1 --emit-lowir source.cpp -o source.lowir
lowir2native --target=wasm32-wasip1 -O2 -o program.wasm source.lowir
lowir2native --target=wasm32-wasip1 -O2 \
--dump-machine-ir program.mir -o program.wasm source.lowirDefine __wasi__ to 1 for the WASI Preview 1 target. In C mode, also
define __wasip1__ to 1 so the SDK selects its Preview 1 declarations.
The object that -c compiles from a source's object LowIR is byte-identical
to the object that -c compiles from the source at the same level. This also
holds after lowiropt -O0 reads and writes that text. The object LowIR is
--emit-lowir -g0 -O0, with -D__OPTIMIZE__=1 for an O1+ level. The checker
compares the two objects at each level, as PA33's object round trip does for
the native targets.
The additional wasm32-unknown-emscripten SDK profile carries Emscripten's
layout and allocation alignment. Use explicit SDK runtime archives and import
declarations for links; it does not generate JS glue. The
target contract specifies its differences from the two
sixteen-byte-aligned long double profiles.
The SDK assembly path accepts .S files or -x assembler-with-cpp for Wasm
targets. Preprocess them with __ASSEMBLER__ defined, then parse GNU Wasm
assembly directly into the existing machine model and relocatable object.
This path has no source-to-LowIR view. Native targets must reject this Wasm
assembly input.
The initial runtime subset covers .functype, .globaltype, function locals,
visibility and binding directives, explicit function imports via .import_module
and .import_name, zero-initialized Wasm globals, constructor
.init_array sections, and target_features metadata. Support scalar core
instructions with typed function/global references, structured control flow,
floating constants, memory size/growth and bulk-memory operations. These are
the forms used by the SDK's memcpy and stack-management sources. Diagnose
unsupported directives and operand forms; this is not a general GNU assembler
profile. Validate instruction stacks before writing objects, and preserve
symbol relocations and constructor priorities through linking.
Wasm invocations of lowir2native may also take relocatable object and
archive inputs, including the supplied arithmetic/runtime libraries.
Freestanding modules use declared imports and exports rather than a WASI
main. Follow the supplied target contract for entry points, exported names,
runtime linkage and initialization. Run freestanding dynamic initializers once
at module instantiation; the core start function must not also call main.
An unresolved symbol is an error unless
explicitly declared as an import with its module, name and signature.
Absent weak references follow the null-address and call rules in the target
contract.
Produce valid deterministic module bytes and LLVM-compatible relocatable Wasm objects directly. The compiler must perform its own lowering, encoding and static linking. LLVM, LLD and external assemblers are reference tools; the submitted compiler must not invoke them to implement code generation. Supplied runtime libraries may provide arithmetic and language-runtime services, as native libraries do in the earlier assignments.
When compiling the C++ runtime, emit the shared RTTI for the fundamental
types in the pinned LLVM toolchain's runtime profile. Emit the descriptors
for those types, pointers to them and pointers to their const-qualified
forms with the __cxxabiv1::__fundamental_type_info vtable. A separate object
using typeid(void) must resolve its reference to _ZTIv against that runtime.
Use --sysroot <directory> to select the supplied target headers and libraries,
and -resource-dir <directory> for its builtin headers and arithmetic runtime.
For example, after installing the pinned SDK, pass its share/wasi-sysroot and
lib/clang/23 directories respectively. Apply the same target configuration to
source compilation and lowir2native links. A WASIp1 link with a sysroot uses
command startup by default; without a sysroot, supply an explicit _start or
disable startup. Support -nostartfiles, -nodefaultlibs and
-nostdlib to select startup and libraries explicitly; these flags do not
remove header search paths.
Implement the following at -O0, -O1, -O2 and -O3:
- GNU label addresses and computed goto within one function, preserving label pointer identity and retaining every addressed entry through optimization.
- Empty GNU assembly used as a compiler barrier, including evaluated inputs and scalar read/write register operands. Preserve its memory effects and captured input values; reject output-only operands and machine instructions.
- The scalar Wasm
__builtin_wasm_min_f32/f64and__builtin_wasm_max_f32/f64builtins, including NaN propagation and signed zero. Advertise these builtins only for Wasm targets. __builtin_flt_rounds()returns 1, the code for round-to-nearest. The query works in modules built with-nostdlib.- Scalar arithmetic and conversions, narrow integer behavior, pointers, aggregates, globals, volatile memory, alignment and address-taken locals. Preserve wide integer and floating types through valid legalization/helper calls where Wasm has no corresponding value type. Apply the Wasm call convention to complex arithmetic helpers, including their indirect aggregate results and the parts of binary128 operands.
- Complete control flow, including phi transfers, switches, nested loops and irreducible graphs accepted by LowIR. Preserve every defined exit path.
- C
setjmpcontinuations andlongjmpthrough direct or indirect calls, with invocation-specific targets, zero-to-one return normalization and restored stack state. Preserve unmodified automatic objects and volatile observations. - Direct and indirect calls, recursion, variadic functions, aggregate argument and result passing, and separately compiled objects.
- The portable class/template behavior already required by the course, including virtual dispatch, RTTI, local statics, allocation, initialization and destruction. Support C++ exceptions, cleanup, matching catches and rethrow using modern Wasm exception handling.
- Portable vector operations through SIMD128 or equivalent correct lowering, with the published quality bounds at optimizing levels.
- Scalar atomic loads, stores, add-and-fetch, exchange, compare-exchange and fences, for integer and pointer widths through 64 bits. Preserve the memory ordering and compare-exchange expected-value update semantics.
- WASIp1 command startup, arguments, the supported I/O services and exit status; freestanding initialization and repeated calls within one module instance.
The first target profile is single-threaded and little-endian, with one 32-bit linear memory and one indirect-function table. Its allowed features are mutable globals, sign extension, nontrapping float-to-int conversion, bulk memory, extended constant expressions, multi-value, reference types, SIMD128, atomics and modern exception handling. Match the supplied profile and feature metadata. The public C ABI retains its specified return/argument convention even when multi-value is available internally. Optimization levels must not change public function parameter/result types, even when a native register convention permits a representation change.
Atomic instructions can operate on the profile's unshared memory. Memory orders
may use stronger ordering when the target requires it. Emit matching atomics
feature metadata. -mno-atomics disables this instruction extension and must
diagnose operations that require it; unsupported atomic widths must also be
diagnosed.
Lock-free queries use the same capability. Enabled queries cover naturally
aligned objects of 1, 2, 4 or 8 bytes and accept a null pointer to ask about
natural alignment. Disabled queries return false. A runtime query observes
each operand once and can execute without an imported atomic runtime.
Threads and shared memory, TLS, Emscripten glue, components, and dynamic linking are outside this profile. Diagnose these and unsupported architecture-specific operations, including x86 assembly, CPUID, MXCSR and hardware frame introspection. Ordinary portable operations must not fail merely because the native backend implemented them with an x86 instruction.
Use --target=wasm64-unknown-unknown for freestanding Wasm with 64-bit
long, pointers, linear-memory addresses, and function-table indices.
int remains 32-bit. Record this data model as the wasm64 LowIR target.
Build relocatable objects with -c and link them with a memory64-capable
linker. The Wasm32 internal linker continues to serve the Wasm32 profiles.
cppgm --target=wasm64-unknown-unknown -std=gnu11 -O2 -c source.c -o source.o
cppgm --target=wasm64-unknown-unknown -std=gnu11 -O2 -S source.c -o source.s
wasm-ld -mwasm64 --no-entry --export=observe source.o -o program.wasmEmit GNU-style Wasm assembly with -S on both Wasm widths. Use the target's
local and global value types in the output. The assembler directives for a
function's host module and import name preserve the separate linker name.
The wasm64 profile also accepts inline moves between typed Wasm globals
and scalar GNU r operands. Declare the globals with file-scope
.globaltype. In -S output, preserve constant substitutions in
.ascii "->..." records used to generate C layout headers.
Select target facts before preprocessing and semantic analysis. Wasm32 uses
32-bit int, long and pointers, 64-bit long long, and 16-byte binary128
long double. Match the supplied ABI for type identity, signedness, layout,
alignment, literals, constant evaluation and calling conventions. Target
headers and builtin macros must describe the target rather than the host.
Keep language builtin templates available across targets while adapting types
such as va_list. Numeric-limit and wide-character declarations must agree
with the target headers, including binary128 long double limits and the
integer types, limits and literal suffixes used by <stdint.h>.
Carry target/layout metadata and sufficient typed ABI facts in LowIR. Reject
incompatible inputs; do not reinterpret existing x86-layout LowIR as wasm32.
Source compilation and compilation through serialized LowIR must agree.
Function pointers use table references, distinct from linear-memory
addresses. Preserve null values, indirect-call signatures, aggregate copies,
hidden result parameters and variadic argument layout. Preserve the passed
scalar types and aggregate shapes on unnamed arguments and va_arg so their
layout survives constant propagation and call cloning. Empty objects, singleton
records and other aggregates have different ABI forms; consume LowIR’s
shape facts together with their size
and alignment. An indirect by-value argument needs its own copy, and an object
SSA value must retain its snapshot when the original storage changes.
Interoperate with the pinned LLVM wasm32 toolchain in both directions. A cppgm-generated object must link with its objects/runtime through LLD, and your linker must accept the documented object profile produced by LLVM. Preserve weak/COMDAT definitions, data and function addresses, initializers, exception tags and supported relocations. Reject mismatched signatures and features instead of emitting a module that fails only when executed. Preserve Wasm globals, constant-expression dependencies and typed reference values. Validate element declarations and all supported index spaces. Where the pinned linker lacks a required case, the reference notes identify its independent checks.
Exporting a linear-memory data symbol exposes its address as an immutable
i32 Wasm global. Aliases must expose the same address. The public name
memory is reserved for the module's linear memory. A reference or export of
__start_NAME or __stop_NAME provides the boundaries of a named data section
present in active input objects. Retain its contributions and their relocation
dependencies, preserve input order within it, and place them contiguously with
their required alignment. A boundary reference alone does not extract an
otherwise unreferenced archive member. Diagnose absent sections.
Keep a typed machine representation that emission actually consumes. It must describe values, control-flow edges, calls, effects, frame objects and debug locations accurately. Common analyses must not require x86 register names, eightbyte ABI classes, fixed two-address operations or one physical frame register. Target-specific instruction and operand forms may remain separate.
Wasm has typed locals and a value stack. Do not require a physical-register allocator for this target. The supplied machine dump must describe the same optimized function that is encoded, including typed locals, control regions, linear-memory frame requirements and call signatures. A WAT/MIR dump is a view, not a transport format to another compiler or assembler.
Run the existing LowIR optimizer using the selected target's layout, capabilities and cost policy. Preserve its semantic improvements without copying x86-specific profitability decisions. Optimizing levels must satisfy the supplied envelopes for locals, frame accesses, code growth and kernel behavior. Pass names, stackification order, local indices, block nesting and individual Wasm instructions are your choices.
Fixtures check compilation status, independent module validation, program
output, return/exit status and the resulting memory state. ABI cases link
objects from both compilers and exercise calls and exceptions across the
boundary. Repeated-export tests use one module instance to check persistent
state and initialization. A sidecar's sequences lists the ordered export calls that share an instance;
ordinary calls are independent invocations. Native regression tests remain required.
A fixture's hosts map names separate supplied host modules. link_exports
selects static linking symbols explicitly; an empty list exercises exports
declared by the inputs themselves. export_names checks the complete public
function-name set, while abi checks parameter/result types. Exported global
types and mutability can be checked with global_abi. Import/export
names and signatures are interface requirements, independent of instruction
selection or optimization strategy.
An export call with trap: true must trap at runtime. trap: "fuel"
requires fuel exhaustion specifically, using the call's per-level fuel budgets.
Fuel-limited calls use segment initialization so host memory-image mapping does
not change their budgets. WASI command sidecars may
provide named input files and expected outputs; each command gets a fresh
preopened directory for them.
For exit values reserved by the runtime, a command's proc_exit assertion
substitutes a test host that checks the exact WASI argument and exits zero on
success. The guest instructions and function indices are preserved. Ordinary
exit assertions use the runtime's WASI host directly.
Quality checks explain the metrics; fixture sidecars publish the actual limits and invariants. Tests do not compare complete instruction sequences against LLVM. Equivalent legal lowerings are accepted. A simple scalar expression should not need a linear-memory frame; an ordinary reducible loop should not become a whole-function dispatch loop. Irreducible graphs still require correct, bounded lowering.
Fail with nonzero status for invalid inputs, conflicting targets/layouts, unsupported operations/features, malformed objects, unresolved symbols, signature/relocation errors and unwritable output. Diagnostic wording is not prescribed. A successful compile must never hide a fallback to host code.
Install the pinned runtime, validator and reference SDK once:
perl ../scripts/install_wasm_tools.pl --prefix ../obj/wasm-tools
export PATH="$(cd ../obj/wasm-tools/bin && pwd):$PATH"Run make test for this assignment or make check TEST=<fixture> for a
focused check. Both use the standard parallel runner. Numbered fixture groups
cover targets/modules, values/memory, control/calls, objects/ABI, C++ runtime
and optimization. The checker reuses successful trusted-tool results for byte-identical inputs
and identical settings within one fixture. WASI commands, failures and traps
still run independently; every compiler path and optimization level still runs.
Install the pinned runtime, validator and reference
toolchain listed in the supplied reference bundle; missing required tools
are reported as prerequisite failures.
Each tool invocation has a 30-second wall limit, a 30-second CPU limit per process, a 2-GiB resident-memory ceiling across its process group, and a 64-MiB limit on each output file. The supervisor wakes when a child exits. While it runs, resident memory is sampled every 10 milliseconds on Linux and macOS; it can briefly exceed the ceiling between samples. The runtime separately limits each guest linear memory to 256 MiB. Resource exhaustion, cancellation and internal errors fail the test, including tests that expect an input diagnostic.
The generated CFG and ABI fixtures use published seeds and independent Perl
arithmetic. They include cyclic phi transfers, switched recurrences, reordered
blocks, narrow values, mixed and over-aligned records, indirect calls and
caller-owned argument copies. The ABI cases cross the reference compiler
boundary in both directions. Reproduce a seed or explore another one with
perl scripts/generate_tests.pl --seed 1 --output student.tests/generated;
run the resulting inputs with the ordinary make check TEST=... command.
Use the assignment target while iterating. Finish with the cumulative
report through this assignment from the repository root with make test-report-through-pa37. That command
includes this assignment, so running both is unnecessary for final validation.
The benchmark target, make benchmark, reports compile time, module size, startup and
steady-state execution separately. Timing comparisons use identical inputs
and runtime settings and are not substitutes for correctness.
Use the versioned offline reference bundle. Online sources are the Wasm core specification, Basic C ABI, object linking conventions and WASI SDK.