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
6 changes: 5 additions & 1 deletion docs/own-memory-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,11 @@ decorators above, and nothing of the bodies. Everything else about another modul
unknown, so a call of one may free anything.

A module compiled under `-mm=own` also records, in its object file, what each exported function
frees: nothing, or only certain fields, and whether its result is fresh. Give the objects of the
frees: nothing, or only certain fields, and whether its result is fresh. A function that may free
anything (it runs a callback) still says whether its result is fresh. A result that borrows one
argument also says which places of that argument it reads, so a call that overwrites another place
of the same type leaves that borrow alone. Functions the module does not export, but whose
declarations an importer sees, say whether their result is fresh. Give the objects of the
modules a program imports to `--own-facts`, and calls into them keep the caller's borrows they do
not touch:

Expand Down
23 changes: 23 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@
// still takes it over, on every path it appears on: nothing after either reads the name. See
// MLIROwnedReference.h.
#define OWNED_RESULT_NAMED_ATTR_NAME "__owned_result_named"
// ...kept, under its own name, on the direct call the canonicalizer and the lowering make of a call that had it
// (`const B = mk()`): only -mm=own's rule that a closure which does not escape borrows a named `const` reads it
// (TSLANG 246, the loop form of 238). The other rules keep seeing such a call as they did.
#define OWNED_RESULT_NAMED_CALL_ATTR_NAME "__owned_result_named_call"

// On a read through an interface's field that is owned under rc (MLIRGenImpl::InterfaceFieldAccess): a number
// of its own. A `ts.Load` only reads memory, so CSE would fold two reads of the same field into one - one
Expand Down Expand Up @@ -491,6 +495,25 @@
// a line's last field is OWN_OBJECT_FACTS_FRESH_RESULT
#define SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME "ts.own_imported_fresh_results"
#define OWN_OBJECT_FACTS_FRESH_RESULT "fresh"
// ...and a line `<name>\tany\tfresh` is a function that may destroy anything (it calls a callback, say) but
// whose result is still its caller's to own (TSLANG 246: `surface(fn, ...)` of another module, whose result
// was taken to hold the closure it was given). A reader that does not know the field finds no place in it,
// so gives the function no facts, which is what it had before.
#define OWN_OBJECT_FACTS_DROPS_ANY "any"
// ...and a field `@<position> <slot type>` per place the result of a function whose result is a plain borrow of one
// argument (`@lends("this") near(z)`) is read through from it (TSLANG 236, own's OWN_RESULT_PLACES_ATTR_NAME): an
// importer's call then knows that a later overwrite of another place of that type leaves the borrow alone. A reader
// that does not know the field finds no place in it, so gives the function no facts.
#define OWN_OBJECT_FACTS_RESULT_PLACE "@"
// ...and `<name> local fresh` a function the module does not export, whose result its caller owns: an importer
// re-parses its declaration, and a call through a value there may reach it (OwnedReturnConsumptionPass). Said of no
// call by name, and never over another module's exported line of the same name.
#define OWN_OBJECT_FACTS_LOCAL "local"
// a module attribute: [name...] of those
#define SHARED_LIB_OWN_LOCAL_FRESH_RESULTS_ATTR_NAME "ts.own_imported_local_fresh_results"
// a module attribute: { name -> [[position, slot type]...] } of the functions --own-facts says read their result
// through those places
#define SHARED_LIB_OWN_RESULT_PLACES_ATTR_NAME "ts.own_imported_result_places"
// `@nodrops declare function strncmp(...)`: a function defined outside TypeScript, a C function,
// that destroys nothing a TypeScript caller can reach. -mm=own calls it the way it calls an
// imported function in SHARED_LIB_OWN_NO_DROPS_ATTR_NAME, so a borrow of a field can be given to
Expand Down
18 changes: 14 additions & 4 deletions tslang/lib/TypeScript/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2900,6 +2900,16 @@ struct CallOpLowering : public TsPattern<mlir_ts::CallOp>

