[CIR][offload-merge] Stamp launch-derived noalias on kernel parameters #30
Few things:
1) The tests are potentially way too verbose, so don't get scared if you see +2k lines of change. The substance of the pass resides in: clang/lib/CIR/Dialect/Transforms/OffloadOpt/OffloadLaunchNoalias.cpp (about ~500 loc).
2) I also witnessed a reduction in binary sizes consistently. However, I didn't want that claim to be a main headline, given once we add specialization, it might increase size back again.
| Comparison | Arms | Size |
|---|---|---:|
| This pass alone | ON vs OFF, merge arm | ON 737,056 B vs OFF 753,440 B over 21 executables: 4 of them exactly 4,096 B smaller with the pass on |
| KACP stack alone | off → on, noalias off in both arms | -11.8% (1× and 2×) |
| Whole merge pipeline | CIR vs CIR-merge | -15.8% (1×, 2×, 4×) |
Nit: IMO this would be easier to read if the condition is flipped.
while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
if (!castOp.isAllocaPreservingCast() &&
castOp.getKind() != cir::CastKind::array_to_ptrdecay)
break;
val = castOp.getSrc();
}
I had a pass similar to this, but a little more geeneral for "pointer facts", which derived other information about pointers as well. Maybe it makes sense to generalize the naming of this pass so we can expand on it, instead of replicating the pointer analysis logic for other cases?
Reference: https://github.com/steffenlarsen/llvm-project/commit/186682c1a1b1a857d6531c4eb43c5908cb06981b
Done!
I had a pass similar to this, but a little more geeneral for "pointer facts", which derived other information about pointers as well. Maybe it makes sense to generalize the naming of this pass so we can expand on it, instead of replicating the pointer analysis logic for other cases?
> Reference: steffenlarsen@186682c
Yes, I had read your pass previously: PropagatePointerFacts IIRC, besides the non-alias proof we look for here, it also stamped alignment and readonly/writeonly metadata. I empirically measured whether if I'd get a runtime improvement by stamping the last two facts in isolation, but that wasn't really the case (I think still, we should attach that metadata for correctness). I'm yet to see if alignment improves vectorization too! Btw all of the measurements collected were for CUDA/NVPTX -- I'm yet to try it on AMD; I think I could do that in a later PR so that we properly extend it.
High level comments:
1. I believe that you have some small issues. I believe that you will need to prove Dominance "A cudaMalloc to dominate the launch = any path that reaches to the launch does a malloc".
2. What happens if you capture the pointer through some uintptr_t value.
__global__ void foo(int *A, uintptr_t B){
}
A = cudaMalloc(....);
uintptr_t B = (uintptr_t) A;
launch(foo, A, B);
3. How are you handling globals and or symbols. Take for example this code:
#include <cstdio>
__device__ float *g_ptr; // host will point this at B's allocation
__device__ __noinline__ void bump() {
g_ptr[0] += 1.0f; // writes B's memory through a pointer not based on `b`
}
static __global__ void k(float *a, float *b) {
b[0] = 1.0f;
bump(); // body check sees: callee "bump", no args -> OK
a[0] = b[0]; // expected 2.0
}
int main() {
float *A, *B;
cudaMalloc(&A, sizeof(float));
cudaMalloc(&B, sizeof(float));
float *tmp = B; // copy, so B's slot only has a load (allowed use)
cudaMemcpyToSymbol(g_ptr, &tmp, sizeof(tmp));
k<<<1, 1>>>(A, B);
float h;
cudaMemcpy(&h, A, sizeof(float), cudaMemcpyDeviceToHost);
printf("%f\n", h); // 2.0 without the pass; can print 1.0 with it
}
You will annotate as no-alias right?
I think @koparasy makes some great points (as always). The global variable example is especially nasty, but I suspect it isn't unique. You could maybe even trigger the same problem if you wrote the address of B to some other piece of global memory, then load the pointer through the memory on the device. The implementation will have to try and be conservative, as soon as the address of any memory pointer leaves our view (e.g. untracable function calls, casts, etc.) then we'll have to assume it could be aliased.
On a side note, did something happen during rebasing? There seems to be a lot of conflicts and a lot of changes in this PR now.
I've done some white-boarding myself throughout the week to address the great points brought in by you guys. so apologies for the late-ish reply -- I'd love to dedicate my 100% to this but school has been unfortunately killing my momentum in open-source 😤😤.
In consquence this might a bit long (please bear with me). Regarding @koparasy's points:
1.Dominance
You're right, this was broken. We only checked that every store to the slot came (lexically) before the cudaMalloc, never that the cudaMalloc actually reaches the launch. Both of these got noalias:
float *A = B;
if (c)
cudaMalloc(&A, n); // skipped when !c
k<<<1, 1>>>(A, B); // A == B
float *A = B;
k<<<1, 1>>>(A, B); // A == B
cudaMalloc(&A, n);
Funny enough, PolyBench-style code hid this. With a cudaFree(A) after the launch, allocationFreed misfires when the malloc sits in a nested block, so the kernel got rejected, just for the wrong reason.
Dominance alone isn't enough though, a write after the malloc can still reach the launch through a loop:
cudaMalloc(&A, n); // dominates the launch
for (...) {
k<<<1, 1>>>(A, B); // 2nd iteration: A == B
A = B;
}
So now, for each pointer arg we take the load that feeds the launch and find the write to that variable whose value it actually sees: it has to dominate the load, and every other write to the variable has to dominate it. If that write is a cudaMalloc, that's the root. If it's a store like C = A, we follow it to A and repeat. Two args are distinct only if their root cudaMallocs are different ops (before, we compared the allocas).
As a side effect, reallocating now works since the last malloc wins:
A = B;
cudaMalloc(&A, n); // overwrites A = B
k<<<1, 1>>>(A, B); // fine
Pointer swaps (tmp = A; A = B; B = tmp;) still get rejected. That needs tracking both variables together, I think it's fine to leave for now.
This change alone doesn't move anything on PolyBench: still 47/47 kernels and 131 noalias attrs, identical per kernel. Fix is in https://github.com/RiverDave/llvm-project/pull/30/changes/6e0075aef3587f2fa483cb3d7532d848a563eec2.
2. Pointers through integers
Yes, this one got noalias too. The host side is actually fine: (uintptr_t)A loads A and casts the value, so A still traces back to its own cudaMalloc. The problem is on the kernel side:
// foo(int *A, uintptr_t B)
%p = cir.cast int_to_ptr %B : !u64i -> !cir.ptr<!s32i>
cir.store %two, %p // writes A's buffer, but %p isn't based on %arg0
For now the body check rejects any int_to_ptr in the kernel or anything it calls (same walk as point 3). It's conservative, but PolyBench has zero int_to_ptr in device code, so it costs nothing there. Fix is in https://github.com/RiverDave/llvm-project/pull/30/changes/0e4f6fc68b31bc5cb9beb4acff19a4511ae21b15
What I'd like your take on is whether it's worth refining this. The idea is a bucket: every pointer arg of the launch starts in it, and we only look at integer args the kernel actually turns into pointers. For each of those we trace where the value came from on the host:
(uintptr_t)A with A in the bucket: eject A, keep the rest
The last rule is the important one, and it's what @steffenlarsen was getting at: not finding a link doesn't mean there isn't one.
tbl[0] = (uintptr_t)A;
uintptr_t B = tbl[0]; // trace stops at the load
k<<<1, 1>>>(A, B, C); // B could be A, C, anything
Without real code that passes pointers as ints I'm not sure it pays off, so I'd keep the conservative check for now. Do you know of workloads that do this?
3. Globals and callees
Yes, noalias would be incorrectly stamped here. The body check only walked the kernel itself, so bump() passed as "callee with no args". I checked it on the real CIR and it stamps both params. It's a real miscompile too; running opt -O3 on that shape:
; without noalias ; with noalias
store float 1.0, ptr %b store float 1.0, ptr %b
call void @bump() call void @bump()
%v = load float, ptr %b store float 1.0, ptr %a ; forwarded across bump()
store float %v, ptr %a
so it prints 1.0 instead of 2.0.
So the fix implemented walks every function the kernel can call and applies the same rules there. bump already breaks two of them (a non-builtin get_global, and a pointer loaded from memory), it just never got visited. For calls:
__nv_) or carries memory_effects with other = none
nvvm.read.ptx.sreg. (thread/block ids) and nvvm.barrier.cta.* (__syncthreads)
Declarations with memory attributes need some care too. For those I only trust other = none, where other is CIR's name for the default location in LLVM's memory(...): anything that isn't argument, inaccessible or errno memory, so globals included. pure doesn't cut it: Clang lowers it to memory(read) (CGCall.cpp), so a pure function can still read globals. That's enough to break noalias, since it also covers reads of anything the kernel writes:
__device__ __attribute__((pure)) float peek(); // defined in another TU, reads g_ptr[0]
k(a, b) { b[0] = 1.0f; a[0] = peek(); }
@steffenlarsen's variant (B's address written to some global and loaded on the device) is covered by the same rules: any pointer loaded from non-local memory, in the kernel or anything it calls, drops the fact.
This portion was fixed in https://github.com/RiverDave/llvm-project/pull/30/changes/0e4f6fc68b31bc5cb9beb4acff19a4511ae21b15.
------------
Any thoughts/suggestions would be great!
On a side note, did something happen during rebasing? There seems to be a lot of conflicts and a lot of changes in this PR now.
Yes! I'd rebased the repo but not this PR and had forgotten to push the fix. It should be alright now.
Instead of mentioning specific CUDA operations, maybe just say "offload memory allocation function call" or similar. Then we can later mention that CUDA is the only one supported, if that is the case. Conceptually the pass is relatively universal.
This description still reads a little noalias-specific. I would probably reword it to be more general, talking about the pass deriving "pointer facts" from the pointer arguments, then talk about what that means. Then noalias attachment can be a section.
continue guarantees termination of the loop block, so you don't need the else.
continue;
}
LDBG() << "GetMemberOp, non-zero index, stopping";
break;
I feel like there must be some switch mechanism that could be used here... But I'm too lazy to look for it. 😉
I would make this description more general, instead of primarily talking about noalias.
The body check lists the ops it rejects and accepts everything else, so any op that produces a pointer and isn't on the list gets through. Two cases where the pass stamps llvm.noalias on both params even though pp may legally hold b. In both, the host side passes two distinct cudaMalloc roots, set up like the kern_two test:
#include <string.h>
// static: keeps the host stub internal, so every launch site is visible.
static __global__ void k_memcpy(float **pp, float *b) {
float *p;
memcpy(&p, pp, sizeof(p)); // p = *pp, through a local slot
*p = *b; // p may equal b
}
static __global__ void k_xchg(float **pp, float *b) {
float *p = __atomic_exchange_n(pp, (float *)0, __ATOMIC_SEQ_CST);
*p = *b; // p may equal b
}
void host() {
float **pp, *b;
cudaMalloc((void **)&pp, sizeof(float *));
cudaMalloc((void **)&b, 16);
// Store b's address into *pp: the two roots are distinct allocations,
// but the kernel reaches b's memory through *pp.
cudaMemcpy(pp, &b, sizeof(float *), cudaMemcpyHostToDevice);
k_memcpy<<<1, 1>>>(pp, b);
k_xchg<<<1, 1>>>(pp, b);
}
Both kernels get noalias on pp and b, yet p and b refer to the same memory, so the attribute is wrong.
cir.copy into a slot, cir.asm with a pointer result, and loading a vector or record from memory and then extracting a pointer all have the same shape. Any new CIR op would reopen the hole without anyone noticing, so patching individual cases won't converge.
Every pointer value in the kernel and its walked callees must come from one of these:
1. a function param, a cir.alloca, or a __cuda_builtin_
global- a null constant
- a select of allowed pointers
- a bitcast or address-space cast, an array_to_ptrdecay, a ptr_stride, a get_member or a get_element of an allowed pointer
- a load from a clean local slot
Anything else rejects the kernel. A load of a record, vector or array that contains pointers rejects it too.
2. A local slot is clean only if all its uses are loads, stores into it of allowed pointers, alloca-preserving casts, or lifetime markers. Any other use makes it dirty: memcpy/cir.copy into it, atomics on it, or passing it to a callee. This is the device-side counterpart of classifyDevPtrWriters, so the two could probably share code.
I am wondering whether this is too string. I "believe" shared and constant memory is modeled as a pointer to a global in CUDA. Such cases will not alias, right? IIUC if you have something like:
static __global__ void gemm(float *A, float *B, float *C) {
__shared__ float tileA[16][16]; // cir.get_global @tileA -> pass gives up
tileA[ty][tx] = A[...];
...
}
although it should not.
I am wondering whether all of this is needed. I thought that:
template <class T>
static __inline__ __host__ cudaError_t cudaMalloc(T **devPtr, size_t size) {
return ::cudaMalloc((void **)(void *)devPtr, size);
}
So, I would guess that only checking for "cudaMalloc" is enough as CUDA defines it as externC.
By the way, the Demangle dependency currently breaks my BUILD_SHARED_LIBS
See comments below:
It's cases like this where I would love to have the wider "offload subdialect" for CIR, though I'm slightly unsure what kinds of malloc/free we are trying to avoid here. This would exclude my favorite getGlutenfree functions. Every program should have them.
We should try to see if there is a way we could flip the condition safely, i.e. if we can do whitelisting instead of blacklisting. The conservative approach is to always assume that we can't add noalias, then recognize when we can. That way we avoid new ops not covered by this that may silently cause invalid noalias. I am not sure whether it is feasible to do though.
This assumes Itanium mangling. Could we have cases where we could get whatever MSVC's mangling is called?
Got through a bit for now. Will return next week.
We could, but CIR does not support it at all now. An early exit in the pass if we have MSVC would be ok for now.
Yep, agreed, the previous check was too liberal. I've switched the body check to an allowlist as you describe, reusing classifyDevPtrWriters for the clean-slot part. Check: dd0bc02 (this PR)
One difference from your list: I allow any get_global, not only __cuda_builtin_*. A global can't be a cudaMalloc buffer, and loading a pointer out of one is still rejected. I think this also covers your __shared__ comment below.
Btw your exact snippet doesn't get stamped: &b goes to cudaMemcpy, so the host side treats b as escaped. It does reproduce with:
float *tmp = b;
cudaMemcpy(pp, &tmp, sizeof(float *), cudaMemcpyHostToDevice);
I am wondering whether all of this is needed. I thought that:
>> template <class T> > static __inline__ __host__ cudaError_t cudaMalloc(T **devPtr, size_t size) { > return ::cudaMalloc((void **)(void *)devPtr, size); > } >
> So, I would guess that only checking for "cudaMalloc" is enough as CUDA defines it as externC.
This was a deliberate decision and very roughly defensive programming. my concern was that the user could define functions such as cudaMallocAll, my::cudaMallocOrReuse(float**, unsigned long) which would get matched to the substring you point out to. I opted for the right combination including the templated brace "<" to avoid collisions with the runtime definitions. This might not be perfect and the user might be able to exploit it somehow, but it should serve us until we have a proper op for these allocations.
By the way, the Demangle dependency currently breaks my BUILD_SHARED_LIBS
I probably didn't encounter this given I built LLVM with static libs, claude helped me with the fix here: dc8e463 (this PR) -- let me know if that fixes your error.
getGlutenfree
🤣🤣
This chunk of code was removed after addressing Dinos' comment here: https://github.com/RiverDave/llvm-project/pull/30#discussion_r4241071448. We utilized this to string match runtime functions which may alter memory on kernel params. Besides that, the check is not needed anymore since a) we cannot see the bodies of runtime functions therefore we reject such cases and b) we may also reject cases where function calls have arguments derived from pointer params and c) we reject functions that yield ptr types.
But I do get your comment here and I think string matching is one of the things that will be a headache at least on this staging branch in the near future. Now that I think of in this patch we don't consider all the "malloc-like_ functions the CUDA/HIP runtime may posses, but I guess that's something we can tackle later?. So to your idea: yes, we will need offload ops to make this make this nicer to write. (that was something great from your prototype).
Same as my other description commit.
That would be llvm::TypeSwitch -- I looked at converting this into that, but it turned out to be just as long and less clear (at least to me). The thing is that this runs inside a loop: the cases would become lambdas, which can't continue/break, so each one would have to return an mlir::Value and the loop would act on that instead. If you'd prefer that still, let me know 🙂
Do check: https://github.com/RiverDave/llvm-project/pull/30#discussion_r4241071448 it should've addressed this.
So this check:
if (!callee.starts_with("_Z")) // "??$cudaMalloc@..." fails here
return false;
already rejects any sort of msvc mangling which may look like: ??$cudaMalloc@M@@YA?AW4cudaError@@PEAPEAM_K@Z (Btw, I just happened to know that's MSVC's mangling, it looks quite interesting I must say 🤣).
Is there something that we can use in ABI, use that to check if we are in microsoft and exit early. I suggest you do this check first thing once you load the module. isHost && ABIisMicrosoft -> NIY.
Whichever you prefer! If it isn't an obviously better solution, I have no strong preference.
Overall this looks good to me. There are some limitations I though off:
1. You are not handling asm instructions, some of those may take addresses or modify those.
2. What happens if device code takes the address of some functions, stores it a global variable, other kernels launch that device function through that global. I am not sure this is even possible, but if it is, you should add a limitation on the current PR.
Overall this looks good to me. There are some limitations I thought of:
> 1. You are not handling asm instructions, some of those may take addresses or modify those.
2. What happens if device code takes the address of some functions, stores it a global variable, other kernels launch that device function through that global. I am not sure this is even possible, but if it is, you should add a limitation on the current PR.
Great! Few things:
1. At this point, I think it's fair to prohibit inline asm instructions (Its possible we could handle them in a follow-up PR). This commit handles that: https://github.com/RiverDave/llvm-project/pull/30/changes/f68321cbca97bb5413f6280deefff3a1c454cec7
2. We'd handled cases like this already, see the following test case: https://github.com/RiverDave/llvm-project/pull/30/changes/6c5f2a025950fc08c845e481eca4bedf6a921930
Lastly, I've added the early exit when encountering MSVC triples for this pass. (I don't believe current MSVC support reaches CIR post-codegen today, but still guess this acts as defensive programming for us :D).
koparasy
RiverDave
Runs over a cir.offload.container and proves, from all visible host launches of a device kernel, that each pointer parameter points into a distinct cudaMalloc slot and that the kernel body cannot reach the pointer through any other path: no address-taken global, loaded pointer, forwarded value, escape or in-kernel allocation. When every launch and body path agrees, llvm.noalias is attached in place to the existing kernel parameters. No clones are created, no diagnostics are emitted.
Unchecked allocations are accepted: a failed cudaMalloc dereferences an invalid pointer at the launch, which is undefined behavior rather than an aliasing scenario the fact has to model. Only a free before the launch invalidates a slot.
The proof is kernel-wide and conservative: a repeated allocation root, an unprovable argument or an unprovable body path drops every launch-derived annotation for that kernel. Pass statistics and remarks were also implemented (I hope it doesn't add a lot of noise), but I tried to be as detailed as possible when emitting reasons when different events happen.
The numbers
(The following data was synthesized with assistance from LLM's, nonetheless it was verified by me)
I ran this on internal linkage kernels (forcing static on all benchmarks)
polybenchGpu,experiment/static-kernels-pr25atf5613c4, built by81d3b96(polybench-gpu-audit). sm_86 on an A10 24 GB, CUDA 12.8, driver 570.148.08. 20 benchmarks; sizes via-DPB_SCALE=k(spatial dims ×k, iterations held); SYR2K dropped for an invalid x2 timing.Protocol. 3 warmup + 8 samples, all ran serially.
S = mean(t_off)/mean(t_on):S > 1is faster with the change on. GPU-region is the benchmark's own timer around launches and sync; wall is the whole process minus compilation and CPU-reference validation.What ran. Merge arm in every block; arms differ only in the last column.
(Note that I refer here to: DKE → Dead Kernel Elimination, KACP → Kernel argument constant prop)
| Block | LLVM | Schedule (merge arm) | Arms differ by |
|---|---|---|---|
| This pass alone |
fbda065af219|mem2reg, sccp→DKE→launch-noalias|-no-launch-noalias|| Whole pipeline |
7a94fd56356d|mem2reg, sccp, inline, symbol-dce, mem2reg, sccp→ drop unreferenced host wrappers →KACP, canonicalize, DKE, launch-noalias| CIR vs CIR-merge || KACP ablation |
7a94fd56356d| as above, noalias off in both arms |inline+KACPoff → on |Whole merge pipeline — this pass plus KACP (host-device constant propagation):
| Size | GPU-region
S| WallS| Wall reduction ||---|---:|---:|---:|
| 1× | 1.716× | 1.194× | 16.3% |
| 2× | 1.684× | 1.243× | 19.6% |
| 4× | 1.636× | 1.249× | 19.9% |
GPU-region drops 4.7% from 1× to 4×, wall keeps climbing (GPU work is a bigger share of the process as sizes grow). CORR/COVAR drive the drop (7.04/7.17× → 4.59/4.64×, both memory-bound); gemm gains (1.92× → 2.94×).
This pass alone. Pass ON vs OFF, cross-run, merge arm; CI95 by the delta method (n = 8).
| Metric | Value |
|---|---|
| geomean
S| 1.672× GPU-region || CI95 | 15/21 fully above 1, 5 straddle 1, 1 below (convolution-3d 0.988×) |
| re-run, 23 samples/bench | 2mm 2.286×, correlation 7.166×, covariance 7.073×, gramschmidt 2.241×, lu 1.006× [0.990, 1.022] |
| compile cost |
+0.006 sper benchmark, ~0.3% |It's important to note that KACP by itself did not yield speedups. For instance: noalias off in both arms, KACP stack off → on:
| Size | Merge-arm
S||---|---:|
| 1× | 1.0016× |
| 2× | 0.9996× |
Runtime-neutral. The runtime gain above is this pass; KACP's is code shape and size.
Emitted code (merged SASS):
LDC.E.CONSTANT, the read-only formload inputs → accumulate → store intermediatebecomesload inputs → accumulate…store completed resultApplicability. 47/47 kernels stamped (131
llvm.noaliasattrs), 0 misses. Bounded by the closed-world precondition: a kernel whose host stub stays externally visible has launch sites that cannot all be proven, and is left untouched.Caveats
4× was timing-only (no validation) and ran on a different A10; 1×/2× validation was not universally clean; DOITGEN and Jacobi-2D did not actually scale; SYR2K is excluded. The whole-pipeline rows measure the pipeline, not this pass.