Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions include/VxDialect.td
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ def Vx_SpawnOp : Vx_Op<"spawn"> {
let assemblyFormat = "`topology` `(` $topology `)` $body attr-dict (`:` type($results)^)?";
}

// At the start of a task: the task takes the value of type `value_type` in
// `slot` at its `spawn`, because it moves or copies the variable. The lowering
// of the task copies the value into the task, and the task then uses a slot of
// its own. The op declares no memory effects, so no pass deletes it first.
def Vx_TakeAtSpawnOp : Vx_Op<"take_at_spawn"> {
let summary = "A task takes the value in a slot at its spawn.";
let arguments = (ins AnyType:$slot, TypeAttr:$value_type);
}

// A transfer operation to move memory/execution context between topologies
// It reads the source and allocates the copy. The general write is the copy
// into the target's memory, and keeps an unused transfer from being deleted.
Expand Down
7 changes: 7 additions & 0 deletions src/bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,10 @@ pub enum Opcode {
/// `v[i] = x` on a vector: the vector `operand1` with lane `imm` replaced by the scalar
/// `operand2`.
VectorInsert = 89,
/// At the start of a task: the task takes the value in the slot `operand1` at its `spawn`,
/// because it moves or copies the variable. The task then works on a slot of its own. It
/// never reads the slot outside, which the code around the task can use for a new value.
TaskTakes = 90,
}