LogicalResult matchAndRewrite(mlir_ts::CallOp op, PatternRewriter &rewriter) const final
{
// a `const` holding the result as its value (`const B = mk()`) stays one for -mm=own, which runs on what
// this makes (TSLANG 246); read before the call is replaced, which erases it
auto named = op->getAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME);
auto keepNamed = [&](mlir::Operation *call) {
if (named)
{
call->setAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME, named);
}
};

if (auto unwind = tsContext->unwind.lookup(op))
{
{
Expand All @@ -2912,9 +2922,9 @@ struct CallOpLowering : public TsPattern<mlir_ts::CallOp>
: op.getOperands()) llvm::dbgs()
<< "!! ...call -> invoke operands: " << opit << "\n";);

rewriter.replaceOpWithNewOp<mlir_ts::InvokeOp>(op, op.getResultTypes(), op.getCalleeAttr(),
keepNamed(rewriter.replaceOpWithNewOp<mlir_ts::InvokeOp>(op, op.getResultTypes(), op.getCalleeAttr(),
op.getArgOperands(), continuationBlock, ValueRange{},
unwind, ValueRange{});
unwind, ValueRange{}));
return success();
}

Expand All @@ -2923,8 +2933,8 @@ struct CallOpLowering : public TsPattern<mlir_ts::CallOp>
}

// just replace
rewriter.replaceOpWithNewOp<mlir_ts::SymbolCallInternalOp>(op, op.getResultTypes(), op.getCalleeAttr(),
op.getArgOperands());
keepNamed(rewriter.replaceOpWithNewOp<mlir_ts::SymbolCallInternalOp>(op, op.getResultTypes(), op.getCalleeAttr(),
op.getArgOperands()));
return success();
}
};
Expand Down
3 changes: 3 additions & 0 deletions tslang/lib/TypeScript/MLIRGenInterfaces.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,9 @@ namespace mlirgen
if (auto stubOp = lookupModuleSymbol<mlir_ts::FuncOp>(stubName))
{
stubOp->setAttr(NULL_INTERFACE_VTABLE_ATTR_NAME, builder.getUnitAttr());
// each module makes its own (`BindingSet..missing` of an imported @value class, `.function_value.missing`),
// so it is the module's alone: two modules defining it failed to link with LNK2005 (TSLANG 243)
stubOp->setAttr("internal_linkage", builder.getUnitAttr());
}

