diff --git a/tslang/docs/superpowers/specs/2026-10-25-own-facts-from-objects-design.md b/tslang/docs/superpowers/specs/2026-10-25-own-facts-from-objects-design.md new file mode 100644 index 000000000..f4daeb6df --- /dev/null +++ b/tslang/docs/superpowers/specs/2026-10-25-own-facts-from-objects-design.md @@ -0,0 +1,108 @@ +# -mm=own: what a call overwrites, and facts read from the objects of imported modules + +Status: implemented 2026-10-25 (branch `own-call-field-drops`). + +## 1. Why + +native_ts_graphics, a graphics sample collection compiled with tslang, builds every example from +separately compiled modules - the example, `core/donut.ts` (wrapper classes over a C++ library), +`core/simple_camera.ts` and so on - each into an object of its own, linked into one program. Under +`-mm=own` about 1200 errors remained after the project's own fixes (`@cpp` handle classes, `@value` +wrapper classes, `@nodrops` C declarations), nearly all `'x' borrows a field but is used here after it +may be released or overwritten`, for two reasons: + +1. **A callee that destroys something destroys everything.** A method that replaces an array field of + its own object (`this.position = [x, y]`), called on an object held in a field + (`this.camera.reset()`), dropped the caller's borrow of `this.camera`: the call was not + `__own_no_drops`, so it might destroy anything, though it can only destroy the old `position`. +2. **Nothing crosses between modules linked statically.** An imported `.ts` module is re-parsed as + declarations; its functions have no bodies there, so a call of one may destroy anything. Facts cross + only from a shared library (`__tsown_`, read through the loaded library) and, for stack promotion, + from static libraries the program links (`__tsborrow_`). + +## 2. What a call overwrites (`__own_drop_fields`) + +`OwnershipSignaturePass::computeDrops` keeps `noDrops` as it was and adds, for every other function, +its `FieldDrops`: the places it may overwrite when that is all it destroys that a caller can reach - +each place's position and slot type, the same pair a store in the caller's own body is judged by +(`OwnershipInferencePass::overwritesChain`, factored out of `dropsChain`'s `ts.ReleaseSlot` branch): + +- a field's position (`OWN_INTERFACE_FIELD_POSITION` for one reached through an interface, which then + matches any field), -1 for an element, and the slot's reference type; +- collected from the body's overwrites `dropsInBody` counts (`fieldDropsInBody`); anything else it + counts - a global's assignment, a captured variable's, a handle's payload (`x.value =`), a popped, + shifted or spliced element, `delete`, a handle released - makes the function `any`; +- joined with its callees' to a fixed point; a call whose callees are not all known, or one of them + `any`, makes it `any`. + +A call whose callees all have `FieldDrops` gets `__own_drop_fields` = `[[position, type]...]` +(`calleesFieldDrops`). `dropsChain` judges such a call as those stores would be judged in the caller, +and only narrows what it said before: a chain the function owns is still dropped only when the call is +given something derived from its root, and both must hold. Not for a chain whose places are not all +known (`chain.anyPlace`, a borrowing call's result), nor a call given a closure. + +This is as sound as the store rule it reuses: inlining the callee's stores would give the same answer. + +## 3. Facts from objects (`__tsownfacts_`, `--own-facts`) + +- **Export.** Every module built under own whose object another module may link (not the JIT's, nor + the JIT cache's) publishes `__tsownfacts__`, named like `__tsborrow_` after the main + source file, whatever it exports: the default library's static `lib.obj` is compiled with + `--export=none`, and has no `__tsmm_own_` marker, yet a program links it and calls `Math.abs`. It + is a NUL-terminated char array, so it can be read from an object without relocations (`__tsown_` is + a pointer, read through a loaded library), made by the LLVM lowering from the module attribute + `ts.own_object_facts` as `__tsborrow_` is. One line per non-private function: its name alone when + it is `__own_no_drops`, else its name and a tab-separated ` ` per place, when + it has `FieldDrops` with at least one place. Types are printed MLIR types and parsed back by the + importer. +- **Fresh results.** A line ends with a `fresh` field when the function's one result is its caller's + to own (`returnsFresh`): its body borrows no argument for it (`factsLocal` and `factsEffective` + have no `borrows`, and no record), and it says no `@lends`, `@borrows` or `@record`. That is what + `isFresh` already assumes of a call of a function defined in the same module: every function + returns its result retained (rc 9.24). A body that returns a borrow - a parameter, a field of one, + a mortal global - and can be called from another module is an error in its own module, so a + function in the facts text never returns one silently. The importer puts these names in + `ts.own_imported_fresh_results`, and their calls get `__own_fresh_result`: `this.eye = + transform3(this.eye, m)` may release the old array. An older compiler reading `name\tfresh` fails + to parse the place and gives the function no facts: safe. +- **Import.** `--own-facts=` (repeatable, comma-separated; only under own) + names the objects of the modules this one imports. The driver reads their `__tsownfacts_` texts + (`readOwnFacts`, beside `readBorrowFacts`); MLIRGen puts the names on the module as imported no-drops + functions (`ts.own_imported_no_drops`, as a shared library's are) and the places as + `ts.own_imported_drop_fields`. A line whose type does not parse gives that function no facts. +- **Use.** `OwnershipSignaturePass::addImported` resolves a declaration by its name, as it does an + imported no-drops function; one with places sets `Callees::importedOverwrites`, so the call gets + `__own_drop_fields` instead of `__own_no_drops`, and `callMayDrop` counts it. A `..new` gets + `__own_fresh_result` from a no-drops library, as before, and any function whose line says `fresh`. +- **The default library.** Without `--no-default-lib`, and not under the JIT, the driver also reads + the facts of the static default library the link will use (`getDefaultLibBinary`, the build and + model of this compile; never its DLL, which a program may load another copy of). + +The facts must describe the code linked: the build passes the objects of the modules it links (or +objects compiled from the same sources with the same flags). tslang cannot check that, as it cannot +for `__tsborrow_`; a stale object is the build's error. + +Only calls by name benefit. A virtual call of an imported class's method cannot be resolved here (its +vtable is the other module's), so a class meant to be called across modules is best `@final`. + +## 4. Tests + +- `own_call_field_drops` (run under own, gc, rc and none: `3 7 4`): a method replacing its own array + field, called on a field-held object, directly, through a method, through an interface. +- `own_err_call_field_drops_owner`, `_under`: a method overwriting the borrowed field, and a field + under the borrowed object, still drop the borrow. +- `own-facts-objects.cmake`: `own_facts_lib.ts` compiled to an object; `own_facts_main.ts` fails without + `--own-facts` and compiles, links and prints `11` with it (`shifted`'s fresh result replaces the + array it was given); `own_facts_main_drops.ts`, whose imported callee overwrites the borrowed + place, fails with it. + +## 5. Compile-time constants (`__MEMORY_MODEL__`, `__OS__`, `__ARCH__`) + +String literals of the memory model (`gc`, `rc`, `own`, `none`) and of the target's OS and +architecture, named as Node's `process.platform` and `process.arch` name them (`win32`, `linux`, +`android`, `darwin`; `x64`, `ia32`, `arm64`, `arm`, `wasm32`). A compare of one with a string literal +(`===`, `!==`, `==`, `!=`) is decided while generating (`foldLiteralCompare`), so an `if` on it +generates the branch taken only: under own a generated wrapper does not keep a callback that only +gc's collector needs kept. Only these constants' ops are folded (`ts.compile_time_constant`): other +values' literal types - a narrowed field's, `~1`'s - need not be what they hold at run time, and +folding every literal compare broke 46 tests. `00memory_model_constant.ts` runs under all four models. diff --git a/tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md b/tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md new file mode 100644 index 000000000..0579e72cc --- /dev/null +++ b/tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md @@ -0,0 +1,156 @@ +# -mm=own: what an append-only global keeps is immortal + +## 1. Why + +A callback a C library calls later has to stay alive after the call that registered it. Under gc a +TypeScript wrapper keeps it in a module-level array that is only ever pushed to, so Boehm sees it: + +```ts +let retained: Callback[] = []; +setRenderCallback(handler: Callback) { retained.push(handler); Donut_SetRenderCallback(this.handle, handler); } +``` + +Under own that push is a move: the wrapper keeps `handler`, so its caller must give it up, and a +bound method `this.onRender` cannot be given up (its object is the caller's `this`, owned by +`main`). A closure that captures a local fails the same way ("captured by a closure that escapes, +and is still used here"). Since `__MEMORY_MODEL__` the generated wrappers skip the push under own, +and the lifetime is the C++ one: the pass objects outlive `App.run()`. This design lets own prove it +instead: what such an array keeps lives to the end of the program, so it is made immortal where it +is kept, as an immortal global is (spec 25). + +## 2. Keepers + +A **keeper** is a `ts.Global` that: + +- is not exported or imported (no `export`, `import`, `dllexport`, `dllimport`), and is not reached + through a vtable; +- is an array whose element type is a class, a bound function, a function value (`hybrid_func`), a + string or an array; +- is given its value only by its region, which yields a new array (`[]`, `ts.Constant` of an array, + `ts.CreateArray`, `ts.NewArray`); +- is used only by `ts.AddressOf`s whose users are a `ts.ArrayPush` (the array operand), and + `ts.Load`s whose users read it: `ts.LengthOf`, and `ts.ElementRef`s that are only loaded. + +Nothing ever takes an element out of a keeper or overwrites one (no `pop`, `shift`, `splice`, +`length =`, element store, nor the array given to anything), and nothing releases a global. So +what it holds is never released: it lives to the end of the program. + +`findKeepers` (OwnershipSignaturePass) marks each `ts.AddressOf` of a keeper +`__own_keeper_global`, and each `ts.Load` of one of its elements `__own_keeper_read`. + +## 3. Immortal at the push + +A value pushed into a keeper is made immortal there: its block's header becomes +`HEAP_BLOCK_IMMORTAL`, so every release skips it, its fields included (a release of an immortal +block runs no destroy body). Writing the header only leaks; it frees nothing. So it is sound wherever +the block is a heap block with a header, and every block the value relies on is made immortal too. +Two blocks need more than the value's own: + +- **A bound method** (`this.onRender`) holds its `this` without owning it, so the object is + marked. +- **A closure that does not escape** borrows its cells and the values it captured by value from the + frame that built it, which releases them. Its box, each cell and each value captured by value + are marked. + +Only the function that builds a value knows these blocks: a callee given a `hybrid_func` does not +know whether its context is an object, a box (whose layout it does not know) or a C++ object with +no header at all. So the mark is made by the function that knows the value's origin, and a function +that pushes a parameter passes the duty to its callers: + +- **The value is a parameter** (a load of the parameter's slot, through casts): the function + **immortalizes** that parameter (`__own_immortalizes`, argument indices). Nothing is marked + there; every call of it marks its argument, by these same rules. +- **The value is built here, or read out of an owning local whose initializer it is**: a bound + method (`ts.ThisSymbolRef`, `ts.ThisVirtualSymbolRef` of a class that owns its block, not + `@cpp`), a closure (`ts.CreateBoundFunction` of a capture box), an allocation (`ts.New`, + `ts.CreateArray`, `ts.NewArray`), or a string. It is marked here. +- **It is immortal already**: a literal, an immortal global's read, a keeper's element. +- **Anything else** (a field's value, a call's result, a merge): an error at the push, "-mm=own + cannot make the value kept in 'retained' immortal here". + +A call passes an argument to a parameter its callee immortalizes. That argument is decided by the +same rules: a parameter of the caller propagates (a fixpoint over the calls, as `@keeps` facts +are), and anything else is marked at the call. + +## 4. In the IR + +- `%i = ts.MakeImmortal(%v)`: the same value, now immortal. Inserted right after `%v`'s definition + (the root, before casts); every other use of `%v` is given `%i`. With `assumed` it marks nothing: + it wraps a parameter its callers made immortal. +- `ts.MarkImmortalCell(%cell)`: marks a captured variable's cell. + +To inference, `ts.MakeImmortal`'s result is immortal (`isImmortalLiteral`): its retains go, and it +may be pushed, stored, returned or given to a call that keeps it, as a string literal may. Its +operand is only borrowed, so the frame still owns what it built and releases it at the end, which +the header makes a no-op. A keeper's element read is immortal too, and is no place read. A keeper's +`ts.AddressOf` is no global read either: the array is never replaced, only appended to. A push of +an immortal value keeps nothing, so a parameter pushed through `ts.MakeImmortal` is not +`__own_params`. That is why the caller's `this` can go to `setRenderCallback`. + +The lowering, under own only: + +- a class or object instance, a string: the block, when not null and not already immortal (a stack + object and a literal have immortal headers, and a literal's may be read-only); +- an array: its header block, when there is one; +- a bound function: its `this`, an object or a capture box; +- `assumed`: nothing. + +## 5. Across modules: `@immortalizes` + +A function another module may call (open: exported, or its address taken) cannot tell callers it +does not see to mark their arguments. Like `@keeps`, an open function that immortalizes a parameter +must say so: `@immortalizes("handler")`. It is checked against the body (`checkDeclared`): a +parameter it names that the body does not immortalize, or one the body immortalizes that it does +not name, is an error. A bodyless declaration's `@immortalizes` is trusted, as `@nodrops` is: a C +function that keeps a callback for good. The decorator is carried in an importer's re-parsed +declaration and in a shared library's declarations, so every caller marks its arguments. + +A call through a class family or an interface immortalizes a parameter only when every callee does. +When the callees disagree, the function that immortalizes is an error: some calls of it would not +mark. + +## 6. Not here + +- A keeper of optionals, unions or tuples: their payloads would need marking through the tag. +- A function value of unknown origin (a field's `hybrid_func`): its context may be a bound method's + object, which only its type tells. +- Removing elements from a keeper: that is an ordinary array, and the push is the move it is + today. + +## 7. As built + +- `OwnershipSignatureKeepers.cpp`: `findKeepers`, `classifyKept`, `decideKeptForGood` (runs after + `findOpen`, before `computeFacts`: an immortal value keeps nothing, so a parameter pushed through + `ts.MakeImmortal` is not `__own_params`), `makeImmortal`. A call's callees are its resolved + functions, or, for a call the pass knows nothing else of (another module's function with no + facts), the declarations of the symbols it names, whose `@immortalizes` is read. +- Inference: `isImmortalLiteral` and the retain decision accept `isKeptForGood`; a keeper's element + read is neither a place read nor a global read; `ts.MakeImmortal` and `ts.MarkImmortalCell` are + borrows; `followClosure` takes `ts.MakeImmortal` as a use and follows it no further, so a closure + kept for good borrows its cells from the frame (which then may still use the captured variables), + and whatever is done with the immortal value afterwards bounds nothing. +- Stack promotion (`StackEscapeFacts`): `ts.MakeImmortal` and `ts.MarkImmortalCell` are an escape, + reason "kept for good", so nothing kept is ever a stack object. +- The decorator is carried like `@keeps`: `processOwnParamMarkers`, the global a declaration's calls + go through, a shared library's printed declarations (a 32-bit mask in a class's method info, which + fits where a 64-bit one would grow the vtable's `SmallVector` past its inline limit). + +Existing programs change only where an array was a keeper: `own_err_closure_escape_twice`, `_loop` +and `_some_paths` pushed closures into a global that is now one, so they were accepted (soundly); +they now empty it once (`handlers.length = 0`), which keeps their errors. `own_closure_escape` and +the stack-promotion test `pass_to_keeper` push into keepers and pass, the latter with the reason +"kept for good" under own. + +## 8. Tests + +- `own_immortal_keepers` (own, gc, rc, none; compile and JIT): a registry pushing a parameter into + a keeper and using it after; a constructor registering `this.onTick` from a function that returns; + a closure over a local the frame still uses; a forwarding function, and an exported one that says + `@immortalizes`; objects pushed directly, fresh and from a local; a keeper's element stored into a + field; churn between, so a freed block would be handed out again. +- `test-own-keepers-objects` (own-keepers-objects.cmake): the keeper in a library object, an + importer registering a bound method and a closure from functions that return; `2 102 2`. +- `own_err_keeper_*`: a value of unknown origin pushed (`unknown_value`), an exported function + without `@immortalizes` (`exported`), an `@immortalizes` the body disagrees with (`declared`), a + function that keeps for good passed on as a value (`called_through_value`), and an array that is + also popped, which is no keeper, so the move error stays (`popped`). diff --git a/tslang/include/TypeScript/DataStructs.h b/tslang/include/TypeScript/DataStructs.h index 54a4e7a86..6800f3b22 100644 --- a/tslang/include/TypeScript/DataStructs.h +++ b/tslang/include/TypeScript/DataStructs.h @@ -73,6 +73,9 @@ struct CompileOptions std::string importedBorrowFacts; // the files they were read from: a JIT cache entry depends on them std::vector importedBorrowFactsFiles; + // The own facts (__tsownfacts_ texts, concatenated) of the objects named by --own-facts: the + // modules this one imports, compiled under -mm=own. Empty: none. + std::string importedOwnFacts; // an import led back to a file still being generated: the modules in the cycle cannot be // compiled one by one (the JIT cache then compiles the program as one module) bool importCycle = false; diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 29c59e94e..0ab1aa3ca 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -276,6 +276,23 @@ #define SHARED_LIB_BORROW_FACTS_ATTR_NAME "ts.borrow_facts" // a module attribute, so it has to carry the dialect's prefix #define SHARED_LIB_OWN_NO_DROPS_ATTR_NAME "ts.own_imported_no_drops" +// A module built under -mm=own also publishes its own facts as a char array, readable from its +// object file without relocations (__tsown_ is a pointer to the text, read through the loaded +// library): `__tsownfacts__`, one line per exported function - its name alone when +// it destroys nothing a caller can reach (__own_no_drops), or its name followed by a tab-separated +// ` ` per place it may overwrite when that is all it destroys +// (__own_drop_fields). A program compiled against the module's object reads them with +// --own-facts=: see docs/superpowers/specs/2026-10-25-own-facts-from-objects-design.md. +#define SHARED_LIB_OWN_OBJECT_FACTS "__tsownfacts_" +// [symbol name, text]: set by OwnershipSignaturePass, made into the symbol by the LLVM lowering +#define SHARED_LIB_OWN_OBJECT_FACTS_ATTR_NAME "ts.own_object_facts" +// a module attribute: { name -> [[position, slot type]...] } of the functions --own-facts says +// overwrite only those places +#define SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME "ts.own_imported_drop_fields" +// ...and [name...] of the functions it says return a value their caller owns, borrowing no argument: +// 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" // `@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 @@ -283,6 +300,15 @@ // declaration can give it: never on one that may run TypeScript code (it takes a callback) or // one re-parsed from a TypeScript library, whose functions may destroy what they are given. #define NO_DROPS_DECORATOR "nodrops" +// The memory model a module is compiled for, a string literal: `if (__MEMORY_MODEL__ === "gc")` +// generates the branch taken only (MLIRGenImpl::foldLiteralCompare) +#define MEMORY_MODEL_IDENTIFIER "__MEMORY_MODEL__" +// ...and the target's OS and architecture, as Node's process.platform and process.arch name them +#define TARGET_OS_IDENTIFIER "__OS__" +#define TARGET_ARCH_IDENTIFIER "__ARCH__" +// The constant op one of them generates: only a compare with it is decided while generating, as +// other values' literal types (a narrowed field's, `~1`'s) need not be what they hold at run time +#define COMPILE_TIME_CONSTANT_ATTR_NAME "ts.compile_time_constant" #define OWN_DECLARED_NO_DROPS_ATTR_NAME "ts.own_declared_no_drops" // `@keeps("p")` and `@borrows("this", "p")`: the facts of a function's body that its callers rely // on (OWN_PARAMS_ATTR_NAME, OWN_RESULT_BOUNDED_ATTR_NAME), said in its signature, so every caller @@ -305,6 +331,12 @@ // that returns such a record has to say it. A unit attribute on the FuncOp. #define RECORD_DECORATOR "record" #define OWN_DECLARED_RECORD_ATTR_NAME "ts.own_declared_record" +// `@immortalizes` names the parameters the function keeps for good, in an append-only global (a +// keeper, docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): its callers make each +// argument immortal. Checked against a body; trusted on a declaration, a C function that keeps a +// callback for good. A FuncOp attribute of argument indices. +#define IMMORTALIZES_DECORATOR "immortalizes" +#define OWN_DECLARED_IMMORTALIZES_ATTR_NAME "ts.own_declared_immortalizes" // the names of the arguments of a function that says any, for -mm=own's errors about it #define OWN_DECLARED_PARAM_NAMES_ATTR_NAME "ts.own_declared_param_names" diff --git a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h index 8eeb1410e..3cb447026 100644 --- a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h +++ b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h @@ -479,6 +479,36 @@ class OwnershipRoutineLogic }); } + // The same for a block that may be immortal already (ts.MakeImmortal, own's keepers): a stack + // object's header is, and a literal's, which may be read-only, so the header is written only + // when it is mortal. + void emitMarkImmortalIfMortal(mlir::Value payloadPtr) + { + emitIfNonNull(payloadPtr, [&]() { + TypeConverterHelper tch(typeConverter); + TypeHelper th(rewriter); + LLVMCodeHelperBase ch(op, rewriter, typeConverter, compileOptions); + auto loc = op->getLoc(); + + auto isMortal = emitIsMortal(payloadPtr); + auto *currentBlock = rewriter.getInsertionBlock(); + auto *continuationBlock = rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint()); + auto *markBlock = rewriter.createBlock(continuationBlock); + + rewriter.setInsertionPointToEnd(markBlock); + auto llvmIndexType = tch.convertType(th.getIndexType()); + auto blockPtr = ch.getBlockPtrFromPayloadPtr(loc, payloadPtr, llvmIndexType); + rewriter.create( + loc, rewriter.create(loc, llvmIndexType, rewriter.getIntegerAttr(llvmIndexType, HEAP_BLOCK_IMMORTAL)), + blockPtr); + rewriter.create(loc, ValueRange{}, continuationBlock); + + rewriter.setInsertionPointToEnd(currentBlock); + rewriter.create(loc, isMortal, markBlock, continuationBlock); + rewriter.setInsertionPointToStart(continuationBlock); + }); + } + private: // Field types of a record-shaped type, empty for anything else. llvm::SmallVector getFieldTypes(mlir::Type type) diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h b/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h index 3b9e139ff..20951056b 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h @@ -25,7 +25,7 @@ namespace typescript void printVariableDeclaration(StringRef, NamespaceInfo::TypePtr, mlir::Type, bool, StringRef = StringRef()); void print(StringRef, NamespaceInfo::TypePtr, mlir_ts::FunctionType, StringRef = StringRef(), ArrayRef ownKeeps = {}, ArrayRef ownBorrows = {}, ArrayRef ownLends = {}, - bool ownRecord = false); + bool ownRecord = false, ArrayRef ownImmortalizes = {}); void print(ClassInfo::TypePtr); void print(InterfaceInfo::TypePtr); void printGenericClass(NamespaceInfo::TypePtr, StringRef); @@ -41,7 +41,8 @@ namespace typescript bool filterName(StringRef); bool filterField(mlir::Attribute); void printParams(ArrayRef, mlir::Type); - void printOwnMarkers(ArrayRef, ArrayRef, ArrayRef, bool, bool, unsigned); + void printOwnMarkers(ArrayRef, ArrayRef, ArrayRef, bool, bool, unsigned, + ArrayRef = {}); void printFunction(StringRef, ArrayRef, mlir::Type); void printMethod(bool, StringRef, ArrayRef, mlir::Type, mlir::Type); void printAccessor(bool, StringRef, StringRef, mlir_ts::AccessLevel, ArrayRef, mlir::Type, mlir::Type, StringRef); diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index a39b54b53..d596a652b 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -172,6 +172,10 @@ struct MethodInfo uint64_t ownLendsMask = 0; // `@record` (OWN_DECLARED_RECORD_ATTR_NAME): what `@lends` names, the result is a record of bool ownRecord = false; + // `@immortalizes` (OWN_DECLARED_IMMORTALIZES_ATTR_NAME), as a mask like `@lends`'s, of 32 bits: + // it fits beside `ownRecord`, where a 64-bit one would grow the vtable's SmallVector past its + // inline-size limit + uint32_t ownImmortalizesMask = 0; }; struct GenericMethodInfo diff --git a/tslang/include/TypeScript/Passes.h b/tslang/include/TypeScript/Passes.h index 890ba6ce3..47d3b54fb 100644 --- a/tslang/include/TypeScript/Passes.h +++ b/tslang/include/TypeScript/Passes.h @@ -39,8 +39,9 @@ std::unique_ptr createOwnershipInferencePass(); /// borrows an argument, a callee that destroys nothing its caller can reach - pinned on each call it /// resolves. Runs just before OwnershipInferencePass, under own only. `executable`: the module is /// built into a program (an executable, or the JIT's entry module), whose exports no other module -/// sees; false when unknown. -std::unique_ptr createOwnershipSignaturePass(bool executable = false); +/// sees; false when unknown. `objectFactsSymbol`: the name of the char array that tells a module +/// linking this one's object which exported functions destroy nothing; empty for none. +std::unique_ptr createOwnershipSignaturePass(bool executable = false, std::string objectFactsSymbol = ""); /// Lets a call take over the reference its callee returned instead of retaining a second one. /// Runs on the whole module, after MLIRGen, because deciding which callees retain their result diff --git a/tslang/include/TypeScript/TypeScriptOps.td b/tslang/include/TypeScript/TypeScriptOps.td index 543032808..5168f5176 100644 --- a/tslang/include/TypeScript/TypeScriptOps.td +++ b/tslang/include/TypeScript/TypeScriptOps.td @@ -625,6 +625,33 @@ def TypeScript_ReleaseContentsOp : TypeScript_Op<"ReleaseContents"> { let arguments = (ins AnyType:$instance, UnitAttr:$reset); } +def TypeScript_MakeImmortalOp : TypeScript_Op<"MakeImmortal", [AllTypesMatch<["value", "result"]>]> { + let summary = "the same value, its block marked immortal"; + let description = [{ + -mm=own (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): a value an + append-only global keeps for good. Its block - an object's, a string's, an array's header, a + bound function's `this` - is marked HEAP_BLOCK_IMMORTAL, unless it is null or immortal already, + so every release skips it. The result is that value, immortal: owned by no one. With `assumed` + nothing is marked: the value is a parameter its callers made immortal. + + Only OwnershipSignaturePass makes it; under the other models it is never there. + }]; + + let arguments = (ins AnyType:$value, UnitAttr:$assumed); + let results = (outs AnyType:$result); +} + +def TypeScript_MarkImmortalCellOp : TypeScript_Op<"MarkImmortalCell"> { + let summary = "mark a captured variable's cell immortal"; + let description = [{ + The cell of a variable a closure captures, when that closure is kept for good and borrows the + cell from the frame that declared it (-mm=own, MakeImmortal): the frame's release of the cell + then skips it. + }]; + + let arguments = (ins TypeScript_Ref:$slot); +} + def TypeScript_SizeOfOp : TypeScript_Op<"SizeOf", [Pure]> { let summary = "size of type"; let description = [{ diff --git a/tslang/lib/TypeScript/CMakeLists.txt b/tslang/lib/TypeScript/CMakeLists.txt index 988e91784..69c6de3b7 100644 --- a/tslang/lib/TypeScript/CMakeLists.txt +++ b/tslang/lib/TypeScript/CMakeLists.txt @@ -49,6 +49,7 @@ add_mlir_dialect_library(MLIRTypeScript OwnershipSignatureGenerators.cpp OwnershipSignatureGlobals.cpp OwnershipSignatureInterfaces.cpp + OwnershipSignatureKeepers.cpp OwnershipSignatureRecords.cpp OwnershipSignatureResolve.cpp OwnedReturnConsumptionPass.cpp @@ -70,4 +71,6 @@ add_mlir_dialect_library(MLIRTypeScript LINK_LIBS PUBLIC ts-new-parser-lib MLIRIR + # mlir::parseType: the slot types of the own facts read from an object (--own-facts) + MLIRAsmParser ) diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 9f25ef38e..d07b178e9 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -232,7 +232,7 @@ namespace typescript // the receiver of a method, so the importer reads the same argument indices back. `@record` after // `@lends`: the importer's only way to know the result is a record it owns (own spec 32). void MLIRDeclarationPrinter::printOwnMarkers(ArrayRef keeps, ArrayRef borrows, ArrayRef lends, - bool record, bool hasThis, unsigned indent) + bool record, bool hasThis, unsigned indent, ArrayRef immortalizes) { auto printMarker = [&](StringRef name, ArrayRef indices) { if (indices.empty()) @@ -262,6 +262,7 @@ namespace typescript }; printMarker(KEEPS_DECORATOR, keeps); + printMarker(IMMORTALIZES_DECORATOR, immortalizes); printMarker(BORROWS_DECORATOR, borrows); printMarker(LENDS_DECORATOR, lends); if (record && !lends.empty()) @@ -448,7 +449,7 @@ namespace typescript void MLIRDeclarationPrinter::print(StringRef name, NamespaceInfo::TypePtr elementNamespace, mlir_ts::FunctionType funcType, StringRef dllName, ArrayRef ownKeeps, ArrayRef ownBorrows, ArrayRef ownLends, - bool ownRecord) + bool ownRecord, ArrayRef ownImmortalizes) { printNamespaceBegin(elementNamespace); @@ -460,7 +461,7 @@ namespace typescript newline(); } - printOwnMarkers(ownKeeps, ownBorrows, ownLends, ownRecord, /*hasThis=*/false, 0); + printOwnMarkers(ownKeeps, ownBorrows, ownLends, ownRecord, /*hasThis=*/false, 0, ownImmortalizes); printFunction( name, @@ -731,17 +732,25 @@ namespace typescript newline(); } - // every index `@lends` names: MLIRGen refuses one past 63, which the mask cannot hold + // every index `@lends` and `@immortalizes` name: MLIRGen refuses one past 63, which the + // masks cannot hold SmallVector lends; + SmallVector immortalizes; for (int32_t index = 0; index < 64; ++index) { if (method.ownLendsMask & (uint64_t(1) << index)) { lends.push_back(index); } + + if (index < 32 && (method.ownImmortalizesMask & (uint32_t(1) << index))) + { + immortalizes.push_back(index); + } } - printOwnMarkers(method.ownKeeps, method.ownBorrows, lends, method.ownRecord, /*hasThis=*/!method.isStatic, 4); + printOwnMarkers(method.ownKeeps, method.ownBorrows, lends, method.ownRecord, /*hasThis=*/!method.isStatic, 4, + immortalizes); // the slot of a @cpp class's virtual method: without it the importer takes the method // for a non-virtual one diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index 092fef088..3a6182d8f 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -651,6 +651,64 @@ class ReleaseCellOpLowering : public TsLlvmPattern } }; +// -mm=own's keepers (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): the block a +// value kept for good relies on is marked immortal, so every release skips it. +class MakeImmortalOpLowering : public TsLlvmPattern +{ + public: + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::MakeImmortalOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + auto value = transformed.getValue(); + if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn && !op.getAssumed()) + { + OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + auto type = op.getValue().getType(); + if (auto boundFuncType = dyn_cast(type)) + { + // a bound method's object, which it does not own, or a closure's box + TypeHelper th(rewriter); + auto thisValue = rewriter.create(op->getLoc(), th.getPtrType(), value, + ArrayRef{THIS_VALUE_INDEX}); + orl.emitMarkImmortalIfMortal(thisValue); + } + else if (isa(type)) + { + // the instance, the string, the array's header + orl.emitMarkImmortalIfMortal(value); + } + else + { + return op.emitError("-mm=own cannot make a value of this type immortal"); + } + } + + rewriter.replaceOp(op, value); + return mlir::success(); + } +}; + +class MarkImmortalCellOpLowering : public TsLlvmPattern +{ + public: + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::MarkImmortalCellOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn) + { + OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + orl.emitMarkImmortalIfMortal(transformed.getSlot()); + } + + rewriter.eraseOp(op); + return mlir::success(); + } +}; + class SizeOfOpLowering : public TsLlvmPattern { public: @@ -2072,7 +2130,8 @@ struct FuncOpLowering : public TsLlvmPattern // read by -mm=own only if (name == OWN_DECLARED_NO_DROPS_ATTR_NAME || name == OWN_DECLARED_KEEPS_ATTR_NAME || name == OWN_DECLARED_BORROWS_ATTR_NAME || name == OWN_DECLARED_LENDS_ATTR_NAME || - name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME) { + name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME || + name == OWN_DECLARED_IMMORTALIZES_ATTR_NAME) { continue; } @@ -8796,15 +8855,16 @@ static LogicalResult cleanupUnrealizedConversionCast(mlir::ModuleOp &module) // The module's borrow facts (BorrowFactsExportPass) as the exported char array importers read: a // char array, NUL included, so its bytes sit in the object file where the symbol points. // ExportFixPass makes it dllexport on Windows, so the JIT finds it in the default library's DLL. -static void emitBorrowFacts(mlir::ModuleOp m) +// The module's own facts for importers' --own-facts (SHARED_LIB_OWN_OBJECT_FACTS) are made the same way. +static void emitBorrowFacts(mlir::ModuleOp m, llvm::StringRef attrName = SHARED_LIB_BORROW_FACTS_ATTR_NAME) { - auto facts = m->getAttrOfType(SHARED_LIB_BORROW_FACTS_ATTR_NAME); + auto facts = m->getAttrOfType(attrName); if (!facts) { return; } - m->removeAttr(SHARED_LIB_BORROW_FACTS_ATTR_NAME); + m->removeAttr(attrName); auto name = mlir::cast(facts[0]).getValue(); auto text = mlir::cast(facts[1]).getValue().str(); text.push_back(char(0)); @@ -9091,7 +9151,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() PointerOffsetRefOpLowering, LogicalBinaryOpLowering, NullOpLowering, NewOpLowering, CreateTupleOpLowering, DeconstructTupleOpLowering, CreateArrayOpLowering, NewEmptyArrayOpLowering, NewArrayOpLowering, ArrayPushOpLowering, ArrayPopOpLowering, ArrayUnshiftOpLowering, ArrayShiftOpLowering, ArraySpliceOpLowering, ArrayViewOpLowering, DeleteOpLowering, - ParseFloatOpLowering, ParseIntOpLowering, IsNaNOpLowering, PrintOpLowering, ConvertFOpLowering, StoreOpLowering, SizeOfOpLowering, TypeDescriptorOpLowering, RetainOpLowering, ReleaseOpLowering, RetainSlotOpLowering, ReleaseSlotOpLowering, RetainCellOpLowering, ReleaseCellOpLowering, ReleaseContentsOpLowering, + ParseFloatOpLowering, ParseIntOpLowering, IsNaNOpLowering, PrintOpLowering, ConvertFOpLowering, StoreOpLowering, SizeOfOpLowering, TypeDescriptorOpLowering, RetainOpLowering, ReleaseOpLowering, RetainSlotOpLowering, ReleaseSlotOpLowering, RetainCellOpLowering, ReleaseCellOpLowering, ReleaseContentsOpLowering, MakeImmortalOpLowering, MarkImmortalCellOpLowering, InsertPropertyOpLowering, LengthOfOpLowering, SetLengthOfOpLowering, StringLengthOpLowering, StringResizeOpLowering, StringConcatOpLowering, StringCopyOpLowering, SharedNewOpLowering, SharedValueRefOpLowering, SharedCountOpLowering, StringCompareOpLowering, AnyCompareOpLowering, CharToStringOpLowering, UndefOpLowering, CopyStructOpLowering, MemoryCopyOpLowering, MemoryMoveOpLowering, @@ -9161,6 +9221,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() giveEntryPointAnExitCode(m, tsContext.compileOptions); emitBorrowFacts(m); + emitBorrowFacts(m, SHARED_LIB_OWN_OBJECT_FACTS_ATTR_NAME); LLVM_DEBUG(llvm::dbgs() << "\n!! AFTER DUMP: \n" << m << "\n";); diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index ab66e296c..3b629c18f 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -951,6 +951,11 @@ namespace mlirgen return *folded; } + if (auto folded = foldLiteralCompare(location, opCode, leftExpressionValue, rightExpressionValue)) + { + return *folded; + } + auto resultReturnUnions = binaryOpLogicForUnions(location, opCode, leftExpressionValue, rightExpressionValue, genContext); if (resultReturnUnions.value || resultReturnUnions.failed()) @@ -2352,6 +2357,36 @@ namespace mlirgen return value; } + // the memory model the module is compiled for, as a string literal ("gc", "rc", "own", + // "none"): `if (__MEMORY_MODEL__ === "gc")` is decided here, and the branch not taken is + // never generated (foldLiteralCompare), so code another model needs - the collector's API, + // a reference only gc has to keep - costs this one nothing, not even its facts under own + // (a name that starts with `__` arrives escaped, with one more `_`, as TypeScript escapes it) + // ...and the target's OS and architecture, named as Node's process.platform and + // process.arch name them + auto builtinName = name.starts_with("___") ? name.drop_front() : name; + std::optional constantText; + llvm::Triple triple(compileOptions.moduleTargetTriple); + if (builtinName == MEMORY_MODEL_IDENTIFIER) + { + constantText = memoryModelName(compileOptions.memoryModel); + } + else if (builtinName == TARGET_OS_IDENTIFIER) + { + constantText = targetOSName(triple); + } + else if (builtinName == TARGET_ARCH_IDENTIFIER) + { + constantText = targetArchName(triple); + } + + if (constantText) + { + auto constant = mlirGenStringValue(location, *constantText); + V(constant).getDefiningOp()->setAttr(COMPILE_TIME_CONSTANT_ATTR_NAME, builder.getUnitAttr()); + return constant; + } + if (MLIRCustomMethods::isInternalFunctionName(compileOptions, name)) { auto symbOp = builder.create( diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index b9bc5466b..ffefa4e96 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1288,7 +1288,8 @@ namespace mlirgen if (auto globalOp = theModule.lookupSymbol(globalName)) { for (auto *name : {OWN_DECLARED_KEEPS_ATTR_NAME, OWN_DECLARED_BORROWS_ATTR_NAME, OWN_DECLARED_LENDS_ATTR_NAME, - OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_PARAM_NAMES_ATTR_NAME}) + OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_IMMORTALIZES_ATTR_NAME, + OWN_DECLARED_PARAM_NAMES_ATTR_NAME}) { if (auto attr = declared->getAttr(name)) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index efb65fa60..d15a4bb01 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -287,6 +287,8 @@ class MLIRGenImpl void addImportedOwnNoDrops(StringRef factsText); + void addImportedOwnObjectFacts(StringRef factsText); + mlir::LogicalResult mlirGen(ImportDeclaration importDeclarationAST, const GenContext &genContext); mlir::LogicalResult mlirGenImportBindings(ImportClause importClause); @@ -3413,14 +3415,16 @@ class MLIRGenImpl return; } - if (name != KEEPS_DECORATOR && name != BORROWS_DECORATOR && name != LENDS_DECORATOR) + if (name != KEEPS_DECORATOR && name != BORROWS_DECORATOR && name != LENDS_DECORATOR && + name != IMMORTALIZES_DECORATOR) { return; } - auto attrName = name == KEEPS_DECORATOR ? OWN_DECLARED_KEEPS_ATTR_NAME - : name == BORROWS_DECORATOR ? OWN_DECLARED_BORROWS_ATTR_NAME - : OWN_DECLARED_LENDS_ATTR_NAME; + auto attrName = name == KEEPS_DECORATOR ? OWN_DECLARED_KEEPS_ATTR_NAME + : name == BORROWS_DECORATOR ? OWN_DECLARED_BORROWS_ATTR_NAME + : name == IMMORTALIZES_DECORATOR ? OWN_DECLARED_IMMORTALIZES_ATTR_NAME + : OWN_DECLARED_LENDS_ATTR_NAME; if (llvm::any_of(attrs, [&](mlir::NamedAttribute &attr) { return attr.getName() == attrName; })) { emitError(location) << "'@" << name << "' is given twice"; @@ -10283,6 +10287,40 @@ class MLIRGenImpl return std::nullopt; } + // A compare of a compile-time constant with a string literal, whose answer is known here: a + // boolean literal, which an `if` or `?:` reads to generate the branch taken only + // (`__MEMORY_MODEL__ === "gc"`) + std::optional foldLiteralCompare(mlir::Location location, SyntaxKind opCode, + mlir::Value leftValue, mlir::Value rightValue) + { + auto isEquals = opCode == SyntaxKind::EqualsEqualsToken || opCode == SyntaxKind::EqualsEqualsEqualsToken; + auto isNotEquals = opCode == SyntaxKind::ExclamationEqualsToken || opCode == SyntaxKind::ExclamationEqualsEqualsToken; + if ((!isEquals && !isNotEquals) || !leftValue || !rightValue) + { + return std::nullopt; + } + + // a compile-time constant (__MEMORY_MODEL__, __OS__, __ARCH__) and a string constant + auto leftConstant = leftValue.getDefiningOp(); + auto rightConstant = rightValue.getDefiningOp(); + if (!leftConstant || !rightConstant || + (!leftConstant->hasAttr(COMPILE_TIME_CONSTANT_ATTR_NAME) && + !rightConstant->hasAttr(COMPILE_TIME_CONSTANT_ATTR_NAME))) + { + return std::nullopt; + } + + auto leftAttr = dyn_cast(leftConstant.getValue()); + auto rightAttr = dyn_cast(rightConstant.getValue()); + if (!leftAttr || !rightAttr) + { + return std::nullopt; + } + + auto equal = leftAttr == rightAttr; + return mlirGenBooleanValue(location, isEquals ? equal : !equal); + } + ValueOrLogicalResult mlirGenBinaryValues(mlir::Location location, SyntaxKind opCode, mlir::Value leftExpressionValue, mlir::Value rightExpressionValue, const GenContext &genContext, bool saveResult = false); @@ -13108,6 +13146,23 @@ class MLIRGenImpl } methodInfo.ownRecord = funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME); + + methodInfo.ownImmortalizesMask = 0; + if (auto immortalizes = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME)) + { + for (auto index : immortalizes.asArrayRef()) + { + // the class's declaration is printed from a 32-bit mask + if (index >= 32) + { + emitError(location) << "'@" IMMORTALIZES_DECORATOR "' of '" << funcOp.getSymName() + << "' names an argument past the 32nd"; + return false; + } + + methodInfo.ownImmortalizesMask |= uint32_t(1) << index; + } + } } if (propertyName.size() > 0) @@ -14696,7 +14751,7 @@ class MLIRGenImpl }; dp.print(funcProto->getNameWithoutNamespace(), elementNamespace, funcProto->getFuncType(), dllName, marker(OWN_DECLARED_KEEPS_ATTR_NAME), marker(OWN_DECLARED_BORROWS_ATTR_NAME), marker(OWN_DECLARED_LENDS_ATTR_NAME), - funcOp && funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME)); + funcOp && funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME), marker(OWN_DECLARED_IMMORTALIZES_ATTR_NAME)); declExports << ss.str().str(); } @@ -15548,6 +15603,49 @@ class MLIRGenImpl return fullPath.str().str(); } + // __OS__: win32, linux, android, darwin, or the target triple's OS name + static StringRef targetOSName(const llvm::Triple &triple) + { + if (triple.isAndroid()) + { + return "android"; + } + + switch (triple.getOS()) + { + case llvm::Triple::Win32: + return "win32"; + case llvm::Triple::Linux: + return "linux"; + case llvm::Triple::Darwin: + case llvm::Triple::MacOSX: + return "darwin"; + default: + return llvm::Triple::getOSTypeName(triple.getOS()); + } + } + + // __ARCH__: x64, ia32, arm64, arm, wasm32, or the target triple's architecture name + static StringRef targetArchName(const llvm::Triple &triple) + { + switch (triple.getArch()) + { + case llvm::Triple::x86_64: + return "x64"; + case llvm::Triple::x86: + return "ia32"; + case llvm::Triple::aarch64: + return "arm64"; + case llvm::Triple::arm: + case llvm::Triple::thumb: + return "arm"; + case llvm::Triple::wasm32: + return "wasm32"; + default: + return llvm::Triple::getArchTypeName(triple.getArch()); + } + } + // The OS part of a module's file name for the target (includeFilePath): win32, linux (Android // too, as the default library builds lib.linux.ts for it), or the target triple's OS name. StringRef targetOSFileSuffix() diff --git a/tslang/lib/TypeScript/MLIRGenModule.cpp b/tslang/lib/TypeScript/MLIRGenModule.cpp index 0ba0d13c5..b57457db6 100644 --- a/tslang/lib/TypeScript/MLIRGenModule.cpp +++ b/tslang/lib/TypeScript/MLIRGenModule.cpp @@ -15,6 +15,7 @@ #include "mlir/IR/Verifier.h" +#include "mlir/AsmParser/AsmParser.h" #include "mlir/Dialect/DLTI/DLTI.h" #include "mlir/Support/FileUtilities.h" @@ -429,9 +430,79 @@ namespace mlirgen builder.setInsertionPointToStart(theModule.getBody()); + if (!compileOptions.importedOwnFacts.empty()) + { + addImportedOwnObjectFacts(compileOptions.importedOwnFacts); + } + return mlir::success(); } + // The facts of the objects --own-facts names (SHARED_LIB_OWN_OBJECT_FACTS): a function's name + // alone joins the imported no-drops ones; one with places goes to SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME. + // A line whose slot type does not parse here gives that function no facts at all. + void MLIRGenImpl::addImportedOwnObjectFacts(StringRef factsText) + { + std::string noDrops; + llvm::SmallVector dropFields; + llvm::SmallVector freshResults; + llvm::StringSet<> seen; + llvm::SmallVector lines; + factsText.split(lines, '\n', -1, false); + for (auto line : lines) + { + llvm::SmallVector parts; + line.trim().split(parts, '\t', -1, false); + if (parts.empty() || !seen.insert(parts.front()).second) + { + continue; + } + + if (parts.size() > 1 && parts.back() == OWN_OBJECT_FACTS_FRESH_RESULT) + { + freshResults.push_back(builder.getStringAttr(parts.front())); + parts.pop_back(); + } + + if (parts.size() == 1) + { + noDrops += parts.front().str() + "\n"; + continue; + } + + llvm::SmallVector 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) + { + places.clear(); + break; + } + + places.push_back(builder.getArrayAttr({builder.getI64IntegerAttr(position), mlir::TypeAttr::get(type)})); + } + + if (!places.empty()) + { + dropFields.push_back(builder.getNamedAttr(parts.front(), builder.getArrayAttr(places))); + } + } + + addImportedOwnNoDrops(noDrops); + if (!dropFields.empty()) + { + theModule->setAttr(SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME, builder.getDictionaryAttr(dropFields)); + } + + if (!freshResults.empty()) + { + theModule->setAttr(SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME, builder.getArrayAttr(freshResults)); + } + } + #ifdef GENERATE_IMPORT_INFO_USING_D_TS_FILE mlir::LogicalResult MLIRGenImpl::createDependencyDeclarationFile(StringRef outputFilename, StringRef dependencyDeclFileBody) { diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index b92804106..647a2fa0c 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -97,6 +97,17 @@ constexpr int64_t OWN_INTERFACE_FIELD_POSITION = -3; // every `ts.AddressOf` of it (isImmortalGlobalRead), and on the `ts.Store` that initializes it, // whose lowering writes the header word. #define OWN_IMMORTAL_GLOBAL_ATTR_NAME "__own_immortal" +// A keeper (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): an append-only array +// global of this module, never given another value, whose elements nothing takes out or overwrites. +// What it holds lives to the end of the program, so each value pushed into it is made immortal +// (ts.MakeImmortal). On every `ts.AddressOf` of it, which no global read is (the array is never +// replaced), and on every `ts.Load` of one of its elements (OWN_KEEPER_READ_ATTR_NAME), which is +// immortal and no place read. +#define OWN_KEEPER_GLOBAL_ATTR_NAME "__own_keeper_global" +#define OWN_KEEPER_READ_ATTR_NAME "__own_keeper_read" +// On a function: the parameters it keeps for good, in a keeper or through a callee that does +// (argument indices). Its callers make each argument immortal. +#define OWN_IMMORTALIZES_ATTR_NAME "__own_immortalizes" // A call inside a try body is a `ts.Invoke` (`ts.InvokeHybrid` through a hybrid function): a // terminator whose normal and unwind edges are its successors. It names its callee as a symbol, or @@ -401,6 +412,15 @@ inline mlir_ts::AddressOfOp globalReadOf(mlir::Value value) // A read of an immortal global (OWN_IMMORTAL_GLOBAL_ATTR_NAME), seen through its views: the // global's own block, which no release frees. Its fields are not immortal: a read out of one is a // place read like any other. +// A value made immortal where a keeper keeps it (ts.MakeImmortal), or a keeper's element, seen +// through its views: owned by no one, and no release frees it. +inline bool isKeptForGood(mlir::Value value) +{ + auto *def = rootOf(value).getDefiningOp(); + return def && (mlir::isa(def) || + (mlir::isa(def) && def->hasAttr(OWN_KEEPER_READ_ATTR_NAME))); +} + inline bool isImmortalGlobalRead(mlir::Value value) { auto addressOfOp = globalReadOf(value); diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 33a6a9004..ceafb0c07 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -746,6 +746,15 @@ namespace own_inference return; } + // kept for good (a keeper's): the box, its cells and its copies are immortal from + // here, so the frame's releases of them free nothing, and whatever is done with the + // immortal value - pushed, stored, run later - outlives nothing it relies on + if (mlir::isa(user)) + { + uses.push_back(user); + return; + } + if (isCall(user)) { if (isKeptArgument(user, used)) diff --git a/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp b/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp index bcbbcee57..01e64c017 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp @@ -77,7 +77,9 @@ namespace own_inference { auto addressOfOp = loadOp.getReference().getDefiningOp(); auto result = loadOp.getResult(); - return addressOfOp && !addressOfOp->hasAttr(OWN_IMMORTAL_GLOBAL_ATTR_NAME) && ownsHeap(result) && !isHandle(result); + // a keeper is never given another array, only appended to (OWN_KEEPER_GLOBAL_ATTR_NAME) + return addressOfOp && !addressOfOp->hasAttr(OWN_IMMORTAL_GLOBAL_ATTR_NAME) && + !addressOfOp->hasAttr(OWN_KEEPER_GLOBAL_ATTR_NAME) && ownsHeap(result) && !isHandle(result); } void OwnershipInferencePass::checkGlobalRead(mlir_ts::LoadOp read) diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index 58ef47d38..e0f5ae309 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -329,7 +329,9 @@ namespace own_inference bool OwnershipInferencePass::isImmortalLiteral(mlir::Value value) { - if (isImmortalGlobalRead(value)) + // ...or a value a keeper keeps for good, which is made immortal (ts.MakeImmortal), and a + // keeper's element + if (isImmortalGlobalRead(value) || isKeptForGood(value)) { return true; } @@ -341,6 +343,12 @@ namespace own_inference bool OwnershipInferencePass::isBorrow(mlir::Operation *user, mlir::Value value) { + // marking a value immortal (a keeper's) reads it; the result is another value, owned by none + if (mlir::isa(user)) + { + return true; + } + if (mlir::isahasAttr(OWN_FRESH_RESULT_ATTR_NAME)) + // nor is a keeper's element, which no release frees (OWN_KEEPER_READ_ATTR_NAME) + if (placeReadOf(loadOp.getResult()) && !loadOp->hasAttr(OWN_FRESH_RESULT_ATTR_NAME) && + !loadOp->hasAttr(OWN_KEEPER_READ_ATTR_NAME)) { ops.placeReads.push_back(loadOp); } @@ -362,7 +364,8 @@ namespace own_inference continue; } - if (value && placeReadOf(value)) + // (not a keeper's element, which is no place read: immortal, decided below) + if (value && placeReadOf(value) && !isKeptForGood(value)) { continue; // a read out of a container: checkPlaceRead decided it } @@ -414,7 +417,8 @@ namespace own_inference // an immortal global's value (spec 25): owned by no one, so returned, stored or kept // as often as it is read, and its releases skip it - if (value && isImmortalGlobalRead(value) && (mlir::isa(op) || slotHoldsInitializerAt(op))) + if (value && (isImmortalGlobalRead(value) || isKeptForGood(value)) && + (mlir::isa(op) || slotHoldsInitializerAt(op))) { toErase.insert(op); continue; diff --git a/tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp b/tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp new file mode 100644 index 000000000..90821a709 --- /dev/null +++ b/tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp @@ -0,0 +1,549 @@ +// OwnershipSignaturePass (see OwnershipSignaturePass.h): keepers - append-only array globals whose +// elements live to the end of the program - and the values they keep, made immortal where it is +// known what they rely on (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md). + +#include "OwnershipSignaturePass.h" + +#include + +#define DEBUG_TYPE "own" + +namespace own_signature +{ + + // The value a chain of casts starts from: `this.onTick` cast to the array's function type + static mlir::Value castRoot(mlir::Value value) + { + while (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + } + + return value; + } + + // Does a global's initializer region give it a new array - `[]`, an array literal - and nothing + // else? + static bool regionYieldsNewArray(mlir_ts::GlobalOp globalOp) + { + if (!globalOp.getInitializerRegion().hasOneBlock()) + { + return false; + } + + auto resultOp = mlir::dyn_cast(globalOp.getInitializerBlock()->getTerminator()); + if (!resultOp || resultOp->getNumOperands() != 1) + { + return false; + } + + auto *def = castRoot(resultOp->getOperand(0)).getDefiningOp(); + return mlir::isa_and_nonnull(def); + } + + void OwnershipSignaturePass::findKeepers(mlir::ModuleOp module) + { + auto uses = mlir::SymbolTable::getSymbolUses(&module.getBodyRegion()); + if (!uses) + { + return; // an op this pass cannot read symbols through: nothing is known append-only + } + + llvm::StringMap> usesOf; + for (auto &use : *uses) + { + usesOf[use.getSymbolRef().getRootReference().getValue()].push_back(use.getUser()); + } + + auto mth = typeHelper(&getContext()); + module.walk([&](mlir_ts::GlobalOp globalOp) { + auto arrayType = mlir::dyn_cast(globalOp.getType()); + if (!arrayType || globalOp->hasAttr("export") || globalOp->hasAttr("import") || globalOp->hasAttr(DLL_EXPORT) || + globalOp->hasAttr(DLL_IMPORT) || !regionYieldsNewArray(globalOp)) + { + return; + } + + // an element ts.MakeImmortal can mark, that owns a block (not a @cpp object) + auto elementType = arrayType.getElementType(); + if (!mlir::isa(elementType) || + !mth.ownsHeapMemory(globalOp.getLoc(), elementType)) + { + return; + } + + // pushed onto, its length read, its elements loaded: nothing else + llvm::SmallVector addresses; + llvm::SmallVector elementReads; + for (auto *user : usesOf.lookup(globalOp.getSymName())) + { + auto addressOfOp = mlir::dyn_cast(user); + if (!addressOfOp) + { + return; + } + + for (auto *addressUser : addressOfOp->getUsers()) + { + // in a function, which decideKeptForGood looks at: not a global's region + if (auto pushOp = mlir::dyn_cast(addressUser); + pushOp && pushOp.getOp() == addressOfOp.getResult() && + !llvm::is_contained(pushOp.getItems(), addressOfOp.getResult()) && + pushOp->getParentOfType()) + { + continue; + } + + auto loadOp = mlir::dyn_cast(addressUser); + if (!loadOp) + { + return; + } + + for (auto *arrayUser : loadOp->getUsers()) + { + if (mlir::isa(arrayUser)) + { + continue; + } + + auto elementRefOp = mlir::dyn_cast(arrayUser); + if (!elementRefOp || elementRefOp->getOperand(0) != loadOp.getResult()) + { + return; + } + + for (auto *elementUser : elementRefOp->getUsers()) + { + auto elementLoad = mlir::dyn_cast(elementUser); + if (!elementLoad) + { + return; + } + + elementReads.push_back(elementLoad); + } + } + } + + addresses.push_back(addressOfOp); + } + + keepers.insert(globalOp.getSymName()); + for (auto addressOfOp : addresses) + { + addressOfOp->setAttr(OWN_KEEPER_GLOBAL_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + + for (auto elementLoad : elementReads) + { + elementLoad->setAttr(OWN_KEEPER_READ_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + }); + } + + OwnershipSignaturePass::Kept OwnershipSignaturePass::classifyKept(mlir::Value value, mlir_ts::FuncOp funcOp) + { + auto root = castRoot(value); + if (holdsNoBlock(root) || isConstantData(root) || isKeptForGood(root) || isImmortalGlobalRead(root)) + { + return {KeptKind::Immortal}; + } + + int32_t index = -1; + if (readsParameterSlot(root, funcOp, index)) + { + return {KeptKind::Param, index, root}; + } + + auto *def = root.getDefiningOp(); + if (!def) + { + return {KeptKind::Unknown}; + } + + // read out of an owning local declared from it and never assigned: what it was declared from, + // the block the read is + if (auto loadOp = mlir::dyn_cast(def)) + { + auto varOp = loadOp.getReference().getDefiningOp(); + if (varOp && isOwningVariable(varOp) && !varOp.getCaptured().value_or(false) && varOp.getInitializer() && + !isAssigned(varOp)) + { + auto declared = classifyKept(varOp.getInitializer(), funcOp); + if (declared.kind == KeptKind::Mark) + { + declared.root = root; + } + + if (declared.kind == KeptKind::Mark || declared.kind == KeptKind::Immortal) + { + return declared; + } + } + + return {KeptKind::Unknown}; + } + + // a closure: its box, and the cells and values the box borrows from this frame + if (auto boundOp = mlir::dyn_cast(def)) + { + auto boxOp = boundOp.getThisVal().getDefiningOp(); + if (boxOp && boxOp->hasAttr(CAPTURE_BOX_ATTR_NAME)) + { + return {KeptKind::Mark, -1, root, boxOp.getResult()}; + } + + return {KeptKind::Unknown}; + } + + // a bound method: the object, which it holds without owning + if (mlir::isa(def) && + mlir::isa(root.getType())) + { + auto object = def->getOperand(0); + if (mlir::isa(object.getType()) && own_facts::ownsHeap(object)) + { + return {KeptKind::Mark, -1, root}; + } + + return {KeptKind::Unknown}; + } + + // made here: an object, an array, a string + if (mlir::isa(root.getType()) && + own_facts::ownsHeap(root) && isFresh(root)) + { + return {KeptKind::Mark, -1, root}; + } + + return {KeptKind::Unknown}; + } + + llvm::SmallVector OwnershipSignaturePass::calleesImmortalize(const Callees &callees, bool &disagree) + { + disagree = false; + if (callees.viaCallback) + { + return {}; + } + + // the functions it may reach; a call this pass knows nothing else of - another module's + // function, which says what it keeps for good in its declaration - by the symbols it names + llvm::SmallVector funcs(callees.funcs.begin(), callees.funcs.end()); + if (funcs.empty()) + { + for (auto name : callees.named) + { + if (auto funcOp = functions.lookup(name.getValue())) + { + funcs.push_back(funcOp); + } + else + { + return {}; + } + } + } + + std::optional> common; + for (auto callee : funcs) + { + auto found = immortalizes.find(callee); + llvm::SmallVector those; + if (found != immortalizes.end()) + { + those = found->second; + } + + if (!common) + { + common = those; + } + else if (*common != those) + { + disagree = true; + return {}; + } + } + + return common ? *common : llvm::SmallVector(); + } + + bool OwnershipSignaturePass::takesAddress(mlir_ts::FuncOp funcOp, mlir::ModuleOp module) + { + auto uses = mlir::SymbolTable::getSymbolUses(funcOp.getSymNameAttr(), &module.getBodyRegion()); + if (!uses) + { + return true; + } + + for (auto &use : *uses) + { + auto *user = use.getUser(); + // a direct call, or a virtual one, whose family is resolved; the class vtable's entry + if (mlir::isa(user) || + (mlir::isa(user) && isClassVTableEntry(user))) + { + continue; + } + + return true; + } + + return false; + } + + void OwnershipSignaturePass::makeImmortal(const Kept &kept, bool assumed) + { + auto root = kept.root; + mlir::OpBuilder builder(&getContext()); + builder.setInsertionPointAfterValue(root); + auto makeOp = builder.create(root.getLoc(), root.getType(), root, + assumed ? builder.getUnitAttr() : mlir::UnitAttr()); + root.replaceAllUsesExcept(makeOp.getResult(), makeOp); + if (!kept.box) + { + return; + } + + // what the box holds and borrows from this frame, which releases it: each captured cell, and + // each value captured by value that owns a block + for (auto *boxUser : kept.box.getUsers()) + { + auto propertyRefOp = mlir::dyn_cast(boxUser); + if (!propertyRefOp) + { + continue; + } + + for (auto *fieldUser : propertyRefOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != propertyRefOp.getResult()) + { + continue; + } + + auto captured = storeOp.getValue(); + if (mlir::isa(captured.getType())) + { + builder.create(captured.getLoc(), captured); + } + else if (own_facts::ownsHeap(captured) && !holdsNoBlock(captured)) + { + builder.create(captured.getLoc(), captured.getType(), captured, mlir::UnitAttr()); + } + } + } + } + + void OwnershipSignaturePass::decideKeptForGood(mlir::ModuleOp module) + { + // a value kept for good: a keeper's push of it, or a call's argument its callee keeps so + struct Site + { + mlir::Operation *op; + unsigned operand; + }; + + llvm::MapVector> pushes; + module.walk([&](mlir_ts::ArrayPushOp pushOp) { + auto addressOfOp = pushOp.getOp().getDefiningOp(); + auto funcOp = pushOp->getParentOfType(); + if (!addressOfOp || !addressOfOp->hasAttr(OWN_KEEPER_GLOBAL_ATTR_NAME) || !funcOp) + { + return; + } + + for (auto index : llvm::seq(1, pushOp->getNumOperands())) + { + pushes[funcOp].push_back({pushOp, index}); + } + }); + + // what declarations say: a C function that keeps a callback for good + immortalizes.clear(); + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (auto declared = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME); + declared && funcOp.isDeclaration()) + { + immortalizes[funcOp].assign(declared.asArrayRef().begin(), declared.asArrayRef().end()); + } + } + + auto addParam = [&](mlir_ts::FuncOp funcOp, int32_t param) { + auto ¶ms = immortalizes[funcOp]; + if (llvm::is_contained(params, param)) + { + return false; + } + + params.insert(llvm::upper_bound(params, param), param); + return true; + }; + + // a parameter pushed, or given to a callee's parameter kept for good, is kept for good + for (auto changed = true; changed;) + { + changed = false; + for (auto &[op, sites] : pushes) + { + auto funcOp = mlir::cast(op); + for (auto site : sites) + { + auto kept = classifyKept(site.op->getOperand(site.operand), funcOp); + if (kept.kind == KeptKind::Param) + { + changed |= addParam(funcOp, kept.param); + } + } + } + + for (auto &call : calls) + { + auto funcOp = call.op->getParentOfType(); + bool disagree = false; + auto args = callArgs(call.op); + for (auto index : calleesImmortalize(call.callees, disagree)) + { + if (funcOp && static_cast(index) < args.size()) + { + auto kept = classifyKept(args[index], funcOp); + if (kept.kind == KeptKind::Param) + { + changed |= addParam(funcOp, kept.param); + } + } + } + } + } + + auto failed = false; + auto describe = [](mlir_ts::FuncOp funcOp, llvm::ArrayRef params) { return describeParams(funcOp, params); }; + + // a function's callers must all know to make what they give it immortal + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (funcOp.isDeclaration()) + { + continue; + } + + auto found = immortalizes.find(funcOp); + llvm::SmallVector computed; + if (found != immortalizes.end()) + { + computed = found->second; + } + + auto declared = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME); + if (declared && llvm::ArrayRef(computed) != declared.asArrayRef()) + { + funcOp.emitError("'@" IMMORTALIZES_DECORATOR "' of '") + << funcOp.getSymName() << "' names " << describe(funcOp, declared.asArrayRef()) + << ", but its body keeps for good " << describe(funcOp, computed); + failed = true; + continue; + } + + if (computed.empty()) + { + continue; + } + + if (takesAddress(funcOp, module)) + { + funcOp.emitError("'") << funcOp.getSymName() << "' keeps " << describe(funcOp, computed) + << " for good, but -mm=own cannot make every caller make it immortal: the function is " + "called through a value"; + failed = true; + } + else if (!declared && open.contains(funcOp)) + { + funcOp.emitError("'") << funcOp.getSymName() << "' keeps " << describe(funcOp, computed) + << " for good, but -mm=own cannot tell its callers in other modules; '@" IMMORTALIZES_DECORATOR + "' would say it in its signature"; + failed = true; + } + } + + // a family whose members disagree: some calls of the one that keeps would not mark + for (auto &call : calls) + { + bool disagree = false; + calleesImmortalize(call.callees, disagree); + if (disagree) + { + call.op->emitError("the functions this call may reach do not all keep the same arguments for good; -mm=own " + "cannot make what it passes immortal"); + failed = true; + } + } + + if (failed) + { + signalPassFailure(); + return; + } + + // every value kept for good: immortal from where it is made, or where it is a parameter + auto decide = [&](mlir::Operation *site, mlir::Value value, mlir_ts::FuncOp funcOp, llvm::StringRef where) { + auto kept = classifyKept(value, funcOp); + switch (kept.kind) + { + case KeptKind::Immortal: + return; + case KeptKind::Param: + makeImmortal(kept, /*assumed=*/true); + return; + case KeptKind::Mark: + makeImmortal(kept, /*assumed=*/false); + return; + case KeptKind::Unknown: + site->emitError("-mm=own cannot make the value ") << where << " immortal here: it is not made here, nor a parameter"; + failed = true; + return; + } + }; + + for (auto &[op, sites] : pushes) + { + for (auto site : sites) + { + auto pushOp = mlir::cast(site.op); + auto addressOfOp = pushOp.getOp().getDefiningOp(); + decide(site.op, site.op->getOperand(site.operand), mlir::cast(op), + ("kept in '" + addressOfOp.getGlobalName() + "'").str()); + } + } + + for (auto &call : calls) + { + auto funcOp = call.op->getParentOfType(); + bool disagree = false; + auto params = calleesImmortalize(call.callees, disagree); + for (auto index : params) + { + auto args = callArgs(call.op); + if (funcOp && static_cast(index) < args.size()) + { + decide(call.op, args[index], funcOp, "given to a parameter its callee keeps for good"); + } + } + } + + if (failed) + { + signalPassFailure(); + } + } + +} // namespace own_signature + +#undef DEBUG_TYPE diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 9a6c27b43..9dbe1f307 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -30,6 +30,26 @@ namespace own_signature } } + if (auto functionsDropping = module->getAttrOfType(SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME)) + { + for (auto entry : functionsDropping) + { + auto &drops = importedFieldDrops[entry.getName().getValue()]; + for (auto place : mlir::cast(entry.getValue()).getAsRange()) + { + drops.add({mlir::cast(place[0]).getInt(), mlir::cast(place[1]).getValue()}); + } + } + } + + if (auto names = module->getAttrOfType(SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME)) + { + for (auto name : names.getAsRange()) + { + importedFreshResults.insert(name.getValue()); + } + } + findImmortalGlobals(module); moveIntoGlobals(module); rejectBorrowedGlobalInitializers(module); @@ -51,6 +71,9 @@ namespace own_signature }); findOpen(module); + // before the facts: a value kept for good is immortal, which keeps nothing of its owner + findKeepers(module); + decideKeptForGood(module); computeFacts(); computeDrops(); pinAssignedGlobals(); @@ -89,8 +112,9 @@ namespace own_signature continue; } - if (call.callees.instanceOf || call.callees.imported || - llvm::all_of(call.callees.funcs, [&](mlir_ts::FuncOp callee) { return noDrops.contains(callee); })) + if (call.callees.instanceOf || (call.callees.imported && !call.callees.importedOverwrites) || + (!call.callees.imported && + llvm::all_of(call.callees.funcs, [&](mlir_ts::FuncOp callee) { return noDrops.contains(callee); }))) { call.op->setAttr(OWN_NO_DROPS_ATTR_NAME, mlir::UnitAttr::get(&getContext())); } @@ -108,8 +132,11 @@ namespace own_signature } // `new C()` of a class from a library built under own: see OWN_FRESH_RESULT_ATTR_NAME - if (call.callees.imported && call.callees.importedName.ends_with("." NEW_METHOD_NAME) && - call.op->getNumResults() == 1) + // ...and of a function another own module's object says returns one its caller owns + // (--own-facts) + if (call.callees.imported && call.op->getNumResults() == 1 && + ((!call.callees.importedOverwrites && call.callees.importedName.ends_with("." NEW_METHOD_NAME)) || + importedFreshResults.contains(call.callees.importedName))) { call.op->setAttr(OWN_FRESH_RESULT_ATTR_NAME, mlir::UnitAttr::get(&getContext())); } @@ -1190,12 +1217,23 @@ namespace own_signature std::optional OwnershipSignaturePass::calleesFieldDrops(const Callees &callees) { - if (!callees.known || callees.instanceOf || callees.imported) + if (!callees.known || callees.instanceOf) { return std::nullopt; } FieldDrops all; + if (callees.imported) + { + // what the imported module's object says (--own-facts), or nothing at all + for (auto place : callees.importedPlaces) + { + all.add(place); + } + + return all; + } + for (auto callee : callees.funcs) { if (noDrops.contains(callee)) @@ -1285,28 +1323,34 @@ namespace own_signature return true; } - return !callees.instanceOf && !callees.imported && + if (callees.imported) + { + return callees.importedOverwrites; + } + + return !callees.instanceOf && llvm::any_of(callees.funcs, [&](mlir_ts::FuncOp callee) { return !noDrops.contains(callee); }); } - void OwnershipSignaturePass::exportNoDrops() + // Its one result is the caller's to own, as a call of it here is (isFresh): its body borrows no + // argument for it, nor says one does, and it does not hand back a record that borrows + bool OwnershipSignaturePass::returnsFresh(mlir_ts::FuncOp funcOp) { - auto markerPrefix = std::string(SHARED_LIB_MEMORY_MODEL) + "own_"; - mlir_ts::GlobalOp marker; - for (auto &entry : globals) + if (funcOp.getFunctionType().getNumResults() != 1 || funcOp->hasAttr(OWN_DECLARED_LENDS_ATTR_NAME) || + funcOp->hasAttr(OWN_DECLARED_BORROWS_ATTR_NAME) || funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME)) { - if (entry.getKey().starts_with(markerPrefix)) - { - marker = entry.second; - break; - } + return false; } - if (!marker) - { - return; - } + // the effective facts are kept only when not empty + auto local = factsLocal.find(funcOp); + auto effective = factsEffective.lookup(funcOp); + return local != factsLocal.end() && local->second.borrows.empty() && !local->second.record && + effective.borrows.empty() && !effective.record; + } + void OwnershipSignaturePass::exportNoDrops() + { llvm::SmallVector names; for (auto &entry : functions) { @@ -1325,6 +1369,79 @@ namespace own_signature text += '\n'; } + // The same names, and the places each other exported function overwrites when that is all + // it destroys, as the char array an importer reads from this module's object + // (SHARED_LIB_OWN_OBJECT_FACTS): `` or `\t ...`, and a last + // field OWN_OBJECT_FACTS_FRESH_RESULT when its result is its caller's to own. Written + // whatever the module exports, as a static library is compiled with --export=none. + llvm::SmallVector> lines; + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (funcOp.isDeclaration() || funcOp.isPrivate()) + { + continue; + } + + auto found = fieldDrops.find(funcOp); + auto overwrites = !noDrops.contains(funcOp) && found != fieldDrops.end() && !found->second.any && + !found->second.places.empty(); + if (!noDrops.contains(funcOp) && !overwrites) + { + continue; + } + + std::string line; + llvm::raw_string_ostream os(line); + if (overwrites) + { + for (auto [position, type] : found->second.places) + { + os << '\t' << position << ' ' << type; + } + } + + if (returnsFresh(funcOp)) + { + os << '\t' << OWN_OBJECT_FACTS_FRESH_RESULT; + } + + lines.push_back({funcOp.getSymName(), line}); + } + + llvm::sort(lines); + std::string objectText; + for (auto &[functionName, fields] : lines) + { + objectText += functionName.str() + fields + "\n"; + } + + mlir::Builder attrBuilder(&getContext()); + if (!objectFactsSymbol.empty() && !objectText.empty()) + { + getOperation()->setAttr(SHARED_LIB_OWN_OBJECT_FACTS_ATTR_NAME, + attrBuilder.getArrayAttr({attrBuilder.getStringAttr(objectFactsSymbol), + attrBuilder.getStringAttr(objectText)})); + } + + // The names, as the shared library's exported SHARED_LIB_OWN_FACTS, beside its memory model + // marker: only a module that has one, exporting its declarations, is imported as -shared + auto markerPrefix = std::string(SHARED_LIB_MEMORY_MODEL) + "own_"; + mlir_ts::GlobalOp marker; + for (auto &entry : globals) + { + if (entry.getKey().starts_with(markerPrefix)) + { + marker = entry.second; + break; + } + } + + if (!marker) + { + return; + } + auto suffix = marker.getSymName().drop_front(markerPrefix.size()); auto name = (llvm::Twine(SHARED_LIB_OWN_FACTS) + suffix).str(); @@ -1499,7 +1616,7 @@ namespace own_signature #undef DEBUG_TYPE -std::unique_ptr mlir_ts::createOwnershipSignaturePass(bool executable) +std::unique_ptr mlir_ts::createOwnershipSignaturePass(bool executable, std::string objectFactsSymbol) { - return std::make_unique(executable); + return std::make_unique(executable, std::move(objectFactsSymbol)); } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 99ad175ca..395ebec68 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -57,11 +57,15 @@ class OwnershipSignaturePass : public mlir::PassWrapper keepers; + void findKeepers(mlir::ModuleOp module); + + // What a value kept for good - pushed into a keeper, or given to a parameter its callee keeps + // so - relies on, and who makes it immortal: nobody (it is already), the callers (a parameter), + // or the function that knows how it was made, which marks `root` (and a closure's `box`). + enum class KeptKind + { + Immortal, + Param, + Mark, + Unknown + }; + + struct Kept + { + KeptKind kind = KeptKind::Unknown; + int32_t param = -1; + mlir::Value root; + mlir::Value box; + }; + + Kept classifyKept(mlir::Value value, mlir_ts::FuncOp funcOp); + + // The parameters each function keeps for good (OWN_IMMORTALIZES_ATTR_NAME): a fixpoint over the + // keepers' pushes and the calls; then every value kept is made immortal (ts.MakeImmortal). + llvm::DenseMap> immortalizes; + void decideKeptForGood(mlir::ModuleOp module); + void makeImmortal(const Kept &kept, bool assumed); + // a reference to the function that is not a call, or a class vtable's entry: a caller that + // would not know to mark what it passes + bool takesAddress(mlir_ts::FuncOp funcOp, mlir::ModuleOp module); + void moveIntoGlobals(mlir::ModuleOp module); void runOnOperation() override; @@ -141,6 +180,10 @@ class OwnershipSignaturePass : public mlir::PassWrapper shifts; // the name the imported function is exported under llvm::StringRef importedName; + // an imported function that destroys the old values of these places and nothing else + // (SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME): `imported` then does not mean it destroys nothing + bool importedOverwrites = false; + llvm::SmallVector, 4> importedPlaces; llvm::SmallVector funcs; // the symbols the call names, whether or not it is known: a direct callee, or every // member of a virtual slot's family (for the facts a declaration says, declaredFacts) @@ -159,6 +202,10 @@ class OwnershipSignaturePass : public mlir::PassWrapper writtenGlobals; llvm::SmallVector calls; + // the parameters every callee of a call keeps for good (immortalizes); `disagree` when some do + // and some not + llvm::SmallVector calleesImmortalize(const Callees &callees, bool &disagree); + // Functions of imported libraries that destroy nothing a caller can reach, by the name they // are exported under (SHARED_LIB_OWN_NO_DROPS_ATTR_NAME). llvm::StringSet<> importedNoDrops; @@ -540,6 +587,13 @@ class OwnershipSignaturePass : public mlir::PassWrapper fieldDrops; + // The FieldDrops of the functions --own-facts read from the objects of the modules this one + // imports, by name (SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME). + llvm::StringMap importedFieldDrops; + + // ...and those it says return a value their caller owns (SHARED_LIB_OWN_FRESH_RESULTS_ATTR_NAME) + llvm::StringSet<> importedFreshResults; + // The body's own share of a function's FieldDrops: its stores, not its calls. FieldDrops fieldDropsInBody(mlir_ts::FuncOp funcOp); @@ -1004,6 +1058,7 @@ class OwnershipSignaturePass : public mlir::PassWrapperhasAttr(OWN_DECLARED_NO_DROPS_ATTR_NAME) || - (scalarDeclaration(funcOp) && !functionsEscape))) + if (!funcOp || !funcOp.isDeclaration()) { return false; } + if (!(importedNoDrops.contains(symbol.getValue()) || funcOp->hasAttr(OWN_DECLARED_NO_DROPS_ATTR_NAME) || + (scalarDeclaration(funcOp) && !functionsEscape))) + { + // a function of an imported module that overwrites only these places (--own-facts) + auto found = importedFieldDrops.find(symbol.getValue()); + if (found == importedFieldDrops.end()) + { + return false; + } + + callees.importedOverwrites = true; + callees.importedPlaces.assign(found->second.places.begin(), found->second.places.end()); + } + callees.imported = true; callees.importedName = symbol.getValue(); return true; diff --git a/tslang/lib/TypeScript/StackEscapeFacts.h b/tslang/lib/TypeScript/StackEscapeFacts.h index f081378e2..9df58e127 100644 --- a/tslang/lib/TypeScript/StackEscapeFacts.h +++ b/tslang/lib/TypeScript/StackEscapeFacts.h @@ -656,6 +656,8 @@ class StackEscapeFacts return argumentEscapes(candidates, use.getOperandNumber() - 1); }) .Case([&](auto) { return "returned"; }) + // -mm=own's keepers: kept for good, it outlives every frame + .Case([&](auto) { return "kept for good"; }) .Case([&](auto) { return "thrown"; }) .Default([&](auto) { return "unclassified"; }); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index f98f18a49..7ee8c3649 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1664,6 +1664,33 @@ if (WIN32) "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" -P "${CMAKE_CURRENT_SOURCE_DIR}/own-shared-record.cmake") endif() +# -mm=own across modules compiled into objects of their own: the importer reads what the library's +# object says its functions destroy (--own-facts, own-facts-objects.cmake) +if (WIN32) + add_test(NAME test-own-facts-objects + COMMAND ${CMAKE_COMMAND} + "-DTSLANG=$" + "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-facts-objects" + "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-facts-objects.cmake") + # ...and a library's keeper: the importer makes what it gives `@immortalizes` immortal + add_test(NAME test-own-keepers-objects + COMMAND ${CMAKE_COMMAND} + "-DTSLANG=$" + "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-keepers-objects" + "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-keepers-objects.cmake") +endif() +# __MEMORY_MODEL__: the branch not taken is not generated (a call of a function defined nowhere there +# would not link) +foreach(model_mm gc rc own none) + tslang_add_test(NAME test-jit-${model_mm}-memory-model-constant COMMAND test-runner -jit -mm=${model_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00memory_model_constant.ts") + tslang_add_test(NAME test-compile-${model_mm}-memory-model-constant COMMAND test-runner -mm=${model_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00memory_model_constant.ts") +endforeach() # the markers mean nothing to the other models foreach(markers_mm gc rc) tslang_add_test(NAME test-jit-${markers_mm}-own-generator-locals COMMAND test-runner -jit -mm=${markers_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_generator_locals.ts") @@ -3850,7 +3877,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_borrowing_record own_borrowing_record_arg own_reduce own_fresh_call_result own_ternary_outer_loop own_destructure_elements own_tuple_record_values own_value_record own_value_loop own_value_temporaries - own_call_field_drops) + own_call_field_drops own_immortal_keepers) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") tslang_add_test(NAME test-compile-own-${own_test} COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") # The promise: no counting at all in what own emits. @@ -3864,7 +3891,7 @@ endforeach() # A global never reassigned is immortal under own (spec 25); the same program under every other model. foreach(immortal_mm rc gc none) - foreach(immortal_test own_immortal_global own_immortal_global_region own_global_loop_store) + foreach(immortal_test own_immortal_global own_immortal_global_region own_global_loop_store own_immortal_keepers) tslang_add_test(NAME test-jit-${immortal_mm}-${immortal_test} COMMAND test-runner -jit -mm=${immortal_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${immortal_test}.ts") tslang_add_test(NAME test-compile-${immortal_mm}-${immortal_test} COMMAND test-runner -mm=${immortal_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${immortal_test}.ts") endforeach() @@ -4274,11 +4301,11 @@ set(own_error_cases "own_err_field_alias|:9:11: error: '[^']*' is used here after its value was moved" "own_err_call_in_try_drops|:30:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_closure_escape_used|:9:11: error: '[^']*' is captured by a closure that escapes, and is still used here" - "own_err_closure_escape_twice|:7:19: error: '[^']*' is captured by a closure that escapes, and is still used here" + "own_err_closure_escape_twice|:12:19: error: '[^']*' is captured by a closure that escapes, and is still used here" "own_err_closure_escape_param|:7:12: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's" "own_err_closure_escape_inherited|:9:21: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: it is captured from an enclosing function" - "own_err_closure_escape_loop|:11:23: error: '[^']*' is moved inside a loop but was made outside it" - "own_err_closure_escape_some_paths|:12:23: error: '[^']*' is moved here on some paths only" + "own_err_closure_escape_loop|:16:23: error: '[^']*' is moved inside a loop but was made outside it" + "own_err_closure_escape_some_paths|:17:23: error: '[^']*' is moved here on some paths only" "own_err_closure_outlives_cell|:13:11: error: '[^']*' borrows '[^']*', which it captures, but runs here after '[^']*' is released" "own_err_closure_copy_moved|:13:11: error: '[^']*' borrows '[^']*', which it captures, but runs here after '[^']*' is released" "own_err_closure_param_assigned|:9:5: error: '[^']*' is a captured parameter and cannot be assigned under -mm=own: its value is the caller's" @@ -4522,7 +4549,12 @@ set(own_error_cases "own_err_record_without_lends|:11:1: error: '@record' of 'pairOf' says its result is a borrowing record, but no '@lends' names what it borrows" "own_err_record_not_record|:7:1: error: '@record' of 'first' says its result is a record that borrows 'a', but its body returns a borrow of it as it is" "own_err_record_exported_unsaid|:12:1: error: 'pairOf' returns a record that borrows 'a', 'b', which another module can learn only from '@record' beside its '@lends'" - "own_err_value_export_borrowing|:13:1: error: 'wrap' returns a tuple that borrows 'n' and owns nothing, which -mm=own cannot tell another module yet") + "own_err_value_export_borrowing|:13:1: error: 'wrap' returns a tuple that borrows 'n' and owns nothing, which -mm=own cannot tell another module yet" + "own_err_keeper_unknown_value|:11:5: error: -mm=own cannot make the value kept in 'retained' immortal here: it is not made here, nor a parameter" + "own_err_keeper_exported|:7:5: error: 'Registry[.]register' keeps '#1' for good, but -mm=own cannot tell its callers in other modules. '@immortalizes' would say it in its signature" + "own_err_keeper_declared|:5:1: error: '@immortalizes' of 'keep' names 'a', but its body keeps for good 'b'" + "own_err_keeper_called_through_value|:6:1: error: 'keep' keeps '#0' for good, but -mm=own cannot make every caller make it immortal: the function is called through a value" + "own_err_keeper_popped|:14:9: error: argument '[^']*' is given to 'Registry[.]register', which keeps it, but -mm=own cannot move it here") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) @@ -5247,7 +5279,7 @@ set(stack_promotion_decision_tests "ctor_local|ctor_local\.ts:14:19: remark: stack-promotion: stack" "borrow_uses|borrow_uses\.ts:17:15: remark: stack-promotion: stack.*borrow_uses\.ts:18:15: remark: stack-promotion: stack" "pass_to_reader|pass_to_reader\.ts:18:19: remark: stack-promotion: stack" - "pass_to_keeper|pass_to_keeper\.ts:16:15: remark: stack-promotion: heap: argument" + "pass_to_keeper|pass_to_keeper\.ts:16:15: remark: stack-promotion: heap: (argument|kept for good)" "method_keeps_this|method_keeps_this\.ts:15:15: remark: stack-promotion: heap: argument" "virtual_one_keeps|virtual_one_keeps\.ts:26:18: remark: stack-promotion: heap: argument" "ctor_keeps_this|ctor_keeps_this\.ts:13:15: remark: stack-promotion: heap: argument" diff --git a/tslang/test/tester/own-facts-objects.cmake b/tslang/test/tester/own-facts-objects.cmake new file mode 100644 index 000000000..aae48f9c8 --- /dev/null +++ b/tslang/test/tester/own-facts-objects.cmake @@ -0,0 +1,70 @@ +# -mm=own across two modules compiled into objects of their own and linked into one program +# (docs/superpowers/specs/2026-10-25-own-facts-from-objects-design.md): own_facts_main.ts holds a +# borrow of a field across calls of own_facts_lib.ts's methods. Given the library's object with +# --own-facts it compiles, links and runs; without, the calls may destroy anything and the borrow is +# an error; and a call whose facts say it overwrites the borrowed place (own_facts_main_drops.ts) +# stays an error with them. + +cmake_minimum_required(VERSION 3.17.3) + +foreach(var TSLANG SOURCE_DIR WORK_DIR LLVM_LIB TSLANG_LIB) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "${var} is required") + endif() +endforeach() + +set(ENV{GC_LIB_PATH} "") +set(ENV{TSLANG_LIB_PATH} "") + +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") +# the importer finds `./own_facts_lib` beside it, as a source to read declarations from +foreach(file own_facts_lib.ts own_facts_main.ts own_facts_main_drops.ts) + file(COPY "${SOURCE_DIR}/${file}" DESTINATION "${WORK_DIR}") +endforeach() + +function(tslang_run what) + execute_process(COMMAND "${TSLANG}" ${ARGN} + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) + set(status "${status}" PARENT_SCOPE) + set(output "${out}${err}" PARENT_SCOPE) +endfunction() + +tslang_run(lib --emit=obj -mm=own own_facts_lib.ts -o own_facts_lib.obj) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_facts_lib: exit ${status}\n${output}") +endif() + +# without the library's facts: Cam.reset may destroy anything, the borrow of this.cam among it +tslang_run(blind --emit=obj -mm=own own_facts_main.ts -o own_facts_main_blind.obj) +if(status EQUAL 0 OR NOT output MATCHES "borrows a field but is used here after it may be released or overwritten") + message(FATAL_ERROR "own_facts_main without --own-facts compiled, or failed otherwise: exit ${status}\n${output}") +endif() + +tslang_run(main --emit=obj -mm=own --own-facts=own_facts_lib.obj own_facts_main.ts -o own_facts_main.obj) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_facts_main with --own-facts: exit ${status}\n${output}") +endif() + +tslang_run(drops --emit=obj -mm=own --own-facts=own_facts_lib.obj own_facts_main_drops.ts -o own_facts_main_drops.obj) +if(status EQUAL 0 OR NOT output MATCHES ":10:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten") + message(FATAL_ERROR "own_facts_main_drops compiled, or failed otherwise: exit ${status}\n${output}") +endif() + +tslang_run(link --emit=exe -mm=own "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" + --own-facts=own_facts_lib.obj --obj=own_facts_lib.obj own_facts_main.ts -o own_facts.exe) +if(NOT status EQUAL 0) + message(FATAL_ERROR "linking own_facts: exit ${status}\n${output}") +endif() + +execute_process(COMMAND "${WORK_DIR}/own_facts.exe" + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT "${out}" MATCHES "^11[\r\n]+done[.]") + message(FATAL_ERROR "own_facts.exe: exit ${status}\n${out}${err}") +endif() diff --git a/tslang/test/tester/own-keepers-objects.cmake b/tslang/test/tester/own-keepers-objects.cmake new file mode 100644 index 000000000..e048bddf3 --- /dev/null +++ b/tslang/test/tester/own-keepers-objects.cmake @@ -0,0 +1,54 @@ +# -mm=own's keepers across two modules compiled into objects of their own and linked into one program +# (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): own_keepers_lib.ts keeps the +# callbacks it is given for good, and says so with `@immortalizes`; own_keepers_main.ts registers a +# bound method and a closure from functions that return before the callbacks run. The importer reads +# the marker from the library's declaration and makes what it passes immortal, so the program runs +# with the right numbers after the memory its locals released is handed out again. + +cmake_minimum_required(VERSION 3.17.3) + +foreach(var TSLANG SOURCE_DIR WORK_DIR LLVM_LIB TSLANG_LIB) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "${var} is required") + endif() +endforeach() + +set(ENV{GC_LIB_PATH} "") +set(ENV{TSLANG_LIB_PATH} "") + +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") +# the importer finds `./own_keepers_lib` beside it, as a source to read declarations from +foreach(file own_keepers_lib.ts own_keepers_main.ts) + file(COPY "${SOURCE_DIR}/${file}" DESTINATION "${WORK_DIR}") +endforeach() + +function(tslang_run what) + execute_process(COMMAND "${TSLANG}" ${ARGN} + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) + set(status "${status}" PARENT_SCOPE) + set(output "${out}${err}" PARENT_SCOPE) +endfunction() + +tslang_run(lib --emit=obj -mm=own own_keepers_lib.ts -o own_keepers_lib.obj) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_keepers_lib: exit ${status}\n${output}") +endif() + +tslang_run(link --emit=exe -mm=own "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" + --own-facts=own_keepers_lib.obj --obj=own_keepers_lib.obj own_keepers_main.ts -o own_keepers.exe) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "linking own_keepers: exit ${status}\n${output}") +endif() + +execute_process(COMMAND "${WORK_DIR}/own_keepers.exe" + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT "${out}" MATCHES "^2 102 2[\r\n]+done[.]") + message(FATAL_ERROR "own_keepers.exe: exit ${status}\n${out}${err}") +endif() diff --git a/tslang/test/tester/own/own_err_closure_escape_loop.ts b/tslang/test/tester/own/own_err_closure_escape_loop.ts index 063a72905..e30b573d5 100644 --- a/tslang/test/tester/own/own_err_closure_escape_loop.ts +++ b/tslang/test/tester/own/own_err_closure_escape_loop.ts @@ -5,6 +5,11 @@ class C { let handlers: (() => number)[] = []; +// emptied, so no keeper: what it holds may be released (a keeper's would be immortal) +function reset() { + handlers.length = 0; +} + function register() { let a = new C(1); for (let i = 0; i < 3; i++) { diff --git a/tslang/test/tester/own/own_err_closure_escape_some_paths.ts b/tslang/test/tester/own/own_err_closure_escape_some_paths.ts index ecacec09c..7e64e4d19 100644 --- a/tslang/test/tester/own/own_err_closure_escape_some_paths.ts +++ b/tslang/test/tester/own/own_err_closure_escape_some_paths.ts @@ -6,6 +6,11 @@ class C { let handlers: (() => number)[] = []; +// emptied, so no keeper: what it holds may be released (a keeper's would be immortal) +function reset() { + handlers.length = 0; +} + function register(keep: boolean) { let a = new C(1); if (keep) { diff --git a/tslang/test/tester/own/own_err_closure_escape_twice.ts b/tslang/test/tester/own/own_err_closure_escape_twice.ts index fb0175a2d..b6f44f248 100644 --- a/tslang/test/tester/own/own_err_closure_escape_twice.ts +++ b/tslang/test/tester/own/own_err_closure_escape_twice.ts @@ -1,6 +1,11 @@ // -mm=own, phase 5b rejects: two closures that escape cannot both own `n`. let handlers: (() => number)[] = []; +// emptied, so no keeper: what it holds may be released (a keeper's would be immortal) +function reset() { + handlers.length = 0; +} + function register() { let n: number = 0; handlers.push(() => ++n); diff --git a/tslang/test/tester/own/own_err_keeper_called_through_value.ts b/tslang/test/tester/own/own_err_keeper_called_through_value.ts new file mode 100644 index 000000000..b28fd78f3 --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_called_through_value.ts @@ -0,0 +1,16 @@ +// A function that keeps a parameter for good, passed on as a function value: whoever calls it +// through that value would not know to make the argument immortal. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +function keep(h: Callback) { + retained.push(h); +} + +function apply(f: (h: Callback) => void) { + f((n: number) => {}); +} + +function main() { + apply(keep); +} diff --git a/tslang/test/tester/own/own_err_keeper_declared.ts b/tslang/test/tester/own/own_err_keeper_declared.ts new file mode 100644 index 000000000..f3e18da9d --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_declared.ts @@ -0,0 +1,12 @@ +// `@immortalizes` is checked against the body: it names 'a', but the body keeps 'b' for good. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +@immortalizes("a") +function keep(a: Callback, b: Callback) { + retained.push(b); +} + +function main() { + keep((n: number) => {}, (n: number) => {}); +} diff --git a/tslang/test/tester/own/own_err_keeper_exported.ts b/tslang/test/tester/own/own_err_keeper_exported.ts new file mode 100644 index 000000000..74f9cdfe4 --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_exported.ts @@ -0,0 +1,10 @@ +// A function another module may call that keeps a parameter for good has to say so: its callers in +// other modules make the argument immortal only if they know. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +export class Registry { + register(handler: Callback): void { + retained.push(handler); + } +} diff --git a/tslang/test/tester/own/own_err_keeper_popped.ts b/tslang/test/tester/own/own_err_keeper_popped.ts new file mode 100644 index 000000000..30fa5c68e --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_popped.ts @@ -0,0 +1,23 @@ +// An array an element is taken out of is no keeper: what it holds may be released, so the push is +// the move it always was, and a bound method of the caller's object cannot be given up. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +class Registry { + register(handler: Callback): void { + retained.push(handler); + } +} + +class Counter { + constructor(registry: Registry) { + registry.register(this.onTick); + } + + onTick(n: number): void {} +} + +function main() { + const c = new Counter(new Registry()); + retained.pop(); +} diff --git a/tslang/test/tester/own/own_err_keeper_unknown_value.ts b/tslang/test/tester/own/own_err_keeper_unknown_value.ts new file mode 100644 index 000000000..223010024 --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_unknown_value.ts @@ -0,0 +1,16 @@ +// A keeper's push of a value this function did not make and is no parameter of it - a field's +// function value - cannot be made immortal: only its maker knows what it relies on. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +class H { + cb: Callback = (n: number) => {}; +} + +function keep(h: H) { + retained.push(h.cb); +} + +function main() { + keep(new H()); +} diff --git a/tslang/test/tester/own/own_immortal_keepers.ts b/tslang/test/tester/own/own_immortal_keepers.ts new file mode 100644 index 000000000..d894ffc39 --- /dev/null +++ b/tslang/test/tester/own/own_immortal_keepers.ts @@ -0,0 +1,108 @@ +// A module-level array that is only ever pushed onto - a keeper - keeps what it holds to the end of +// the program, so under -mm=own a value pushed into it is made immortal where it is known what it +// relies on (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): a bound method's +// object, a closure's box and the cells it borrows, an object pushed directly. The owners' releases +// then free nothing, and the callbacks still run after the functions that registered them return +// and the memory they released is handed out again. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +class Registry { + register(handler: Callback): void { + retained.push(handler); + handler(0); // still the caller's to use after the push + } +} + +class Counter { + count: number[] = [0.0]; + constructor(registry: Registry) { + registry.register(this.onTick); // the object is main's, and kept for good + } + onTick(n: number): void { + this.count[0] += n; + } +} + +// a parameter passed on: the caller makes it immortal +function forward(r: Registry, h: Callback): void { + r.register(h); +} + +// said, as a function another module may call has to +@immortalizes("h") +export function forwardExported(h: Callback): void { + new Registry().register(h); +} + +class Node { + constructor(public v: number) {} +} + +let nodes: Node[] = []; + +let sums: number[] = [0.0, 0.0, 0.0, 0.0]; + +function setupBound(): Counter { + return new Counter(new Registry()); +} + +function setupClosure(): void { + const total = [100.0]; + new Registry().register((n: number) => { total[0] += n; sums[0] = total[0]; }); + total[0] += 1.0; // the frame still uses what the closure captured +} + +function setupForward(): void { + const box = [7.0]; + forward(new Registry(), (n: number) => { box[0] += n; sums[1] = box[0]; }); +} + +function setupExported(): void { + const box = [20.0]; + forwardExported((n: number) => { box[0] += n; sums[2] = box[0]; }); +} + +function setupNodes(): void { + nodes.push(new Node(5)); + const local = new Node(6); + nodes.push(local); // and still the local's + sums[3] = local.v; +} + +class Holder { + first: Callback; + constructor() { this.first = retained[0]; } // a keeper's element goes anywhere +} + +function churn(): number { + let sum = 0.0; + for (let i = 0; i < 20000; i++) { + const a = [i * 1.0, 2.0, 3.0]; + sum += a[0]; + } + return sum; +} + +function main() { + const counter = setupBound(); + setupClosure(); + setupForward(); + setupExported(); + setupNodes(); + churn(); + for (let k = 0; k < 3; k++) { + for (const cb of retained) { + cb(1); + } + + churn(); + } + + const holder = new Holder(); + holder.first(10); + print(counter.count[0], sums[0], sums[1], sums[2], nodes[0].v + nodes[1].v, retained.length); + assert(counter.count[0] == 13 && sums[0] == 104 && sums[1] == 10 && sums[2] == 23); + assert(nodes[0].v + nodes[1].v == 11 && sums[3] == 6 && retained.length == 4); + print("done."); +} diff --git a/tslang/test/tester/tests/00memory_model_constant.ts b/tslang/test/tester/tests/00memory_model_constant.ts new file mode 100644 index 000000000..ade1f2da3 --- /dev/null +++ b/tslang/test/tester/tests/00memory_model_constant.ts @@ -0,0 +1,62 @@ +// __MEMORY_MODEL__ is the memory model the module is compiled for, a string literal, and a compare of +// it with a literal is decided while the module is generated: the branch not taken is not there at +// all. So an API only one model has can be called under a test of the model, and a callback that +// only gc needs kept - Boehm cannot see a pointer C holds - is not kept under own, whose caller does +// not own the object the callback holds. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +// defined nowhere: a call of it that were generated would fail to link (or to resolve, in the JIT) +declare function definedNowhere(): void; + +class Registry { + register(handler: Callback): void { + if (__MEMORY_MODEL__ === "gc") { + retained.push(handler); + } + + handler(1); + } +} + +class Counter { + count: number[] = [0.0]; + + constructor(registry: Registry) { + registry.register(this.onTick); + } + + onTick(n: number): void { + this.count[0] += n; + } +} + +function main() { + if (__MEMORY_MODEL__ === "no such model") { + definedNowhere(); + } + + const model: string = __MEMORY_MODEL__; + assert(model == "gc" || model == "rc" || model == "own" || model == "none", "a memory model"); + assert(__MEMORY_MODEL__ !== "unknown", "a literal compare"); + + // the target's OS and architecture, as Node names them + const os: string = __OS__; + const arch: string = __ARCH__; + assert(os.length > 0 && arch.length > 0, "an OS and an architecture"); + if (__OS__ === "win32") { + assert(os == "win32", "the branch for this OS"); + } else { + assert(os != "win32", "the branch for another OS"); + } + + if (__ARCH__ === "x64" || __ARCH__ === "arm64") { + assert(sizeof() == 8, "a 64-bit target"); + } + + const counter = new Counter(new Registry()); + assert(counter.count[0] == 1, "the callback ran"); + assert((retained.length == 1) == (model == "gc"), "kept under gc only"); + print(model, retained.length); + print("done."); +} diff --git a/tslang/test/tester/tests/own_facts_lib.ts b/tslang/test/tester/tests/own_facts_lib.ts new file mode 100644 index 000000000..699c128a6 --- /dev/null +++ b/tslang/test/tester/tests/own_facts_lib.ts @@ -0,0 +1,30 @@ +// The library half of own-facts-objects.cmake: compiled into an object of its own under -mm=own, +// whose __tsownfacts_ says what its exported functions destroy (SHARED_LIB_OWN_OBJECT_FACTS). +// Cam.reset overwrites only its own `position`; Cam.size destroys nothing; replaceCam overwrites +// a Holder's `cam`, the place an importer's borrow is read from in own_facts_main_drops.ts. +@final +export class Cam { + position: number[] = [0.0, 0.0]; + + reset(x: number): void { + this.position = [x, x + 1.0]; + } + + size(): number { + return this.position.length; + } +} + +export class Holder { + cam: Cam = new Cam(); +} + +export function replaceCam(h: Holder): void { + h.cam = new Cam(); +} + +// returns an array its caller owns, borrowing neither argument: the facts say so (`fresh`), and an +// importer may store it over the place it read `a` from +export function shifted(a: number[], d: number): number[] { + return [a[0] + d, a[1] + d]; +} diff --git a/tslang/test/tester/tests/own_facts_main.ts b/tslang/test/tester/tests/own_facts_main.ts new file mode 100644 index 000000000..5da82347a --- /dev/null +++ b/tslang/test/tester/tests/own_facts_main.ts @@ -0,0 +1,36 @@ +// The program half of own-facts-objects.cmake: a borrow of `this.cam` held across calls of +// another module's methods. With --own-facts= -mm=own knows Cam.reset +// overwrites only a Cam's `position` and Cam.size nothing, so the borrow survives both; without it +// either call may destroy anything, and the borrow is an error. `shifted`'s result is fresh, so it +// may replace the array it was given. +import { Cam, shifted } from "./own_facts_lib"; + +function churn() { + const keep: Cam[] = []; + for (let i = 0; i < 2000; i++) { + const c = new Cam(); + c.reset(77777.0); + keep.push(c); + } + + return keep.length; +} + +class Pass { + private cam: Cam = new Cam(); + private offset: number[] = [1.0, 5.0]; + + run(): number { + this.cam.reset(3.0); + churn(); + this.offset = shifted(this.offset, 1.0); + churn(); + return this.cam.position[0] + this.cam.position[1] + this.cam.size() + this.offset[0]; + } +} + +function main() { + const p = new Pass(); + print(p.run()); // 11 + print("done."); +} diff --git a/tslang/test/tester/tests/own_facts_main_drops.ts b/tslang/test/tester/tests/own_facts_main_drops.ts new file mode 100644 index 000000000..64e1e2685 --- /dev/null +++ b/tslang/test/tester/tests/own_facts_main_drops.ts @@ -0,0 +1,11 @@ +// own-facts-objects.cmake, the negative: replaceCam, another module's function, overwrites the +// Holder's `cam` its caller's borrow was read from. Its facts (--own-facts) say so, and the borrow +// used after the call is still an error. +import { Cam, Holder, replaceCam } from "./own_facts_lib"; + +function main() { + const h = new Holder(); + const c = h.cam; + replaceCam(h); + print(c.size()); +} diff --git a/tslang/test/tester/tests/own_keepers_lib.ts b/tslang/test/tester/tests/own_keepers_lib.ts new file mode 100644 index 000000000..d43619b2d --- /dev/null +++ b/tslang/test/tester/tests/own_keepers_lib.ts @@ -0,0 +1,17 @@ +// The library half of own-keepers-objects.cmake: a keeper - an array only ever pushed onto - and the +// function that keeps a callback in it for good. Another module calls it, so it says so with +// `@immortalizes`, and each caller makes what it passes immortal. +let retained: ((n: number) => void)[] = []; + +@immortalizes("handler") +export function register(handler: (n: number) => void): void { + retained.push(handler); +} + +export function runAll(n: number): number { + for (const cb of retained) { + cb(n); + } + + return retained.length; +} diff --git a/tslang/test/tester/tests/own_keepers_main.ts b/tslang/test/tester/tests/own_keepers_main.ts new file mode 100644 index 000000000..150686bb8 --- /dev/null +++ b/tslang/test/tester/tests/own_keepers_main.ts @@ -0,0 +1,50 @@ +// The program half of own-keepers-objects.cmake: it registers a bound method of an object and a +// closure over a local with another module's `register`, which keeps them for good, from functions +// that return before they run. Reading the declaration's `@immortalizes`, -mm=own makes the object, +// the box and the cell immortal here, so they outlive their owners' releases. +import { register, runAll } from "./own_keepers_lib"; + +let results: number[] = [0.0, 0.0]; + +class Counter { + count: number[] = [0.0]; + + constructor() { + register(this.onTick); + } + + onTick(n: number): void { + this.count[0] += n; + results[0] = this.count[0]; + } +} + +function setupBound(): void { + const c = new Counter(); +} + +function setupClosure(): void { + const total = [100.0]; + register((n: number) => { total[0] += n; results[1] = total[0]; }); +} + +function churn(): number { + let sum = 0.0; + for (let i = 0; i < 20000; i++) { + const a = [i * 1.0, 2.0]; + sum += a[0]; + } + + return sum; +} + +function main() { + setupBound(); + setupClosure(); + churn(); + runAll(1); + churn(); + const kept = runAll(1); + print(results[0], results[1], kept); // 2 102 2 + print("done."); +} diff --git a/tslang/tslang/borrowfacts.cpp b/tslang/tslang/borrowfacts.cpp index 592b40f9f..f70ba1244 100644 --- a/tslang/tslang/borrowfacts.cpp +++ b/tslang/tslang/borrowfacts.cpp @@ -27,6 +27,7 @@ namespace cl = llvm::cl; extern cl::opt emitAction; extern cl::list libs; extern cl::list objs; +extern cl::list ownFacts; llvm::Triple getLinkTargetTriple(); std::string getTargetStaticLibName(llvm::StringRef); @@ -169,3 +170,41 @@ void readBorrowFacts(CompileOptions &compileOptions) appendBorrowFacts(compileOptions, files, std::vector(objs.begin(), objs.end())); } + +// Called before the module is compiled: the ownership signature pass reads them (MLIRGen puts +// them on the module). Only under own, and only from the files --own-facts names: the objects of +// the modules this one imports, which the build links with it - so, like a library's borrow facts, +// they describe the code that runs. A file that is missing or holds none gives no facts. +void readOwnFacts(CompileOptions &compileOptions) +{ + if (compileOptions.memoryModel != MemoryModelOwn) + { + return; + } + + // and the default library's: its own build is the one every own program links (statically: its + // DLL, which a program may load another copy of, is never read), so `Math.abs` is a call of a + // function whose facts are known + std::vector files(ownFacts.begin(), ownFacts.end()); + if (!compileOptions.noDefaultLib && emitAction != Action::RunJIT) + { + files.push_back(getDefaultLibBinary(/*shared=*/false, compileOptions, getLinkTargetTriple())); + } + + for (auto &file : files) + { + if (!llvm::sys::fs::is_regular_file(file) || !isStaticLinkInput(file)) + { + continue; + } + + for (auto &[symbol, text] : Dump::readCStringSymbols(file, SHARED_LIB_OWN_OBJECT_FACTS)) + { + compileOptions.importedOwnFacts += text; + if (!text.empty() && text.back() != '\n') + { + compileOptions.importedOwnFacts += "\n"; + } + } + } +} diff --git a/tslang/tslang/transform.cpp b/tslang/tslang/transform.cpp index 58d71398d..56aef0206 100644 --- a/tslang/tslang/transform.cpp +++ b/tslang/tslang/transform.cpp @@ -147,11 +147,27 @@ int runMLIRPasses(mlir::MLIRContext &context, llvm::SourceMgr &sourceMgr, mlir:: // Under own, after the verifier: the verifier pairs rc's acquisitions with their // releases, and inference erases the acquisitions it proves are the one owner's. Inference // either erases a retain or reports it, and a program it reports stops here. + // Named after the module's own file, the main buffer, not inputFilename, so a symbol is + // never another module's. + llvm::StringRef moduleFile = inputFilename; + if (sourceMgr.getNumBuffers() > 0 && inputFilename != "-") + { + moduleFile = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID())->getBufferIdentifier(); + } + + // Nothing links the object of a JIT-run program, nor those the JIT cache compiles beside + // it: they are only loaded into the JIT. + auto linkedByOthers = !compileOptions.isJit && !compileOptions.jitCache; + if (compileOptions.memoryModel == MemoryModelOwn && !ownSkipInference) { // a program's exports are seen by no other module (own spec 31): an executable, or the - // module the JIT enters (a module the JIT cache compiles beside it has isJit off) - pm.addPass(mlir::typescript::createOwnershipSignaturePass(compileOptions.isExecutable || compileOptions.isJit)); + // module the JIT enters (a module the JIT cache compiles beside it has isJit off). What + // its object tells a module linking it is written whatever it exports: a static + // library is compiled with --export=none. + pm.addPass(mlir::typescript::createOwnershipSignaturePass( + compileOptions.isExecutable || compileOptions.isJit, + linkedByOthers ? SHARED_LIB_OWN_OBJECT_FACTS + typescript::moduleSymbolSuffix(moduleFile) : "")); pm.nest().addPass(mlir::typescript::createOwnershipInferencePass()); // an `await`'s continuation and a `for await` body, outlined by the async lowering pm.nest().addPass(mlir::typescript::createOwnershipInferencePass()); @@ -161,16 +177,9 @@ int runMLIRPasses(mlir::MLIRContext &context, llvm::SourceMgr &sourceMgr, mlir:: // anything itself. Nothing imports a JIT-run program, nor the modules the JIT cache // compiles beside it (isJit off, jitCache on): their objects are only loaded into the // JIT, never linked, and the program run there does not read facts from them - // (StackPromotionPass). Named after the module's own file, the main buffer, not - // inputFilename, so a symbol is never another module's. - if (!compileOptions.isJit && !compileOptions.jitCache && !noBorrowFactsExport) + // (StackPromotionPass). + if (linkedByOthers && !noBorrowFactsExport) { - llvm::StringRef moduleFile = inputFilename; - if (sourceMgr.getNumBuffers() > 0 && inputFilename != "-") - { - moduleFile = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID())->getBufferIdentifier(); - } - pm.addPass(mlir::typescript::createBorrowFactsExportPass( SHARED_LIB_BORROW_FACTS + typescript::moduleSymbolSuffix(moduleFile))); } diff --git a/tslang/tslang/tslang.cpp b/tslang/tslang/tslang.cpp index 32718d912..9eea2095c 100644 --- a/tslang/tslang/tslang.cpp +++ b/tslang/tslang/tslang.cpp @@ -59,6 +59,7 @@ namespace Dump CompileOptions prepareOptions(); void readBorrowFacts(CompileOptions &); +void readOwnFacts(CompileOptions &); std::string getDefaultOutputFileName(enum Action); std::string getDefaultExt(enum Action); std::string getDefaultLibPath(); @@ -171,6 +172,7 @@ cl::opt emsdksysrootpath("emsdk-sysroot-path", cl::desc("TypeScript cl::opt androidndkpath("android-ndk-path", cl::desc("Android NDK path, the directory holding 'toolchains/llvm/prebuilt', or ANDROID_NDK_HOME environmental variable. (used when '-mtriple=-linux-android')"), cl::value_desc("androidndkpath"), cl::cat(TypeScriptCompilerBuildCategory)); cl::list libs{"lib", cl::desc("Libraries to link statically. (used in --emit=exe)"), cl::ZeroOrMore, cl::MiscFlags::CommaSeparated, cl::cat(TypeScriptCompilerBuildCategory)}; cl::list objs{"obj", cl::desc("Object files to link statically. (used in --emit=exe and --emit=dll)"), cl::ZeroOrMore, cl::MiscFlags::CommaSeparated, cl::cat(TypeScriptCompilerBuildCategory)}; +cl::list ownFacts{"own-facts", cl::desc("Objects (or static libraries) of the modules this one imports, compiled under -mm=own and linked with it: their ownership facts are trusted for calls into them. (used with -mm=own)"), cl::ZeroOrMore, cl::MiscFlags::CommaSeparated, cl::cat(TypeScriptCompilerBuildCategory)}; cl::opt noDefaultLib("no-default-lib", cl::desc("Disable loading default lib"), cl::init(false), cl::cat(TypeScriptCompilerCategory)); cl::opt enableBuiltins("builtins", cl::desc("Builtin functionality (needed if Default lib is not provided)"), cl::init(true), cl::cat(TypeScriptCompilerCategory)); @@ -515,6 +517,7 @@ int main(int argc, char **argv) } readBorrowFacts(compileOptions); + readOwnFacts(compileOptions); // what --jit-native links is the objects the cache keeps if (emitAction == Action::RunJIT && jitNative && !compileOptions.jitCache)