/// The `imm` of an `ElementwiseInto` that writes `op` of its operands into `dst`.
Expand Down Expand Up @@ -619,6 +623,9 @@ impl Opcode {
85 => TensorCast,
86 => TensorRange,
87 => ElementwiseInto,
88 => VectorSplat,
89 => VectorInsert,
90 => TaskTakes,
8 => Call,
9 => Ret,
10 => Matmul,
Expand Down
1 change: 1 addition & 0 deletions src/codegen/flat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2770,6 +2770,7 @@ impl<'a> FnEmit<'a> {
// terminator already ended it), stamp the `topology` attribute, and resume emitting into
// the enclosing block (which the spawn op did not terminate).
Opcode::SpawnEnd => self.op_spawn_end(idx, ins),
Opcode::TaskTakes => self.op_task_takes(ins),
Opcode::TasksWait => {
let join = if ins.imm == 1 { " {join}" } else { "" };
self.body += &format!(" \"vx.tasks_wait\"(){join} : () -> ()\n");
Expand Down
23 changes: 23 additions & 0 deletions src/codegen/flat/emit/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,29 @@ impl FnEmit<'_> {
Ok(marks)
}

/// `vx.take_at_spawn`: the task takes the value in a slot at its `spawn` (`TaskTakes`). Only
/// a slot that is an `!llvm.ptr` gets one: a struct, a pointer or a scalar whose address is
/// taken. The task can reach into such a slot by its address. A scalar in a rank-0 memref is
/// only loaded, and the lowering copies it anyway.
pub(crate) fn op_task_takes(&mut self, ins: &HirInstruction) -> Lowered<()> {
let r = ins.operand1.0 as usize;
let value_ty = if let Some(&Some(gid)) = self.agg_of.get(r) {
let agg = self.ctx.aggs.get(&gid).ok_or(crate::emitter_gap!())?;
agg.struct_ty.clone()
} else if self.pslot_of.get(r).copied().unwrap_or(false) {
"!llvm.ptr".to_string()
} else if let Some(e) = self.sslot_of.get(r).cloned().flatten() {
mlir_scalar(&e).ok_or(crate::emitter_gap!())?.to_string()
} else {
return Ok(());
};
let slot = self.names.get(r).ok_or(crate::emitter_gap!())?;
self.body += &format!(
" \"vx.take_at_spawn\"({slot}) {{value_type = {value_ty}}} : (!llvm.ptr) -> ()\n"
);
Ok(())
}

// Close the `vx.spawn` region: terminate its last block with `vx.yield` (unless a body
// terminator already ended it), stamp the `topology` attribute, and resume emitting into
// the enclosing block (which the spawn op did not terminate).
Expand Down
137 changes: 131 additions & 6 deletions src/dialect/VxLowering.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7976,10 +7976,11 @@ static Operation *resultSlotStore(vx::SpawnOp task, Value &slot) {
}

/// The value that a load of the stack slot `capture` gives, when the task
/// only loads it: a scalar local, the cell of a `let mut` tensor, or a struct
/// that the task moves or copies. The task copies such a slot at its `spawn`
/// (T4), because the variable may end, and its slot get a new value, before
/// the task reads it. A null type for any other capture.
/// only loads it: a scalar local, or the cell of a `let mut` tensor. The task
/// copies such a slot at its `spawn` (T4), because the variable may end, and
/// its slot get a new value, before the task reads it. A null type for any
/// other capture. A slot that the task moves or copies and can reach by its
/// address, such as a struct, has a `vx.take_at_spawn` instead.
static Type copiedAtSpawn(Value capture, Region &body) {
Type loaded;
if (auto type = dyn_cast<MemRefType>(capture.getType())) {
Expand Down Expand Up @@ -8013,6 +8014,69 @@ static SmallVector<Operation *> loadsIn(Value slot, func::FuncOp fn) {
return loads;
}

/// The blocks of the region of `task` that are on a cycle through the block of
/// `task`: the code of a loop around the `spawn`. Empty when no loop is around
/// it in its region.
static SmallPtrSet<Block *, 8> loopAroundSpawn(vx::SpawnOp task) {
Block *start = task->getBlock();
auto walk = [start](bool forward) {
SmallPtrSet<Block *, 8> seen;
SmallVector<Block *> work;
auto next = [&](Block *b) {
if (forward)
work.append(b->getSuccessors().begin(), b->getSuccessors().end());
else
work.append(b->getPredecessors().begin(), b->getPredecessors().end());
};
next(start);
while (!work.empty()) {
Block *b = work.pop_back_val();
if (seen.insert(b).second)
next(b);
}
return seen;
};
SmallPtrSet<Block *, 8> after = walk(true);
SmallPtrSet<Block *, 8> loop;
if (!after.contains(start))
return loop;
for (Block *b : walk(false))
if (after.contains(b))
loop.insert(b);
return loop;
}

/// Whether code outside `task`, in a block of `loop`, gives the stack slot
/// `slot` a new value: a store to it or to a field of it, or a new start of its
/// lifetime, as the `let` of a variable in a loop makes in each pass.
static bool newValueOnLoop(Value slot, vx::SpawnOp task,
const SmallPtrSet<Block *, 8> &loop) {
Region *region = task->getParentRegion();
SmallVector<Value> places = {slot};
while (!places.empty()) {
Value place = places.pop_back_val();
for (OpOperand &use : place.getUses()) {
Operation *user = use.getOwner();
if (task->isAncestor(user))
continue;
Block *block = region->findAncestorBlockInRegion(*user->getBlock());
if (!block || !loop.contains(block))
continue;
if (auto gep = dyn_cast<LLVM::GEPOp>(user)) {
places.push_back(gep.getResult());
continue;
}
auto store = dyn_cast<LLVM::StoreOp>(user);
auto cellStore = dyn_cast<memref::StoreOp>(user);
if ((store && store.getAddr() == place) ||
(cellStore && cellStore.getMemRef() == place) ||
isa<LLVM::LifetimeStartOp>(user))
return true;
}
}
return false;
}

/// Outlines `task` into a function that runs on a thread of `group`.
static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module,
SmallVectorImpl<TaskSlot> &slots) {
Expand Down Expand Up @@ -8051,20 +8115,62 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module,
if (resultSlot)
captures.insert(resultSlot);

// The slots that the task moves or copies, which the checker marked with
// `vx.take_at_spawn`. The `spawn` copies each one into the task, whatever the
// task does with it. Then the code around the task can give the slot a new
// value, as the next pass of a loop does, before the task reads it.
DenseMap<Value, Type> taken;
SmallVector<vx::TakeAtSpawnOp> takeOps;
body.walk([&](vx::TakeAtSpawnOp op) {
if (op->getParentOfType<vx::SpawnOp>() != task)
return;
takeOps.push_back(op);
Value slot = op.getSlot();
assert(captures.contains(slot) && "a task takes a slot from outside it");
assert(isa<LLVM::LLVMPointerType>(slot.getType()) &&
"a task takes a value from a place in memory");
auto [it, inserted] = taken.try_emplace(slot, op.getValueType());
assert((inserted || it->second == op.getValueType()) &&
"a task takes a slot with one type");
(void)it;
(void)inserted;
});

// The environment: the header, then one field for each captured value, then
// the result when no slot takes it.
// A copied slot has the type of its value, and every other capture its own.
SmallVector<Type> copied;
SmallVector<Type> fieldTypes = {ptrTy, i64Ty};
for (Value capture : captures) {
Type copy = capture != resultSlot ? copiedAtSpawn(capture, body) : Type();
Type copy;
if (auto it = taken.find(capture); it != taken.end())
copy = it->second;
else if (capture != resultSlot)
copy = copiedAtSpawn(capture, body);
copied.push_back(copy);
Type type = copy ? copy : capture.getType();
Type field = converter.convertType(type);
if (!field)
return task.emitError("a task cannot take a value of type ") << type;
fieldTypes.push_back(field);
}
// A task that nothing joins runs until its `tasks` block ends. When a loop
// around its `spawn` gives a slot a new value in each pass, the task must
// copy the slot: with the address, it can read the value of a later pass.
if (task.getNumResults() == 0) {
SmallPtrSet<Block *, 8> loop = loopAroundSpawn(task);
for (auto [i, capture] : llvm::enumerate(captures)) {
bool slot = capture.getDefiningOp<LLVM::AllocaOp>() ||
capture.getDefiningOp<memref::AllocaOp>();
if (!copied[i] && slot && !loop.empty() &&
newValueOnLoop(capture, task, loop))
return task.emitError(
"the compiler gives this task the address of a variable, and the "
"loop around the `spawn` gives the variable a new value in each "
"pass. So the task can read the value of a later pass. This is a "
"bug in the compiler");
}
}
std::optional<unsigned> resultField;
Type resultFieldType;
if (result && !resultSlot) {
Expand Down Expand Up @@ -8112,13 +8218,22 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module,
cast->setAttr("vx.task_takes", UnitAttr::get(ctx));
v = cast.getResult(0);
}
// A slot that the task takes: the task gets a slot of its own with the
// value, and each use in the task goes to that slot.
if (taken.contains(capture)) {
Value one = LLVM::ConstantOp::create(b, loc, b.getI32Type(),
b.getI32IntegerAttr(1));
Value own = LLVM::AllocaOp::create(b, loc, ptrTy, type, one);
LLVM::StoreOp::create(b, loc, v, own);
v = own;
}
inTask.push_back(v);
}
Block *first = &body.front();
fn.getBody().getBlocks().splice(fn.getBody().end(), body.getBlocks());
cf::BranchOp::create(b, loc, first);
for (auto [i, capture] : llvm::enumerate(captures)) {
if (copied[i]) {
if (copied[i] && !taken.contains(capture)) {
for (Operation *load : loadsIn(capture, fn)) {
load->getResult(0).replaceAllUsesWith(inTask[i]);
load->erase();
Expand All @@ -8129,6 +8244,16 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module,
return fn->isProperAncestor(use.getOwner());
});
}
for (vx::TakeAtSpawnOp op : takeOps)
op.erase();
// A copied capture has no use left in the task: the task never reads the
// slot outside it.
for (auto [i, capture] : llvm::enumerate(captures))
assert((!copied[i] || llvm::none_of(capture.getUsers(),
[&](Operation *user) {
return fn->isProperAncestor(user);
})) &&
"a task reads a slot outside it that it copied");
Value slotInTask;
if (resultSlot)
slotInTask = inTask[llvm::find(captures, resultSlot) - captures.begin()];
Expand Down
7 changes: 6 additions & 1 deletion src/hir/check/drops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,12 @@ fn rename_in_node(e: &mut Expr, from: &str, to: &str) {
rename_stmt_names(b, from, to);
}
}
Expr::UnsafeBlock(b) => rename_stmt_names(&mut b.stmts, from, to),
Expr::UnsafeBlock(b) => {
for n in b.takes.iter_mut().filter(|n| n.as_ref() == from) {
*n = to.into();
}
rename_stmt_names(&mut b.stmts, from, to);
}
Expr::ComptimeBlock(b) => rename_stmt_names(&mut b.stmts, from, to),
Expr::SpawnOn(b) => rename_stmt_names(&mut b.stmts, from, to),
Expr::TaskBlock(b) => rename_stmt_names(&mut b.stmts, from, to),
Expand Down
13 changes: 13 additions & 0 deletions src/hir/check/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,7 @@ impl TypeChecker<'_> {
cancels_on_err,
value_ty,
closure_body: false,
takes: Vec::new(),
});
}

