verify: Check existing result buffer sources

746b9a09b5150ddb32a1d58c13b6795d95cac1459c9b49f021a70f8c8dca2b4a
A result buffer could supply existing references to a caller target
without declaring them as inputs. Start its input cells as foreign,
and permit only the current output region to retain its own contents.

Keep separate buffer regions independent. Cover the caller frame escape,
cross-region copies and unchanged buffers.

Assisted-by: Codex:gpt-6
Alexis Sellier committed ago 1 parent 5ac4b96f
lib/std/lang/gen/regalloc/liveness.rad +1 -23
70 70
    uses: *mut [bitset::Bitset],
71 71
    /// Block being scanned.
72 72
    block: u32,
73 73
}
74 74
75 -
/// Visitor that looks for one register.
76 -
record FindCtx: Copy {
77 -
    target: u32,
78 -
    found: bool,
79 -
}
80 -
81 75
/// Compute liveness by growing live sets until no live-in set changes.
82 76
/// The sets are allocated from `a` and remain valid while its arena is in use.
83 77
export fn analyze(func: *il::Fn, a: &heap::Heap) -> LiveInfo
84 78
    throws (alloc::AllocError)
85 79
{
310 304
311 305
    if bitset::contains(&info.liveOut[blockIdx], reg.n) {
312 306
        return true;
313 307
    }
314 308
    for i in instrIdx + 1 .. block.instrs.len {
315 -
        if instrUsesReg(func, block.instrs[i], reg) {
309 +
        if il::usesReg(func, block.instrs[i], reg) {
316 310
            return true;
317 311
        }
318 312
    }
319 313
    return false;
320 314
}
321 -
322 -
/// Check if an instruction uses a specific register.
323 -
fn instrUsesReg(func: *il::Fn, instr: il::Instr, reg: il::Reg) -> bool {
324 -
    let mut ctx = FindCtx { target: reg.n, found: false };
325 -
    il::forEachReg(func, instr, &mut ctx);
326 -
    return ctx.found;
327 -
}
328 -
329 -
instance il::RegVisitor for FindCtx {
330 -
    /// Set `found` when the register equals the target.
331 -
    fn (c: &mut FindCtx) visit(reg: il::Reg) {
332 -
        if reg.n == c.target {
333 -
            set c.found = true;
334 -
        }
335 -
    }
336 -
}
lib/std/lang/il.rad +24 -0
1296 1296
            return false;
1297 1297
        }
1298 1298
    }
1299 1299
    return true;
1300 1300
}
1301 +
1302 +
/// Visitor that looks for one register.
1303 +
record FindCtx: Copy {
1304 +
    /// Register number to find.
1305 +
    target: u32,
1306 +
    /// Whether an operand has the target register number.
1307 +
    found: bool,
1308 +
}
1309 +
1310 +
/// Check if an instruction uses a specific register.
1311 +
export fn usesReg(func: &Fn, instr: Instr, reg: Reg) -> bool {
1312 +
    let mut ctx = FindCtx { target: reg.n, found: false };
1313 +
    forEachReg(func, instr, &mut ctx);
1314 +
    return ctx.found;
1315 +
}
1316 +
1317 +
instance RegVisitor for FindCtx {
1318 +
    /// Set `found` when the register equals the target.
1319 +
    fn (c: &mut FindCtx) visit(reg: Reg) {
1320 +
        if reg.n == c.target {
1321 +
            set c.found = true;
1322 +
        }
1323 +
    }
1324 +
}
lib/std/lang/il/verify.rad +49 -5
2231 2231
        }
2232 2232
        else => return false,
2233 2233
    }