return result;
Expand Down
78 changes: 73 additions & 5 deletions tslang/lib/TypeScript/MLIRGenModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1708,13 +1708,34 @@ namespace mlirgen
std::string noDrops;
llvm::SmallVector<mlir::NamedAttribute> dropFields;
llvm::SmallVector<mlir::Attribute> freshResults;
llvm::SmallVector<mlir::NamedAttribute> resultPlaces;
llvm::StringSet<> seen;
llvm::StringSet<> localFresh;
// `<position> <slot type>`, or null when it does not parse here
auto placeOf = [&](StringRef part) -> mlir::Attribute {
auto [positionText, typeText] = part.split(' ');
int64_t position;
auto type = typeText.empty() ? mlir::Type() : mlir::parseType(typeText, builder.getContext());
if (positionText.getAsInteger(10, position) || !type)
{
return {};
}

return builder.getArrayAttr({builder.getI64IntegerAttr(position), mlir::TypeAttr::get(type)});
};
llvm::SmallVector<StringRef> lines;
factsText.split(lines, '\n', -1, false);
for (auto line : lines)
{
llvm::SmallVector<StringRef> parts;
line.trim().split(parts, '\t', -1, false);
// a function a module does not export (OWN_OBJECT_FACTS_LOCAL): kept apart, below every exported line
if (parts.size() == 3 && parts[1] == OWN_OBJECT_FACTS_LOCAL && parts[2] == OWN_OBJECT_FACTS_FRESH_RESULT)
{
localFresh.insert(parts.front());
continue;
}

if (parts.empty() || !seen.insert(parts.front()).second)
{
continue;
Expand All @@ -1726,25 +1747,45 @@ namespace mlirgen
parts.pop_back();
}

// the places its result is read through (OWN_OBJECT_FACTS_RESULT_PLACE), all or none
llvm::SmallVector<mlir::Attribute> readThrough;
auto placesParse = true;
while (parts.size() > 1 && parts.back().starts_with(OWN_OBJECT_FACTS_RESULT_PLACE))
{
auto place = placeOf(parts.back().drop_front(StringRef(OWN_OBJECT_FACTS_RESULT_PLACE).size()));
placesParse = placesParse && place;
readThrough.insert(readThrough.begin(), place);
parts.pop_back();
}

if (placesParse && !readThrough.empty())
{
resultPlaces.push_back(builder.getNamedAttr(parts.front(), builder.getArrayAttr(readThrough)));
}

if (parts.size() == 1)
{
noDrops += parts.front().str() + "\n";
continue;
}

// it may destroy anything: only its fresh result, if any, is known
if (parts.size() == 2 && parts.back() == OWN_OBJECT_FACTS_DROPS_ANY)
{
continue;
}

llvm::SmallVector<mlir::Attribute> places;
for (auto part : llvm::drop_begin(parts))
{
auto [positionText, typeText] = part.split(' ');
int64_t position;
auto type = typeText.empty() ? mlir::Type() : mlir::parseType(typeText, builder.getContext());
if (positionText.getAsInteger(10, position) || !type)
auto place = placeOf(part);
if (!place)
{
places.clear();
break;
}

places.push_back(builder.getArrayAttr({builder.getI64IntegerAttr(position), mlir::TypeAttr::get(type)}));
places.push_back(place);
}

if (!places.empty())
Expand All @@ -1763,6 +1804,33 @@ namespace mlirgen
{
theModule->setAttr(SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME, builder.getArrayAttr(freshResults));
}

if (!resultPlaces.empty())
{
theModule->setAttr(SHARED_LIB_OWN_RESULT_PLACES_ATTR_NAME, builder.getDictionaryAttr(resultPlaces));
}

// (a name another module exports is that function's, whatever a module that does not export it says)
llvm::SmallVector<StringRef> localNames;
for (auto &entry : localFresh)
{
if (!seen.contains(entry.getKey()))
{
localNames.push_back(entry.getKey());
}
}

llvm::sort(localNames);
if (!localNames.empty())
{
llvm::SmallVector<mlir::Attribute> names;
for (auto name : localNames)
{
names.push_back(builder.getStringAttr(name));
}

theModule->setAttr(SHARED_LIB_OWN_LOCAL_FRESH_RESULTS_ATTR_NAME, builder.getArrayAttr(names));
}
}

// The module's exported declarations, as a global the passes can read (the ownership signature
Expand Down
27 changes: 25 additions & 2 deletions tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,24 @@ class OwnedReturnConsumptionPass
// default library's Map iterators' `next` (lending a key of the `{ value, done }` they return), there in every
// module with a dictionary, made every call through a function value returning a string keep its result
llvm::DenseSet<mlir::Type> unclassifiedNotLendingResults;
// -mm=own: the declarations another own module's object says return a value their caller owns (--own-facts,
// SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME): what a call through a value reaches of them is the caller's too
// (TSLANG 246: golden_line_extrude's functions, imported by golden_line_traingeo, turned this off there)
llvm::StringSet<> importedFresh;
if (compileOptions.memoryModel == MemoryModelOwn)
{
for (auto *attrName : {SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME, SHARED_LIB_OWN_LOCAL_FRESH_RESULTS_ATTR_NAME})
{
if (auto names = module->getAttrOfType<mlir::ArrayAttr>(attrName))
{
for (auto name : names.getAsRange<mlir::StringAttr>())
{
importedFresh.insert(name.getValue());
}
}
}
}