Expand Down Expand Up @@ -912,6 +913,9 @@ impl TypeChecker<'_> {
}

let mut uses = Vec::new();
// What the task moves or copies. The code generator copies each one into the task at
// its `spawn`, so the task never reads a slot that the code around it can change.
let mut takes = Vec::new();
for (name, var_ty) in &used {
let Some(var_depth) = self.lookup_with_depth(name).map(|(_, _, d)| d) else {
continue;
Expand All @@ -934,6 +938,12 @@ impl TypeChecker<'_> {
Take::Reads
};
self.check_task_takes(name, var_ty, take, &span);
// A reference is the address of what it borrows: the task copies the address, and
// must not copy what it points to.
if matches!(take, Take::Moves | Take::Copies) && !matches!(var_ty, Type::Borrow { .. })
{
takes.push(name.clone());
}
if take == Take::Moves {
continue;
}
Expand Down Expand Up @@ -1008,6 +1018,9 @@ impl TypeChecker<'_> {
// The type of the value of a task with a handle, for an exit that gives it early.
let value_ty = (place == Some(SpawnPlace::Let)).then(|| ty.clone());
self.task_block_to_plain_block(expr, ret, None, cancels_on_err, value_ty);
if let Expr::UnsafeBlock(block) = expr {
block.takes = takes;
}
ty
}