2234 2234
}
2235 2235
2236 +
/// Whether typed instructions read or pass on the result buffer. A direct
2237 +
/// destination write cannot expose old contents. Address aliases and argument
2238 +
/// ranges count as inputs.
2239 +
fn readsResultBuffer(func: *il::Fn) -> bool {
2240 +
    let buffer = func.params[0].value;
2241 +
    for block in func.blocks {
2242 +
        for instr in block.instrs {
2243 +
            let mut input = false;
2244 +
            match instr {
2245 +
                case il::Instr::Blit { src, .. }      => set input = src == buffer,
2246 +
                case il::Instr::SliceSub { src, .. }  => set input = src == buffer,
2247 +
                case il::Instr::TraitCopy { src, .. } => set input = src == buffer,
2248 +
                case il::Instr::UnionGet { src, .. }  => set input = src == buffer,
2249 +
                case il::Instr::StorePtr { src, .. }  => set input = src == il::Val::Reg(buffer),
2250 +
                case il::Instr::UnionSet { src, .. }  => set input = src == il::Val::Reg(buffer),
2251 +
                case il::Instr::SliceNew { base, .. } => set input = base == il::Val::Reg(buffer),
2252 +
                case il::Instr::TraitNew { recv, .. } => set input = recv == buffer,
2253 +
                // Data operands observe addresses without following their protected contents.
2254 +
                // Direct page outputs replace the slot contents.
2255 +
                case
2256 +
                    il::Instr::Store { .. },
2257 +
                    il::Instr::BinOp { .. },
2258 +
                    il::Instr::UnOp { .. },
2259 +
                    il::Instr::Zext { .. },
2260 +
                    il::Instr::Sext { .. },
2261 +
                    il::Instr::PageSlice { .. },
2262 +
                    il::Instr::PageHeap { .. } =>
2263 +
                {}
2264 +
                else => set input = il::usesReg(func, instr, buffer),
2265 +
            }
2266 +
            if input {
2267 +
                return true;
2268 +
            }
2269 +
        }
2270 +
    }
2271 +
    return false;
2272 +
}
2273 +
2236 2274
/// Start from foreign facts everywhere, except the sources that the signature
2237 2275
/// permits for region `region` of the result, or of the object of parameter
2238 2276
/// `target`, which also keeps its own region. Grow the facts to a fixed point.
2239 -
fn permit(v: &mut Verifier, target: ?u32, region: u32) throws (Error) {
2277 +
fn permit(v: &mut Verifier, target: ?u32, region: u32, bufferInput: bool) throws (Error) {
2240 2278
    let func = v.func;
2241 2279
    for i in 0 .. v.defs.len {
2242 2280
        set v.defs[i].foreign = false;
2243 2281
    }
2244 2282
    for i in 0 .. v.cells.len {
2245 2283
        set v.cells[i] = false;
2246 2284
    }
2247 2285
    for param in func.params {
2248 2286
        set v.defs[param.value.n].foreign = true;
2249 -
        if not v.frame[param.value.n] {
2287 +
        if bufferInput or not v.frame[param.value.n] {
2250 2288
            for i in 0 .. cellCount(v, param.value) {
2251 2289
                let _ = markCell(v, param.value, i);
2252 2290
            }
2253 2291
        }
2254 2292
    }
2255 -
    if let t = target {
2293 +
    // Each output can retain its own contents. Other input regions need a declared source.
2294 +
    let mut output = target;
2295 +
    if output == nil and resultBuffer(func.returnType, func.borrows) {
2296 +
        set output = 0;
2297 +
    }
2298 +
    if let t = output {
2256 2299
        set v.cells[func.params[t].value.n * v.cellWidth + region] = false;
2257 2300
    }
2258 2301
    for borrow in func.borrows {
2259 2302
        if borrow.target <> target or borrow.result <> region {
2260 2303
            continue;
2310 2353
/// Check each region of the result, and of the object of each target parameter,
2311 2354
/// against the sources that the signature permits for it.
2312 2355
fn checkBorrow(v: &mut Verifier) throws (Error) {
2313 2356
    let func = v.func;
2314 2357
    let buffered = resultBuffer(func.returnType, func.borrows);
2358 +
    let bufferInput = buffered and readsResultBuffer(func);
2315 2359
    let mut count: u32 = 0;
2316 2360
    let mut address: u32 = 1;
2317 2361
    let mut pointee: ?u32 = nil;
2318 2362
    if buffered {
2319 2363
        set count = cellCount(v, func.params[0].value);
2322 2366
        set address = 0 if p.own else 1;
2323 2367
        set count = address + v.ctx.table.layouts[p.layout].regions;
2324 2368
        set pointee = p.layout;
2325 2369
    }
2326 2370
    for region in 0 .. count {
2327 -
        try permit(v, nil, region);
2371 +
        try permit(v, nil, region, bufferInput);
2328 2372
        for b in 0 .. func.blocks.len {
2329 2373
            set v.block = b;
2330 2374
            for instr, i in func.blocks[b].instrs {
2331 2375
                set v.instr = i;
2332 2376
                let case il::Instr::Ret { val } = instr else continue;
2352 2396
    for param, k in func.params {
2353 2397
        if not v.target[param.value.n] {
2354 2398
            continue;
2355 2399
        }
2356 2400
        for region in 0 .. cellCount(v, param.value) {
2357 -
            try permit(v, k, region);
2401 +
            try permit(v, k, region, bufferInput);
2358 2402
            if foreignCell(v, param.value, region) {
2359 2403
                throw failFn(v.fnIndex, Rule::Return);
2360 2404
            }
2361 2405
        }
2362 2406
    }
lib/std/lang/il/verify/tests.rad +87 -0
5357 5357
        ]
5358 5358
    );
5359 5359
    try rejected(&mut b, verify::Rule::Return);
5360 5360
}
5361 5361
5362 +
/// Result buffers cannot supply undeclared inputs to target stores.
5363 +
@test unsafe fn resultBufferInputEscape() throws (testing::TestError) {
5364 +
    let slot = ptrType(LOCAL, false, true, false);
5365 +
    let source = ptrType(P4, false, false, false);
5366 +
    let mut b = newBuilder();
5367 +
    let body = block(&mut b, &[], &[blit(1, 0, LOCAL), retVoid()]);
5368 +
    addSources(
5369 +
        &mut b,
5370 +
        "f",
5371 +
        &[param(0, slot), param(1, slot), param(2, source)],
5372 +
        il::ValType::Void,
5373 +
        &[body],
5374 +
        &[
5375 +
            il::Borrow { target: nil, result: 0, param: 2, source: nil },
5376 +
            il::Borrow { target: 1,   result: 0, param: 2, source: nil },
5377 +
        ]
5378 +
    );
5379 +
    let passed = args(&mut b, &[reg(3), reg(0), reg(1)]);
5380 +
    let caller = block(
5381 +
        &mut b,
5382 +
        &[],
5383 +
        &[
5384 +
            reserve(2, P4), reserve(3, LOCAL), storePtr(reg(2), 3, 0),
5385 +
            call(nil,  il::ValType::Void, il::Val::FnAddr("f"), passed), retVoid(),
5386 +
        ]
5387 +
    );
5388 +
    addSources(&mut b, "g", &[param(0, slot), param(1, source)], il::ValType::Void, &[caller], &[
5389 +
        il::Borrow { target: 0, result: 0, param: 1, source: nil }
5390 +
    ]);
5391 +
    try rejected(&mut b, verify::Rule::Return);
5392 +
}
5393 +
5362 5394
/// A protected slice can use a prefix of its backing array.
5363 5395
@test unsafe fn sliceArrayPrefixView() throws (testing::TestError) {
5364 5396
    let params = [param(0, ptrType(CELLS, true, true, false))];
5365 5397
    try check(&params[..], &[reserve(1, SLICECELL), sliceNew(1, reg(0), CELL, 3)], nil);
5366 5398
    try check(
5368 5400
        &[reserve(1, SLICECELL), sliceNew(1, reg(0), CELL, 4)],
5369 5401
        verify::Rule::Bounds
5370 5402
    );
5371 5403
    try check(&params[..], &[reserve(1, SLICECELL), sliceNew(1, reg(0), CELL, 2)], nil);
5372 5404
}
5405 +
5406 +
/// A result buffer retains each input region without mixing independent sources.
5407 +
@test unsafe fn resultBufferRegions() throws (testing::TestError) {
5408 +
    for cross in &[false, true] {
5409 +
        let mut b = newBuilder();
5410 +
        let pair = addLayout(&mut b, 16, 8, &[subSlot(0, LOCAL), subSlot(8, LOCAL)]);
5411 +
        let entry = block(&mut b, &[], &[
5412 +
            field(2, 0, 0), field(3, 0, 8), blit(2, 3, LOCAL), retVoid()
5413 +
        ])
5414 +
            if cross
5415 +
            else block(&mut b, &[], &[retVoid()]);
5416 +
        addSources(
5417 +
            &mut b,
5418 +
            "f",
5419 +
            &[
5420 +
                param(0, ptrType(pair, false, true, false)),
5421 +
                param(1, ptrType(P4, false, false, false)),
5422 +
            ],
5423 +
            il::ValType::Void,
5424 +
            &[entry],
5425 +
            &[
5426 +
                il::Borrow { target: nil, result: 0, param: 1, source: nil },
5427 +
                il::Borrow { target: nil, result: 1, param: 1, source: nil },
5428 +
            ]
5429 +
        );
5430 +
        if cross {
5431 +
            try rejected(&mut b, verify::Rule::Return);
5432 +
        } else {
5433 +
            try accepted(&mut b);
5434 +
        }
5435 +
    }
5436 +
}
5437 +
5438 +
/// A write-only result buffer shares mutable contents with its declared source.
5439 +
@test unsafe fn bufferedMutableContents() throws (testing::TestError) {
5440 +
    let mut b = newBuilder();
5441 +
    let body = block(&mut b, &[], &[
5442 +
        reserve(2, SLICELOCAL), sliceSub(2, 1, LOCAL), blit(0, 2, SLICELOCAL), retVoid()
5443 +
    ]);
5444 +
    addSources(
5445 +
        &mut b,
5446 +
        "f",
5447 +
        &[
5448 +
            param(0, ptrType(SLICELOCAL, false, true, false)),
5449 +
            param(1, ptrType(SLICELOCAL, false, false, false)),
5450 +
        ],
5451 +
        il::ValType::Void,
5452 +
        &[body],
5453 +
        &[
5454 +
            il::Borrow { target: nil, result: 0, param: 1, source: 0 },
5455 +
            il::Borrow { target: nil, result: 1, param: 1, source: 1 },
5456 +
        ]
5457 +
    );
5458 +
    try accepted(&mut b);
5459 +
}