module.walk([&](mlir_ts::FuncOp funcOp) {
// a method of an interface's null vtable throws, and returns nothing to anyone
// (mlirGenNullInterfaceVTable)
Expand All @@ -116,7 +134,7 @@ class OwnedReturnConsumptionPass
returnsOwned.insert(name);
}

if (!classified)
if (!classified && !(funcOp.getBody().empty() && importedFresh.contains(name)))
{
for (auto resultType : funcOp.getFunctionType().getResults())
{
Expand Down Expand Up @@ -5145,9 +5163,14 @@ class OwnedReturnConsumptionPass
auto dot = name.rfind('.');
if (dot != mlir::StringRef::npos)
{
// only a method of a class on the receiver's chain can be in its slot (`Part.at` is not
// `JsonValue.at`), as everyOverrideReturnsOwned reads it
auto receiverType = thisVirtualSymbolRefOp.getThisVal().getType();
auto it = methodsByMemberName.find(name.substr(dot + 1));
if (it != methodsByMemberName.end() &&
llvm::any_of(it->second, [&](const auto &method) { return names.contains(method.first); }))
llvm::any_of(it->second, [&](const auto &method) {
return names.contains(method.first) && onReceiverChain(method.second, receiverType);
}))
{
return true;
}
Expand Down
3 changes: 2 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1198,7 +1198,8 @@ namespace own_inference
{
auto *user = use.getOwner();
if (pending.borrowed && keeping.bookkeeping &&
((mlir::isa<mlir_ts::ReleaseOp>(user) && borrowingCall(rootOf(pending.value))) ||
((mlir::isa<mlir_ts::ReleaseOp>(user) &&
(borrowingCall(rootOf(pending.value)) || mergeOfBorrowingCalls(pending.value))) ||
(keeping.returns && mlir::isa<mlir_ts::RetainOp>(user))))
{
keeping.bookkeeping->push_back(user);
Expand Down
4 changes: 3 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ namespace own_inference
auto ownedByNamedConst = [&](mlir::Value value) {
auto root = rootOf(value);
auto *def = root.getDefiningOp();
return def && isFresh(root) && def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME);
// (a call made direct keeps it as OWNED_RESULT_NAMED_CALL_ATTR_NAME: `const B = mk()`, TSLANG 246)
return def && isFresh(root) &&
(def->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME) || def->hasAttr(OWNED_RESULT_NAMED_CALL_ATTR_NAME));
};
auto noneFresh = llvm::none_of(closure->fills, [&](auto &fill) {
auto value = fill.second.getValue();
Expand Down
4 changes: 4 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -1090,6 +1090,10 @@ class OwnershipInferencePass
// record (spec 32) is not one: the caller owns the box (checkRecordResults).
static mlir::Operation *borrowingCall(mlir::Value value);

// A merge every way into which brings such a call's result: `c ? t.a() : t.b()` of two methods that each
// return a borrow (TSLANG 245). rc's release of the merge is its bookkeeping, as one of the call's is.
static bool mergeOfBorrowingCalls(mlir::Value value);

// The places from a read up to its roots, and the roots: the values the function reached the
// first container through. A container reached through a merge (`(c ? a : b).x`) has a root
// on each way in.
Expand Down
8 changes: 8 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,14 @@ namespace own_inference
return llvm::all_of(indices, [&](int index) { return static_cast<size_t>(index) < args.size(); }) ? def : nullptr;
}

bool OwnershipInferencePass::mergeOfBorrowingCalls(mlir::Value value)
{
auto argument = mlir::dyn_cast<mlir::BlockArgument>(rootOf(value));
llvm::SmallVector<mlir::Value> merged;
return argument && mergedInto(argument, merged) && !merged.empty() &&
llvm::all_of(merged, [](mlir::Value incoming) { return borrowingCall(incoming) != nullptr; });
}

// A plain borrow of one argument that says the places it is read through (OWN_RESULT_PLACES_ATTR_NAME): those go on
// the chain, as if read here. False for any other call's result.
bool OwnershipInferencePass::knownResultPlaces(mlir::Operation *call, Chain &chain)
Expand Down
Loading
Loading