Expand Down
23 changes: 23 additions & 0 deletions src/hir/flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,9 @@ struct Lowerer<'r> {
/// The `Result` type of the next task region, when its task can fail. An `Err` value at its
/// end cancels its `tasks` block (F3).
region_cancels_on_err: Option<Type>,
/// The variables that the next task region moves or copies. The region starts with a
/// `TaskTakes` for each one that is in a slot.
region_takes: Vec<Symbol>,
/// Tensor-type side table `GID -> (element, shape)`, recorded as tensor-typed values are emitted.
/// Tensor GIDs are content hashes, so codegen recovers a tensor's memref shape from here rather
/// than by inverting the GID (which is impossible). Committed onto the worker.
Expand Down Expand Up @@ -690,6 +693,7 @@ impl<'r> Lowerer<'r> {
task_bodies: Vec::new(),
region_tail_slot: None,
region_cancels_on_err: None,
region_takes: Vec::new(),
tensor_types: Vec::new(),
strings: Vec::new(),
ast_types: HashMap::new(),
Expand Down Expand Up @@ -4389,6 +4393,7 @@ impl<'r> Lowerer<'r> {
self.region_cancels_on_err = u.cancels_on_err.clone();
let task = kind == crate::syntax::TaskBlockKind::Spawn;
if task {
self.region_takes = u.takes.clone();
self.task_bodies.push(TaskBody {
spawn_depth: self.spawn_depth + 1,
want_value,
Expand Down Expand Up @@ -4630,6 +4635,7 @@ impl<'r> Lowerer<'r> {
) -> Lowered<Option<Val>> {
let tail_slot = self.region_tail_slot.take();
let cancels_on_err = self.region_cancels_on_err.take();
let takes = std::mem::take(&mut self.region_takes);
let on_device = !matches!(
imm as u32 as i32,
crate::arch::TASK_DISPATCH_ID | crate::arch::TASKS_BLOCK_DISPATCH_ID
Expand All @@ -4655,6 +4661,23 @@ impl<'r> Lowerer<'r> {
Register(0),
imm,
);
for name in &takes {
match self.scope.get(name) {
Some(Binding::Slot { reg, .. }) => {
let reg = *reg;
self.emit_effect(Opcode::TaskTakes, reg, Register(0), 0);
}
// A value in a register is copied into the task anyway. A struct value in a
// register is in a slot, and the code generator finds it.
Some(Binding::Reg(v)) => {
let reg = v.reg;
self.emit_effect(Opcode::TaskTakes, reg, Register(0), 0);
}
// A reference that has no address in memory: the task reads what it names.
Some(Binding::Place { .. }) => {}
None => panic!("the task takes '{name}', which has no binding"),
}
}
if launch.across {
self.emit_effect(Opcode::AcrossRegion, Register(0), Register(0), 0);
}
Expand Down
1 change: 1 addition & 0 deletions src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1075,6 +1075,7 @@ impl<'a> Parser<'a> {
cancels_on_err: None,
value_ty: None,
closure_body: false,
takes: Vec::new(),
});
let expr = self.wrap_try(expr);
// `unsafe { .. }.len()` calls a method on the value of the block. Only a `.` starts the
Expand Down
Loading
Loading