← Back to Pull requests

[CIR][offload-merge] Stamp launch-derived noalias on kernel parameters #30

Merged
RiverDave merged 19 files (3872 lines) on Oct 28, 2026 19:38 UTC
View on GitHub
RiverDave RiverDave commented on Sep 17, 2026 06:49 UTC
Author

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-pr25 at f5613c4, built by 81d3b96 (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 > 1 is 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 + KACP off → on |

Whole merge pipeline — this pass plus KACP (host-device constant propagation):

| Size | GPU-region S | Wall S | 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 s per 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):

  • accumulation stores leave the inner loops; accumulation stays in registers

  • eligible input loads become LDC.E.CONSTANT, the read-only form

  • load inputs → accumulate → store intermediate becomes load inputs → accumulate … store completed result

  • holds at 4× (CORR/COVAR x2 vs x4 differ only in dimension-related immediates)
  • Applicability. 47/47 kernels stamped (131 llvm.noalias attrs), 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.

    Diff: 3872 lines (+3872 / -0) across 19 files Reviewer: koparasy Review duration: 59809m
    All Vouch review confidence checks passed
    Residual risk 0.08 = Change Risk (0.72) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 3872 lines diff across 19 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.86 · 5 substantive comment(s)
    0.86
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    42 items
    RiverDave RiverDave commented on Sep 17, 2026 06:51 UTC
    Author

    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×) |

    steffenlarsen steffenlarsen commented on code on Sep 18, 2026 07:09 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -23,7 +23,19 @@ using namespace cir;
     
     static constexpr unsigned MaxLookupDepth = 6;
     
    -mlir::Value CIRBasicAliasAnalysis::getUnderlyingObject(mlir::Value val) {
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (castOp.isAllocaPreservingCast() ||
    +        castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +      val = castOp.getSrc();
    +      continue;
    +    }
    +    break;
    +  }

    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();
      }
    

    steffenlarsen steffenlarsen commented on Sep 18, 2026 07:15 UTC
    Reviewer

    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

    RiverDave RiverDave commented on code on Sep 18, 2026 14:18 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -23,7 +23,19 @@ using namespace cir;
     
     static constexpr unsigned MaxLookupDepth = 6;
     
    -mlir::Value CIRBasicAliasAnalysis::getUnderlyingObject(mlir::Value val) {
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (castOp.isAllocaPreservingCast() ||
    +        castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +      val = castOp.getSrc();
    +      continue;
    +    }
    +    break;
    +  }

    Done!

    RiverDave RiverDave commented on Sep 18, 2026 14:38 UTC
    Author

    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.

    koparasy koparasy commented on Sep 25, 2026 13:43 UTC
    Reviewer

    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?

    steffenlarsen steffenlarsen commented on Sep 28, 2026 11:05 UTC
    Contributor

    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.

    steffenlarsen steffenlarsen commented on Sep 28, 2026 11:06 UTC
    Contributor

    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.

    RiverDave RiverDave commented on Oct 02, 2026 06:35 UTC
    Author

    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:

  • exactly (uintptr_t)A with A in the bucket: eject A, keep the rest

  • exactly the address of an allocation that isn't passed as a pointer: eject nothing

  • anything we can't trace (arithmetic, a load, a call): eject everything
  • 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:

  • callee has a body: walk it

  • callee is only a declaration: reject, unless it's libdevice (__nv_) or carries memory_effects with other = none

  • indirect call: reject

  • intrinsics: only 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!

    RiverDave RiverDave commented on Oct 02, 2026 06:36 UTC
    Author

    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.

    steffenlarsen steffenlarsen commented on code on Oct 02, 2026 13:39 UTC
    Code Review
    clang/include/clang/CIR/Dialect/Passes.td:1
    @@ -374,4 +374,34 @@ def OffloadLaunchBoundsPropagation
       let dependentDialects = ["cir::CIRDialect"];
     }
     
    +def OffloadPointerFacts
    +    : Pass<"cir-offload-pointer-facts", "mlir::ModuleOp"> {
    +  let summary = "Stamp launch-derived pointer facts on kernel parameters";
    +  let description = [{
    +    Runs on an offload container module (a module carrying the
    +    `cir.offload.container` unit attribute) and is a no-op elsewhere. For every
    +    device kernel, proves from
    +    all of its visible host launches that each pointer parameter points into a
    +    distinct `cudaMalloc` allocation and that no address-taken global, loaded

    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.

    steffenlarsen steffenlarsen commented on code on Oct 02, 2026 13:40 UTC
    Code Review
    clang/include/clang/CIR/Dialect/Passes.td:1
    @@ -374,4 +374,34 @@ def OffloadLaunchBoundsPropagation
       let dependentDialects = ["cir::CIRDialect"];
     }
     
    +def OffloadPointerFacts
    +    : Pass<"cir-offload-pointer-facts", "mlir::ModuleOp"> {
    +  let summary = "Stamp launch-derived pointer facts on kernel parameters";
    +  let description = [{
    +    Runs on an offload container module (a module carrying the
    +    `cir.offload.container` unit attribute) and is a no-op elsewhere. For every
    +    device kernel, proves from
    +    all of its visible host launches that each pointer parameter points into a
    +    distinct `cudaMalloc` allocation and that no address-taken global, loaded
    +    pointer, forwarded value, escape, or in-kernel allocation can reach the
    +    parameter. When every launch and body path agrees, `noalias` is attached in
    +    place to the existing kernel parameters.

    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.

    steffenlarsen steffenlarsen commented on code on Oct 02, 2026 14:14 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -233,6 +233,123 @@ static PointerOffset decomposePointer(mlir::Value val,
       return {val, offset};
     }
     
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (!castOp.isAllocaPreservingCast() &&
    +        castOp.getKind() != cir::CastKind::array_to_ptrdecay)
    +      break;
    +    val = castOp.getSrc();
    +  }
    +  return val;
    +}
    +
    +mlir::Value cir::getUnderlyingObject(mlir::Value val) {
    +  LDBG() << "Getting underlying object for: " << val;
    +
    +  for (unsigned depth = 0; depth < MaxLookupDepth; ++depth) {
    +    mlir::Operation *defOp = val.getDefiningOp();
    +    if (!defOp) {
    +      LDBG() << "No defining operation, stopping";
    +      break; // Block argument (e.g. function parameter) — stop here.
    +    }
    +
    +    // Bitcast and address-space casts don't change the underlying object.
    +    // array_to_ptrdecay produces an element pointer to the same storage as
    +    // the array pointer, so strip through it too.
    +    if (auto castOp = mlir::dyn_cast<cir::CastOp>(defOp)) {
    +      if (castOp.isAllocaPreservingCast() ||
    +          castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +        LDBG() << "Walking past cast operation";
    +        val = castOp.getSrc();
    +        continue;
    +      }
    +      LDBG() << "Opaque cast operation, stopping";
    +      break;
    +    }
    +
    +    // Pointer stride: only strip through when we can prove the access stays
    +    // within the bounds of the underlying allocation.
    +    if (auto strideOp = mlir::dyn_cast<cir::PtrStrideOp>(defOp)) {
    +      auto constOp = strideOp.getStride().getDefiningOp<cir::ConstantOp>();
    +      if (constOp) {
    +        if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(constOp.getValue())) {
    +          APInt stride = intAttr.getValue();
    +
    +          // Zero stride is trivially in-bounds.
    +          if (stride.isZero()) {
    +            LDBG() << "Walking past zero-strided PtrStrideOp";
    +            val = strideOp.getBase();
    +            continue;
    +          }
    +        }
    +      }
    +      // Dynamic stride or unverifiable bounds — stop here conservatively.
    +      LDBG() << "Non-zero or dynamic PtrStrideOp, stopping";
    +      break;
    +    }
    +
    +    // Handle special cases for zero-offset sub-object accesses.
    +    if (auto op = mlir::dyn_cast<cir::GetMemberOp>(defOp)) {
    +      if (op.getIndex() == 0) {
    +        LDBG() << "GetMemberOp[0], following to underlying object";
    +        val = op.getAddr();
    +        continue;
    +      } else {
    +        LDBG() << "GetMemberOp, non-zero index, stopping";
    +        break;
    +      }

    continue guarantees termination of the loop block, so you don't need the else.

            continue;
          }
          LDBG() << "GetMemberOp, non-zero index, stopping";
          break;
    

    steffenlarsen steffenlarsen commented on code on Oct 02, 2026 14:30 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -233,6 +233,123 @@ static PointerOffset decomposePointer(mlir::Value val,
       return {val, offset};
     }
     
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (!castOp.isAllocaPreservingCast() &&
    +        castOp.getKind() != cir::CastKind::array_to_ptrdecay)
    +      break;
    +    val = castOp.getSrc();
    +  }
    +  return val;
    +}
    +
    +mlir::Value cir::getUnderlyingObject(mlir::Value val) {
    +  LDBG() << "Getting underlying object for: " << val;
    +
    +  for (unsigned depth = 0; depth < MaxLookupDepth; ++depth) {
    +    mlir::Operation *defOp = val.getDefiningOp();
    +    if (!defOp) {
    +      LDBG() << "No defining operation, stopping";
    +      break; // Block argument (e.g. function parameter) — stop here.
    +    }
    +
    +    // Bitcast and address-space casts don't change the underlying object.
    +    // array_to_ptrdecay produces an element pointer to the same storage as
    +    // the array pointer, so strip through it too.
    +    if (auto castOp = mlir::dyn_cast<cir::CastOp>(defOp)) {
    +      if (castOp.isAllocaPreservingCast() ||
    +          castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +        LDBG() << "Walking past cast operation";
    +        val = castOp.getSrc();
    +        continue;
    +      }
    +      LDBG() << "Opaque cast operation, stopping";
    +      break;
    +    }
    +
    +    // Pointer stride: only strip through when we can prove the access stays
    +    // within the bounds of the underlying allocation.
    +    if (auto strideOp = mlir::dyn_cast<cir::PtrStrideOp>(defOp)) {
    +      auto constOp = strideOp.getStride().getDefiningOp<cir::ConstantOp>();
    +      if (constOp) {
    +        if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(constOp.getValue())) {
    +          APInt stride = intAttr.getValue();
    +
    +          // Zero stride is trivially in-bounds.
    +          if (stride.isZero()) {
    +            LDBG() << "Walking past zero-strided PtrStrideOp";
    +            val = strideOp.getBase();
    +            continue;
    +          }
    +        }
    +      }
    +      // Dynamic stride or unverifiable bounds — stop here conservatively.
    +      LDBG() << "Non-zero or dynamic PtrStrideOp, stopping";
    +      break;
    +    }
    +
    +    // Handle special cases for zero-offset sub-object accesses.
    +    if (auto op = mlir::dyn_cast<cir::GetMemberOp>(defOp)) {
    +      if (op.getIndex() == 0) {
    +        LDBG() << "GetMemberOp[0], following to underlying object";
    +        val = op.getAddr();
    +        continue;
    +      } else {
    +        LDBG() << "GetMemberOp, non-zero index, stopping";
    +        break;
    +      }
    +    }
    +    if (auto op = mlir::dyn_cast<cir::GetElementOp>(defOp)) {
    +      cir::IntAttr index;
    +      if (auto constOp = op.getIndex().getDefiningOp<cir::ConstantOp>())
    +        index = mlir::dyn_cast<cir::IntAttr>(constOp.getValue());
    +      if (index && index.getValue().isZero()) {
    +        LDBG() << "GetElementOp[0], following to underlying object";
    +        val = op.getBase();
    +        continue;
    +      }
    +      LDBG() << "GetElementOp, non-zero or dynamic index, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::BaseClassAddrOp>(defOp)) {
    +      // A zero byte offset means the base subobject starts at the same address
    +      // as the derived object.
    +      if (op.getOffset().isZero()) {
    +        LDBG() << "BaseClassAddrOp[0], following to underlying object";
    +        val = op.getDerivedAddr();
    +        continue;
    +      }
    +      LDBG() << "BaseClassAddrOp, non-zero offset, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::DerivedClassAddrOp>(defOp)) {
    +      // The offset is stored unsigned but applied as a negative adjustment. A
    +      // zero offset means the derived object starts at the same address as the
    +      // base subobject.
    +      if (op.getOffset().isZero()) {
    +        LDBG() << "DerivedClassAddrOp[0], following to underlying object";
    +        val = op.getBaseAddr();
    +        continue;
    +      }
    +      LDBG() << "DerivedClassAddrOp, non-zero offset, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::ComplexRealPtrOp>(defOp)) {
    +      LDBG() << "Getting input pointer for ComplexRealPtrOp";
    +      val = op.getOperand();
    +      continue;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::ComplexImagPtrOp>(defOp)) {
    +      LDBG() << "ComplexImagPtrOp, 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. 😉

    steffenlarsen steffenlarsen commented on code on Oct 02, 2026 14:31 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,610 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.

    I would make this description more general, instead of primarily talking about noalias.

    koparasy koparasy commented on code on Oct 05, 2026 14:04 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {

    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.

    koparasy koparasy commented on code on Oct 05, 2026 14:10 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;

    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.

    koparasy koparasy commented on code on Oct 05, 2026 14:19 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))
    +    return false;
    +  std::string demangled = llvm::demangle(callee.str());
    +  return llvm::StringRef(demangled).contains("cudaMalloc<");

    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.

    koparasy koparasy commented on code on Oct 05, 2026 14:19 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))
    +    return false;
    +  std::string demangled = llvm::demangle(callee.str());
    +  return llvm::StringRef(demangled).contains("cudaMalloc<");

    By the way, the Demangle dependency currently breaks my BUILD_SHARED_LIBS

    koparasy koparasy commented on Oct 05, 2026 14:20 UTC
    Reviewer

    See comments below:

    steffenlarsen steffenlarsen commented on code on Oct 09, 2026 14:45 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {

    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.

    steffenlarsen steffenlarsen commented on code on Oct 09, 2026 14:55 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;

    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.

    steffenlarsen steffenlarsen commented on code on Oct 09, 2026 14:58 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))

    This assumes Itanium mangling. Could we have cases where we could get whatever MSVC's mangling is called?

    steffenlarsen steffenlarsen commented on Oct 09, 2026 15:02 UTC
    Reviewer

    Got through a bit for now. Will return next week.

    koparasy koparasy commented on code on Oct 09, 2026 17:55 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))

    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.

    RiverDave RiverDave commented on code on Oct 11, 2026 09:34 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {

    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);
    

    RiverDave RiverDave commented on code on Oct 11, 2026 11:00 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))
    +    return false;
    +  std::string demangled = llvm::demangle(callee.str());
    +  return llvm::StringRef(demangled).contains("cudaMalloc<");

    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.

    RiverDave RiverDave commented on code on Oct 11, 2026 11:04 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))
    +    return false;
    +  std::string demangled = llvm::demangle(callee.str());
    +  return llvm::StringRef(demangled).contains("cudaMalloc<");

    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.

    RiverDave RiverDave commented on code on Oct 11, 2026 11:29 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {

    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).

    RiverDave RiverDave commented on code on Oct 11, 2026 11:43 UTC
    Code Review
    clang/include/clang/CIR/Dialect/Passes.td:1
    @@ -374,4 +374,34 @@ def OffloadLaunchBoundsPropagation
       let dependentDialects = ["cir::CIRDialect"];
     }
     
    +def OffloadPointerFacts
    +    : Pass<"cir-offload-pointer-facts", "mlir::ModuleOp"> {
    +  let summary = "Stamp launch-derived pointer facts on kernel parameters";
    +  let description = [{
    +    Runs on an offload container module (a module carrying the
    +    `cir.offload.container` unit attribute) and is a no-op elsewhere. For every
    +    device kernel, proves from
    +    all of its visible host launches that each pointer parameter points into a
    +    distinct `cudaMalloc` allocation and that no address-taken global, loaded
    +    pointer, forwarded value, escape, or in-kernel allocation can reach the
    +    parameter. When every launch and body path agrees, `noalias` is attached in
    +    place to the existing kernel parameters.
    RiverDave RiverDave commented on code on Oct 11, 2026 11:43 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,610 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.

    Same as my other description commit.

    RiverDave RiverDave commented on code on Oct 11, 2026 11:49 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -233,6 +233,123 @@ static PointerOffset decomposePointer(mlir::Value val,
       return {val, offset};
     }
     
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (!castOp.isAllocaPreservingCast() &&
    +        castOp.getKind() != cir::CastKind::array_to_ptrdecay)
    +      break;
    +    val = castOp.getSrc();
    +  }
    +  return val;
    +}
    +
    +mlir::Value cir::getUnderlyingObject(mlir::Value val) {
    +  LDBG() << "Getting underlying object for: " << val;
    +
    +  for (unsigned depth = 0; depth < MaxLookupDepth; ++depth) {
    +    mlir::Operation *defOp = val.getDefiningOp();
    +    if (!defOp) {
    +      LDBG() << "No defining operation, stopping";
    +      break; // Block argument (e.g. function parameter) — stop here.
    +    }
    +
    +    // Bitcast and address-space casts don't change the underlying object.
    +    // array_to_ptrdecay produces an element pointer to the same storage as
    +    // the array pointer, so strip through it too.
    +    if (auto castOp = mlir::dyn_cast<cir::CastOp>(defOp)) {
    +      if (castOp.isAllocaPreservingCast() ||
    +          castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +        LDBG() << "Walking past cast operation";
    +        val = castOp.getSrc();
    +        continue;
    +      }
    +      LDBG() << "Opaque cast operation, stopping";
    +      break;
    +    }
    +
    +    // Pointer stride: only strip through when we can prove the access stays
    +    // within the bounds of the underlying allocation.
    +    if (auto strideOp = mlir::dyn_cast<cir::PtrStrideOp>(defOp)) {
    +      auto constOp = strideOp.getStride().getDefiningOp<cir::ConstantOp>();
    +      if (constOp) {
    +        if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(constOp.getValue())) {
    +          APInt stride = intAttr.getValue();
    +
    +          // Zero stride is trivially in-bounds.
    +          if (stride.isZero()) {
    +            LDBG() << "Walking past zero-strided PtrStrideOp";
    +            val = strideOp.getBase();
    +            continue;
    +          }
    +        }
    +      }
    +      // Dynamic stride or unverifiable bounds — stop here conservatively.
    +      LDBG() << "Non-zero or dynamic PtrStrideOp, stopping";
    +      break;
    +    }
    +
    +    // Handle special cases for zero-offset sub-object accesses.
    +    if (auto op = mlir::dyn_cast<cir::GetMemberOp>(defOp)) {
    +      if (op.getIndex() == 0) {
    +        LDBG() << "GetMemberOp[0], following to underlying object";
    +        val = op.getAddr();
    +        continue;
    +      } else {
    +        LDBG() << "GetMemberOp, non-zero index, stopping";
    +        break;
    +      }
    +    }
    +    if (auto op = mlir::dyn_cast<cir::GetElementOp>(defOp)) {
    +      cir::IntAttr index;
    +      if (auto constOp = op.getIndex().getDefiningOp<cir::ConstantOp>())
    +        index = mlir::dyn_cast<cir::IntAttr>(constOp.getValue());
    +      if (index && index.getValue().isZero()) {
    +        LDBG() << "GetElementOp[0], following to underlying object";
    +        val = op.getBase();
    +        continue;
    +      }
    +      LDBG() << "GetElementOp, non-zero or dynamic index, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::BaseClassAddrOp>(defOp)) {
    +      // A zero byte offset means the base subobject starts at the same address
    +      // as the derived object.
    +      if (op.getOffset().isZero()) {
    +        LDBG() << "BaseClassAddrOp[0], following to underlying object";
    +        val = op.getDerivedAddr();
    +        continue;
    +      }
    +      LDBG() << "BaseClassAddrOp, non-zero offset, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::DerivedClassAddrOp>(defOp)) {
    +      // The offset is stored unsigned but applied as a negative adjustment. A
    +      // zero offset means the derived object starts at the same address as the
    +      // base subobject.
    +      if (op.getOffset().isZero()) {
    +        LDBG() << "DerivedClassAddrOp[0], following to underlying object";
    +        val = op.getBaseAddr();
    +        continue;
    +      }
    +      LDBG() << "DerivedClassAddrOp, non-zero offset, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::ComplexRealPtrOp>(defOp)) {
    +      LDBG() << "Getting input pointer for ComplexRealPtrOp";
    +      val = op.getOperand();
    +      continue;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::ComplexImagPtrOp>(defOp)) {
    +      LDBG() << "ComplexImagPtrOp, stopping";
    +      break;
    +    }

    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 🙂

    RiverDave RiverDave commented on code on Oct 11, 2026 11:52 UTC
    Code Review
    clang/include/clang/CIR/Dialect/Passes.td:1
    @@ -374,4 +374,34 @@ def OffloadLaunchBoundsPropagation
       let dependentDialects = ["cir::CIRDialect"];
     }
     
    +def OffloadPointerFacts
    +    : Pass<"cir-offload-pointer-facts", "mlir::ModuleOp"> {
    +  let summary = "Stamp launch-derived pointer facts on kernel parameters";
    +  let description = [{
    +    Runs on an offload container module (a module carrying the
    +    `cir.offload.container` unit attribute) and is a no-op elsewhere. For every
    +    device kernel, proves from
    +    all of its visible host launches that each pointer parameter points into a
    +    distinct `cudaMalloc` allocation and that no address-taken global, loaded
    RiverDave RiverDave commented on code on Oct 11, 2026 11:52 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -233,6 +233,123 @@ static PointerOffset decomposePointer(mlir::Value val,
       return {val, offset};
     }
     
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (!castOp.isAllocaPreservingCast() &&
    +        castOp.getKind() != cir::CastKind::array_to_ptrdecay)
    +      break;
    +    val = castOp.getSrc();
    +  }
    +  return val;
    +}
    +
    +mlir::Value cir::getUnderlyingObject(mlir::Value val) {
    +  LDBG() << "Getting underlying object for: " << val;
    +
    +  for (unsigned depth = 0; depth < MaxLookupDepth; ++depth) {
    +    mlir::Operation *defOp = val.getDefiningOp();
    +    if (!defOp) {
    +      LDBG() << "No defining operation, stopping";
    +      break; // Block argument (e.g. function parameter) — stop here.
    +    }
    +
    +    // Bitcast and address-space casts don't change the underlying object.
    +    // array_to_ptrdecay produces an element pointer to the same storage as
    +    // the array pointer, so strip through it too.
    +    if (auto castOp = mlir::dyn_cast<cir::CastOp>(defOp)) {
    +      if (castOp.isAllocaPreservingCast() ||
    +          castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +        LDBG() << "Walking past cast operation";
    +        val = castOp.getSrc();
    +        continue;
    +      }
    +      LDBG() << "Opaque cast operation, stopping";
    +      break;
    +    }
    +
    +    // Pointer stride: only strip through when we can prove the access stays
    +    // within the bounds of the underlying allocation.
    +    if (auto strideOp = mlir::dyn_cast<cir::PtrStrideOp>(defOp)) {
    +      auto constOp = strideOp.getStride().getDefiningOp<cir::ConstantOp>();
    +      if (constOp) {
    +        if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(constOp.getValue())) {
    +          APInt stride = intAttr.getValue();
    +
    +          // Zero stride is trivially in-bounds.
    +          if (stride.isZero()) {
    +            LDBG() << "Walking past zero-strided PtrStrideOp";
    +            val = strideOp.getBase();
    +            continue;
    +          }
    +        }
    +      }
    +      // Dynamic stride or unverifiable bounds — stop here conservatively.
    +      LDBG() << "Non-zero or dynamic PtrStrideOp, stopping";
    +      break;
    +    }
    +
    +    // Handle special cases for zero-offset sub-object accesses.
    +    if (auto op = mlir::dyn_cast<cir::GetMemberOp>(defOp)) {
    +      if (op.getIndex() == 0) {
    +        LDBG() << "GetMemberOp[0], following to underlying object";
    +        val = op.getAddr();
    +        continue;
    +      } else {
    +        LDBG() << "GetMemberOp, non-zero index, stopping";
    +        break;
    +      }
    RiverDave RiverDave commented on code on Oct 11, 2026 11:52 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    RiverDave RiverDave commented on code on Oct 11, 2026 11:52 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    RiverDave RiverDave commented on code on Oct 11, 2026 11:58 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))

    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 🤣).

    koparasy koparasy commented on code on Oct 12, 2026 15:32 UTC
    Code Review
    clang/lib/CIR/Dialect/Transforms/OffloadOpt/PointerFacts.cpp:1
    @@ -0,0 +1,640 @@
    +//===- PointerFacts.cpp - Launch-derived pointer facts on kernel params ---===//
    +//
    +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
    +// See https://llvm.org/LICENSE.txt for license information.
    +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
    +//
    +//===----------------------------------------------------------------------===//
    +//
    +// Stamps `llvm.noalias` on device-kernel pointer parameters when every visible
    +// launch of the kernel passes pointers that provably come from distinct
    +// cudaMalloc calls and the kernel body cannot reach the pointer through any
    +// other path. A launch argument's root is the cudaMalloc whose result reaches
    +// the launch: it dominates the read of the slot and every other write to the
    +// slot dominates it. Unchecked allocations are accepted; only a free before the
    +// launch invalidates a slot.
    +//
    +// The analysis is conservative and kernel-wide: a repeated root, an unprovable
    +// argument, or an unprovable body path drops every launch-derived annotation
    +// for that kernel. It attaches attributes in place, creates no clones, emits no
    +// diagnostics, and always succeeds.
    +//
    +//===----------------------------------------------------------------------===//
    +
    +#include "mlir/IR/Remarks.h"
    +#include "clang/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.h"
    +#include "clang/CIR/Dialect/IR/CIRDialect.h"
    +#include "clang/CIR/Dialect/IR/CIROpsEnums.h"
    +#include "clang/CIR/Dialect/Passes.h"
    +#include "clang/CIR/Dialect/Transforms/OffloadOpt/KernelBindingTable.h"
    +#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
    +#include "mlir/IR/BuiltinAttributes.h"
    +#include "mlir/IR/Dominance.h"
    +#include "llvm/ADT/SmallPtrSet.h"
    +#include "llvm/ADT/SmallVector.h"
    +#include "llvm/Demangle/Demangle.h"
    +#include "llvm/Support/DebugLog.h"
    +
    +#define DEBUG_TYPE "cir-offload-pointer-facts"
    +
    +namespace mlir {
    +#define GEN_PASS_DEF_OFFLOADPOINTERFACTS
    +#include "clang/CIR/Dialect/Passes.h.inc"
    +} // namespace mlir
    +
    +using namespace mlir;
    +using namespace cir;
    +
    +namespace {
    +
    +static constexpr llvm::StringLiteral kRemarkName = "OffloadPointerFacts";
    +static constexpr llvm::StringLiteral kRemarkCategory = "cir-offload-noalias";
    +
    +static void remarkSkipped(cir::FuncOp anchor, llvm::StringRef kernelName,
    +                          llvm::StringRef reason, size_t numLaunchSites) {
    +  if (!anchor)
    +    return;
    +  remark::missed(anchor.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("no launch-derived noalias")
    +      << remark::reason("{0}", reason)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +static void remarkStamped(cir::FuncOp kernel, llvm::StringRef kernelName,
    +                          size_t numParams, size_t numLaunchSites) {
    +  remark::passed(kernel.getLoc(), remark::RemarkOpts::name(kRemarkName)
    +                                      .category(kRemarkCategory)
    +                                      .function(kernelName))
    +      << remark::add("stamped llvm.noalias on kernel pointer parameter(s)")
    +      << remark::metric("pointerParams", numParams)
    +      << remark::metric("launchSites", numLaunchSites);
    +}
    +
    +// The cudaMalloc out-parameter slot a launch argument derives from.
    +struct SlotRoot {
    +  Value slot;
    +  cir::CallOp malloc;
    +};
    +
    +static bool resolveValueToRoot(Value v, SlotRoot &out, DominanceInfo &dom,
    +                               unsigned depth);
    +
    +// Whether `v` transitively derives from a pointer parameter of `kernel`. Only
    +// pointer-typed operands are followed, so comparing a pointer against null and
    +// using the boolean result does not count as a derivation.
    +static bool derivesFromPointerParam(Value v, cir::FuncOp kernel) {
    +  if (!mlir::isa<cir::PointerType>(v.getType()))
    +    return false;
    +
    +  llvm::SmallPtrSet<Value, 16> visited;
    +  llvm::SmallVector<Value, 8> work{v};
    +  while (!work.empty()) {
    +    Value cur = work.pop_back_val();
    +    if (!visited.insert(cur).second)
    +      continue;
    +    if (auto arg = mlir::dyn_cast<BlockArgument>(cur)) {
    +      if (arg.getOwner()->getParentOp() == kernel.getOperation())
    +        return true;
    +      // Region arguments are not followed to their parent operands: fine today
    +      // (CIR loops carry no value region args), but derivations through them
    +      // would be missed if that changes.
    +      continue;
    +    }
    +    Operation *def = cur.getDefiningOp();
    +    if (!def)
    +      continue;
    +    // Pointer values round-trip through local stack slots: CIRGen materializes
    +    // kernel parameters (and other address-taken values) into allocas. Follow
    +    // the stores into such a slot so a reloaded pointer still counts as
    +    // derived.
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(def))
    +      if (auto slot = load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        for (Operation *user : slot->getUsers())
    +          if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +            if (mlir::isa<cir::PointerType>(store.getValue().getType()))
    +              work.push_back(store.getValue());
    +        continue;
    +      }
    +    for (Value operand : def->getOperands())
    +      if (mlir::isa<cir::PointerType>(operand.getType()))
    +        work.push_back(operand);
    +  }
    +  return false;
    +}
    +
    +// CUDA builtin variables (__cuda_builtin_blockIdx_t, ...) are compiler-owned
    +// records in the constant bank; they can never alias device allocations.
    +static bool isCudaBuiltinVar(cir::GetGlobalOp getGlobal) {
    +  auto ptrTy = mlir::dyn_cast<cir::PointerType>(getGlobal.getResult().getType());
    +  if (!ptrTy)
    +    return false;
    +  auto rec = mlir::dyn_cast<cir::RecordType>(ptrTy.getPointee());
    +  return rec && rec.getName().getValue().starts_with("__cuda_builtin_");
    +}
    +
    +// A local slot holding a pointer derived from a kernel parameter carries that
    +// pointer on the stack; forwarding the slot itself to a callee can leak it.
    +static bool slotHoldsDerivedPointer(Value slot, cir::FuncOp kernel) {
    +  if (!slot.getDefiningOp<cir::AllocaOp>())
    +    return false;
    +  for (Operation *user : slot.getUsers())
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(user))
    +      if (derivesFromPointerParam(store.getValue(), kernel))
    +        return true;
    +  return false;
    +}
    +
    +// A callee without a body whose memory behavior is known: libdevice math
    +// (`__nv_*`, a name reserved to the implementation) or a declaration that
    +// touches no memory besides its arguments. Only consulted for declarations, so
    +// a user-defined body under one of these names is still walked.
    +static bool isKnownSafeDeclaration(cir::FuncOp fn, cir::CallOp call) {
    +  if (fn.getSymName().starts_with("__nv_"))
    +    return true;
    +  auto touchesNoOtherMemory = [](std::optional<cir::MemoryEffectsAttr> me) {
    +    return me && me->getOther() == cir::ModRefInfo::NoModRef;
    +  };
    +  return touchesNoOtherMemory(fn.getMemoryEffects()) ||
    +         touchesNoOtherMemory(call.getMemoryEffects());
    +}
    +
    +// Thread-geometry reads and CTA barriers; neither accesses memory through a
    +// pointer.
    +static bool isAllowedIntrinsic(llvm::StringRef name) {
    +  // TODO: Handle AMD intrinsics
    +  return name.starts_with("nvvm.read.ptx.sreg.") ||
    +         name.starts_with("nvvm.barrier.cta.");
    +}
    +
    +// Checks one function reachable from the kernel and collects the callees whose
    +// bodies must be checked next. `fn`'s own parameters anchor the derivation
    +// checks: in a callee they can only carry pointers the caller was allowed to
    +// pass.
    +static bool functionAllowsNoalias(cir::FuncOp fn,
    +                                  llvm::SmallVectorImpl<cir::FuncOp> &callees) {
    +  bool ok = true;
    +  fn.walk([&](Operation *op) {
    +    if (!ok)
    +      return;
    +
    +    if (auto getGlobal = mlir::dyn_cast<cir::GetGlobalOp>(op)) {
    +      if (!isCudaBuiltinVar(getGlobal)) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto call = mlir::dyn_cast<cir::CallOp>(op)) {
    +      std::optional<llvm::StringRef> callee = call.getCallee();
    +      if (callee && (callee->contains("malloc") || callee->contains("Malloc") ||
    +                     callee->contains("free") || callee->contains("Free"))) {
    +        ok = false;
    +        return;
    +      }
    +      for (Value operand : call.getArgOperands())
    +        if (derivesFromPointerParam(operand, fn) ||
    +            slotHoldsDerivedPointer(operand, fn)) {
    +          ok = false;
    +          return;
    +        }
    +      // The callee runs during the kernel, so its body is part of the proof.
    +      // Indirect calls and unknown declarations cannot be checked.
    +      cir::FuncOp target;
    +      if (callee)
    +        target = SymbolTable::lookupNearestSymbolFrom<cir::FuncOp>(
    +            call, call.getCalleeAttr());
    +      if (!target) {
    +        ok = false;
    +        return;
    +      }
    +      if (!target.isDeclaration())
    +        callees.push_back(target);
    +      else if (!isKnownSafeDeclaration(target, call))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (auto intrinsic = mlir::dyn_cast<cir::LLVMIntrinsicCallOp>(op)) {
    +      if (!isAllowedIntrinsic(intrinsic.getIntrinsicName()))
    +        ok = false;
    +      return;
    +    }
    +
    +    if (mlir::isa<CallOpInterface>(op)) {
    +      ok = false;
    +      return;
    +    }
    +
    +    if (auto load = mlir::dyn_cast<cir::LoadOp>(op)) {
    +      // Reloading a pointer from a local stack slot is the round-trip of a
    +      // value this body already holds (parameter materialization); pointers
    +      // loaded from real memory still drop the fact.
    +      if (mlir::isa<cir::PointerType>(load.getResult().getType()) &&
    +          !load.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto store = mlir::dyn_cast<cir::StoreOp>(op)) {
    +      // Storing into a local stack slot keeps the value on the stack; escapes
    +      // through memory or callees are caught by the other obligations (and by
    +      // slotHoldsDerivedPointer at call sites).
    +      if (derivesFromPointerParam(store.getValue(), fn) &&
    +          !store.getAddr().getDefiningOp<cir::AllocaOp>()) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +
    +    if (auto cast = mlir::dyn_cast<cir::CastOp>(op)) {
    +      if (cast.getKind() == cir::CastKind::ptr_to_int &&
    +          derivesFromPointerParam(cast.getSrc(), fn)) {
    +        ok = false;
    +        return;
    +      }
    +      // A pointer made from an integer is not based on any parameter, yet it
    +      // can hold the address of a parameter's buffer.
    +      if (cast.getKind() == cir::CastKind::int_to_ptr) {
    +        ok = false;
    +        return;
    +      }
    +    }
    +  });
    +  return ok;
    +}
    +
    +// The kernel and every function it can call must pass functionAllowsNoalias.
    +static bool bodyAllowsNoalias(cir::FuncOp kernel) {
    +  if (kernel.isDeclaration() || kernel.getBody().empty())
    +    return false;
    +
    +  llvm::SmallPtrSet<Operation *, 8> visited;
    +  llvm::SmallVector<cir::FuncOp, 8> worklist{kernel};
    +  while (!worklist.empty()) {
    +    cir::FuncOp fn = worklist.pop_back_val();
    +    if (!visited.insert(fn.getOperation()).second)
    +      continue;
    +    if (!functionAllowsNoalias(fn, worklist))
    +      return false;
    +  }
    +  return true;
    +}
    +
    +// The runtime declares cudaMalloc as a C function, but the C++ headers also
    +// provide an inline `template <class T> cudaMalloc(T **, size_t)` shim that
    +// PolyBench-style code calls without a cast; CIRGen keeps the call to the
    +// instantiation visible (no inlining runs before this pass), so recognize both
    +// the plain symbol and its mangled C++ template instantiations.
    +//TODO: Implement this for HIP symbols!.
    +static bool isCudaMallocSymbol(llvm::StringRef callee) {
    +  if (callee == "cudaMalloc")
    +    return true;
    +  if (!callee.starts_with("_Z"))

    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.

    steffenlarsen steffenlarsen commented on code on Oct 16, 2026 13:02 UTC
    Code Review
    clang/lib/CIR/Dialect/Analysis/CIRBasicAliasAnalysis.cpp:1
    @@ -233,6 +233,123 @@ static PointerOffset decomposePointer(mlir::Value val,
       return {val, offset};
     }
     
    +mlir::Value cir::stripPointerCasts(mlir::Value val) {
    +  while (auto castOp = val.getDefiningOp<cir::CastOp>()) {
    +    if (!castOp.isAllocaPreservingCast() &&
    +        castOp.getKind() != cir::CastKind::array_to_ptrdecay)
    +      break;
    +    val = castOp.getSrc();
    +  }
    +  return val;
    +}
    +
    +mlir::Value cir::getUnderlyingObject(mlir::Value val) {
    +  LDBG() << "Getting underlying object for: " << val;
    +
    +  for (unsigned depth = 0; depth < MaxLookupDepth; ++depth) {
    +    mlir::Operation *defOp = val.getDefiningOp();
    +    if (!defOp) {
    +      LDBG() << "No defining operation, stopping";
    +      break; // Block argument (e.g. function parameter) — stop here.
    +    }
    +
    +    // Bitcast and address-space casts don't change the underlying object.
    +    // array_to_ptrdecay produces an element pointer to the same storage as
    +    // the array pointer, so strip through it too.
    +    if (auto castOp = mlir::dyn_cast<cir::CastOp>(defOp)) {
    +      if (castOp.isAllocaPreservingCast() ||
    +          castOp.getKind() == cir::CastKind::array_to_ptrdecay) {
    +        LDBG() << "Walking past cast operation";
    +        val = castOp.getSrc();
    +        continue;
    +      }
    +      LDBG() << "Opaque cast operation, stopping";
    +      break;
    +    }
    +
    +    // Pointer stride: only strip through when we can prove the access stays
    +    // within the bounds of the underlying allocation.
    +    if (auto strideOp = mlir::dyn_cast<cir::PtrStrideOp>(defOp)) {
    +      auto constOp = strideOp.getStride().getDefiningOp<cir::ConstantOp>();
    +      if (constOp) {
    +        if (auto intAttr = mlir::dyn_cast<cir::IntAttr>(constOp.getValue())) {
    +          APInt stride = intAttr.getValue();
    +
    +          // Zero stride is trivially in-bounds.
    +          if (stride.isZero()) {
    +            LDBG() << "Walking past zero-strided PtrStrideOp";
    +            val = strideOp.getBase();
    +            continue;
    +          }
    +        }
    +      }
    +      // Dynamic stride or unverifiable bounds — stop here conservatively.
    +      LDBG() << "Non-zero or dynamic PtrStrideOp, stopping";
    +      break;
    +    }
    +
    +    // Handle special cases for zero-offset sub-object accesses.
    +    if (auto op = mlir::dyn_cast<cir::GetMemberOp>(defOp)) {
    +      if (op.getIndex() == 0) {
    +        LDBG() << "GetMemberOp[0], following to underlying object";
    +        val = op.getAddr();
    +        continue;
    +      } else {
    +        LDBG() << "GetMemberOp, non-zero index, stopping";
    +        break;
    +      }
    +    }
    +    if (auto op = mlir::dyn_cast<cir::GetElementOp>(defOp)) {
    +      cir::IntAttr index;
    +      if (auto constOp = op.getIndex().getDefiningOp<cir::ConstantOp>())
    +        index = mlir::dyn_cast<cir::IntAttr>(constOp.getValue());
    +      if (index && index.getValue().isZero()) {
    +        LDBG() << "GetElementOp[0], following to underlying object";
    +        val = op.getBase();
    +        continue;
    +      }
    +      LDBG() << "GetElementOp, non-zero or dynamic index, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::BaseClassAddrOp>(defOp)) {
    +      // A zero byte offset means the base subobject starts at the same address
    +      // as the derived object.
    +      if (op.getOffset().isZero()) {
    +        LDBG() << "BaseClassAddrOp[0], following to underlying object";
    +        val = op.getDerivedAddr();
    +        continue;
    +      }
    +      LDBG() << "BaseClassAddrOp, non-zero offset, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::DerivedClassAddrOp>(defOp)) {
    +      // The offset is stored unsigned but applied as a negative adjustment. A
    +      // zero offset means the derived object starts at the same address as the
    +      // base subobject.
    +      if (op.getOffset().isZero()) {
    +        LDBG() << "DerivedClassAddrOp[0], following to underlying object";
    +        val = op.getBaseAddr();
    +        continue;
    +      }
    +      LDBG() << "DerivedClassAddrOp, non-zero offset, stopping";
    +      break;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::ComplexRealPtrOp>(defOp)) {
    +      LDBG() << "Getting input pointer for ComplexRealPtrOp";
    +      val = op.getOperand();
    +      continue;
    +    }
    +    if (auto op = mlir::dyn_cast<cir::ComplexImagPtrOp>(defOp)) {
    +      LDBG() << "ComplexImagPtrOp, stopping";
    +      break;
    +    }

    Whichever you prefer! If it isn't an obviously better solution, I have no strong preference.

    koparasy koparasy approved these changes on Oct 16, 2026 13:24 UTC
    Approved Reviewer

    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.

    RiverDave RiverDave commented on Oct 26, 2026 17:09 UTC
    Author

    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).

    Reviewers
    Assignees
    RiverDave RiverDave
    Labels
    risk: low confidence: 89.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.4% · Lower = rushed or shallow review
    89.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.6% · Safe to merge
    7.6%