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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ Template for new versions:

## Misc Improvements
- Core: docs files generated by previous builds are now cleaned up automatically, so switching branches no longer breaks the build with missing-file errors
- Core: performance tweaks in Lua identity handling: memoize last virtual identity lookup to provide a fast path for homogeneous loads; leverage the registry index's bidirectionality to speed metatable discovery; add a cache for identity to metatable lookups to enable userdata reuse
- `tailor`: clothing needs are now computed from each unit's body plan instead of a fixed armor/pants/shoes list: dwarves get two shoes, units with any number of stance parts get appropriately many pairs of shoes, and helmets, gloves, and unusually-shaped citizens are covered too. Clothing types are chosen to maximize body coverage using their UBSTEP/LBSTEP/UPSTEP reach
- `tailor`: pending manager orders now count toward clothing needs, so repeating ``tailor now`` no longer creates additional orders in other materials for needs that are already covered by an outstanding order

Expand Down
46 changes: 40 additions & 6 deletions library/DataDefs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ distribution.
#include <vector>
#include <map>
#include <mutex>
#include <atomic>
#include <cstdint>

#include "MemAccess.h"
#include "Core.h"
Expand Down Expand Up @@ -148,6 +150,11 @@ bool compound_identity::is_equivalent(const compound_identity* other) const

static std::mutex *known_mutex = NULL;

// Bumped whenever an entry is removed from virtual_identity::known, so
// that the per-thread memo in virtual_identity::find(void*) below can't
// hand out a stale identity pointer.
static std::atomic<uint64_t> known_erase_generation{0};

void compound_identity::Init(Core *core)
{
if (!known_mutex)
Expand Down Expand Up @@ -314,13 +321,16 @@ decltype(virtual_identity::interpose_list_map) virtual_identity::interpose_list_

void virtual_identity::ensure_virtual_identity_init()
{
static std::once_flag virtual_identity_init_flag;
std::call_once(virtual_identity_init_flag, []() {
// Magic static: on the steady-state path this is just a guard check,
// cheaper than std::call_once on this hot path.
static bool initialized = []() {
name_lookup = new (std::remove_pointer<decltype(name_lookup)>::type)();
known = new (std::remove_pointer<decltype(known)>::type)();
vtable_ptr_map = new (std::remove_pointer<decltype(vtable_ptr_map)>::type)();
interpose_list_map = new (std::remove_pointer<decltype(interpose_list_map)>::type)();
});
return true;
}();
(void)initialized;
}

virtual_identity::virtual_identity(size_t size, const TAllocateFn alloc,
Expand Down Expand Up @@ -350,10 +360,16 @@ virtual_identity::~virtual_identity()
// Remove global lookup table entries if we're from a plugin
if (is_plugin)
{
(*name_lookup).erase(getOriginalName());
if (known_mutex)
{
std::lock_guard<std::mutex> lock(*known_mutex);
(*name_lookup).erase(getOriginalName());

if (vtable_ptr())
(*known).erase(vtable_ptr());
}

if (vtable_ptr())
(*known).erase(vtable_ptr());
known_erase_generation.fetch_add(1, std::memory_order_relaxed);
}
}

Expand Down Expand Up @@ -391,6 +407,21 @@ const virtual_identity *virtual_identity::find(void *vtable)
if (!vtable || !known_mutex)
return nullptr;

// Bulk materialization (e.g. vectors of homogeneous df objects)
// repeats the same vtable lookup; memoize the last hit per thread
// and skip the map lock entirely. `known` is only appended to after
// init except that plugin identities are removed by the destructor
// above, so the memo is validated by a generation counter.
static thread_local struct {
void *vtable;
const virtual_identity *identity;
uint64_t generation;
} last_hit = { nullptr, nullptr, 0 };

uint64_t gen = known_erase_generation.load(std::memory_order_relaxed);
if (vtable == last_hit.vtable && gen == last_hit.generation)
return last_hit.identity;

ensure_virtual_identity_init();

// Actually, a reader/writer lock would be sufficient,
Expand All @@ -399,7 +430,10 @@ const virtual_identity *virtual_identity::find(void *vtable)

auto it = (*known).find(vtable);
if (it != (*known).end())
{
last_hit = { vtable, it->second, gen };
return it->second;
}

// If using a reader/writer lock, re-grab as write here, and recheck
Core &core = Core::getInstance();
Expand Down
24 changes: 22 additions & 2 deletions library/LuaTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,9 @@ static void field_reference(lua_State *state, const struct_field_info *field, vo
{
case struct_field_info::PRIMITIVE:
case struct_field_info::SUBSTRUCT:
push_object_internal(state, field->type, ptr);
// Field refs are mutated below, so they must not come from
// the shared ref cache.
push_object_internal(state, field->type, ptr, true, false);
get_object_ref_header(state, -1)->field_info = field;
return;

Expand Down Expand Up @@ -565,6 +567,14 @@ static int meta_struct_index(lua_State *state)
auto struct_type = (struct_identity*)get_object_identity(state, 1, "read", false);
if (auto tag_field = find_union_tag(struct_type, field))
{
// The produced ref may be shared via the ref cache; union
// tag data is stored per-ref, so substitute a private copy
// before tagging it.
if (lua_isuserdata(state, -1) && lua_getmetatable(state, -1))
{
push_object_ref(state, get_object_ref(state, -2));
lua_replace(state, -2);
}
get_object_ref_header(state, -1)->tag_ptr = ptr + tag_field->offset;
get_object_ref_header(state, -1)->tag_identity = tag_field->type;
get_object_ref_header(state, -1)->tag_attr = field->extra ? field->extra->union_tag_attr : nullptr;
Expand Down Expand Up @@ -857,7 +867,17 @@ static void attach_container_item_tagged_union(lua_State *state, int container,

auto tag_container = (container_identity*)header->tag_identity;

auto ref = get_object_ref_header(state, item);
// The element ref may be shared via the ref cache; union tags
// are stored per-ref, so substitute a private copy before
// tagging it.
int aitem = lua_absindex(state, item);
if (lua_isuserdata(state, aitem) && lua_getmetatable(state, aitem))
{
push_object_ref(state, get_object_ref(state, aitem));
lua_replace(state, aitem);
}

auto ref = get_object_ref_header(state, aitem);

// on both msvc and gcc, vectors have the same memory layout
auto item_type = tag_container->getItemType();
Expand Down
193 changes: 185 additions & 8 deletions library/LuaWrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ void LuaWrapper::SaveTypeInfo(lua_State *state, void *node)

static void BuildTypeMetatable(lua_State *state, const type_identity *type);

/*
* Address of this object is used as a unique key: metatable[key] holds
* the ref cache for the type, a weak-valued table mapping object
* pointer -> canonical ref userdata. Using a lightuserdata field keeps
* the cache invisible to table enumeration.
*/
static char refcache_field_key;

/**
* Push the pointer as DF object ref using metatable on the stack.
*/
Expand Down Expand Up @@ -203,10 +211,28 @@ void *LuaWrapper::get_object_ref(lua_State *state, int val_index)
return get_object_ref_header(state, val_index)->ptr;
}

/**
* Push the pointer using given identity.
/*
* Expects a type metatable on the stack top; pushes its ref cache
* table, creating it on first use. Result: [meta, cache].
*/
void LuaWrapper::push_object_internal(lua_State *state, const type_identity *type, void *ptr, bool in_method)
static void push_ref_cache(lua_State *state)
{
lua_rawgetp(state, -1, &refcache_field_key); // -> cache
if (lua_istable(state, -1))
return;

lua_pop(state, 1); // [meta]

lua_createtable(state, 0, 0); // [meta, cache]
lua_createtable(state, 0, 1); // [meta, cache, weakmeta]
lua_pushliteral(state, "v");
lua_setfield(state, -2, "__mode");
lua_setmetatable(state, -2); // [meta, cache]
lua_pushvalue(state, -1);
lua_rawsetp(state, -3, &refcache_field_key); // [meta, cache]
}

void LuaWrapper::push_object_internal(lua_State *state, const type_identity *type, void *ptr, bool in_method, bool cacheable)
{
/*
* If NULL pointer or no type, push something simple
Expand Down Expand Up @@ -234,15 +260,166 @@ void LuaWrapper::push_object_internal(lua_State *state, const type_identity *typ
}

/*
* Resolve metatable by identity, and push the object
* Resolve metatable by identity, and push the object.
*
* Fast path: identity -> metatable mappings are mirrored directly
* in the registry under the identity pointer, so a single rawgetp
* suffices for types that have been pushed before (this is the
* common case for e.g. bulk vector materialization).
*/

lua_pushlightuserdata(state, const_cast<type_identity*>(type)); // () -> type
lua_rawgetp(state, LUA_REGISTRYINDEX, type);
if (lua_isnil(state, -1))
{
lua_pop(state, 1);

lua_pushlightuserdata(state, const_cast<type_identity*>(type)); // () -> type

if (!LookupTypeInfo(state, in_method)) // type -> metatable?
BuildTypeMetatable(state, type); // () -> metatable

lua_pushlightuserdata(state, const_cast<type_identity*>(type));
lua_pushvalue(state, -2);
lua_rawset(state, LUA_REGISTRYINDEX); // registry[type] = metatable
}

// stack: [metatable]

if (!cacheable)
{
push_object_ref(state, ptr); // metatable -> userdata
return;
}

/*
* Probe the metatable's ref cache for a canonical ref for this
* pointer. Cached refs are shared: field refs and union-tagged
* refs carry per-reference metadata in their DFRefHeader, so code
* paths that write those fields must either pass cacheable=false
* above or substitute a private ref before mutating.
*/
push_ref_cache(state); // [meta, cache]

lua_pushlightuserdata(state, ptr);
lua_rawget(state, -2); // [meta, cache, ref|nil]

if (lua_isuserdata(state, -1))
{
lua_remove(state, -2); // [meta, ref]
lua_remove(state, -2); // [ref]
return;
}

lua_pop(state, 1); // [meta, cache]

// Create the ref and publish it.
lua_swap(state); // [cache, meta]
push_object_ref(state, ptr); // [cache, ref]
lua_pushlightuserdata(state, ptr); // [cache, ref, ptr]
lua_pushvalue(state, -2); // [cache, ref, ptr, ref]
lua_rawset(state, -4); // cache[ptr] = ref -> [cache, ref]
lua_remove(state, -2); // [ref]
}

/**
* Metatable lookup shared by the vector push slow path.
*/
static void push_metatable_for(lua_State *state, const type_identity *type)
{
lua_rawgetp(state, LUA_REGISTRYINDEX, type);
if (lua_isnil(state, -1))
{
lua_pop(state, 1);

lua_pushlightuserdata(state, const_cast<type_identity*>(type));

if (!LookupTypeInfo(state, false)) // type -> metatable?
BuildTypeMetatable(state, type); // () -> metatable

lua_pushlightuserdata(state, const_cast<type_identity*>(type));
lua_pushvalue(state, -2);
lua_rawset(state, LUA_REGISTRYINDEX); // registry[type] = metatable
}
}

void LuaWrapper::push_object_vector(lua_State *state, const type_identity *type, void *const *items, size_t count, bool addn)
{
lua_createtable(state, (int)count, addn ? 1 : 0);
if (addn)
{
lua_pushinteger(state, (lua_Integer)count);
lua_setfield(state, -2, "n");
}

int result = lua_gettop(state);

// Pinned slots for the current identity's metatable and ref cache,
// refreshed whenever the resolved element identity changes.
lua_pushnil(state); // result+1: metatable
lua_pushnil(state); // result+2: ref cache
int meta_slot = result + 1, cache_slot = result + 2;

const type_identity *cur = NULL;
bool is_class = type && type->type() == IDTYPE_CLASS;

for (size_t i = 0; i < count; i++)
{
void *ptr = items[i];
if (!ptr)
{
lua_pushnil(state);
lua_rawseti(state, result, (lua_Integer)(i + 1));
continue;
}

if (!LookupTypeInfo(state, in_method)) // type -> metatable?
BuildTypeMetatable(state, type); // () -> metatable
const type_identity *id = type;
if (is_class)
{
if (const virtual_identity *vid = virtual_identity::get(virtual_ptr(ptr)))
id = vid;
}

if (!id)
{
lua_pushlightuserdata(state, ptr);
lua_rawseti(state, result, (lua_Integer)(i + 1));
continue;
}

if (id != cur)
{
cur = id;

push_metatable_for(state, id);
lua_replace(state, meta_slot);

lua_pushvalue(state, meta_slot);
push_ref_cache(state); // [meta, cache]
lua_replace(state, cache_slot); // pin cache -> [meta]
lua_pop(state, 1);
}

lua_pushlightuserdata(state, ptr);
lua_rawget(state, cache_slot); // -> ref|nil

if (lua_isuserdata(state, -1))
{
lua_rawseti(state, result, (lua_Integer)(i + 1));
continue;
}

lua_pop(state, 1);

// Create the ref and publish it.
lua_pushvalue(state, meta_slot);
push_object_ref(state, ptr); // [ref]
lua_pushlightuserdata(state, ptr);
lua_pushvalue(state, -2);
lua_rawset(state, cache_slot); // cache[ptr] = ref -> [ref]
lua_rawseti(state, result, (lua_Integer)(i + 1));
}

push_object_ref(state, ptr); // metatable -> userdata
lua_pop(state, 2); // pinned slots
}

static void fetch_container_details(lua_State *state, int meta, const type_identity **pitem, int *pcount)
Expand Down
10 changes: 10 additions & 0 deletions library/include/LuaTools.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ distribution.
#include "ColorText.h"
#include "DataDefs.h"
#include "DataIdentity.h"
#include "LuaWrapper.h"

#include "df/coord.h"
#include "df/coord2d.h"
Expand Down Expand Up @@ -421,6 +422,15 @@ namespace DFHack::Lua {
}
}

// Fast path for vectors of df objects: hoists identity/metatable/ref-cache
// lookups out of the element loop (see LuaWrapper::push_object_vector).
template<df_object T>
void PushVector(lua_State *state, const std::vector<T*> &pvec, bool addn = false)
{
LuaWrapper::push_object_vector(state, df::identity_traits<T>::get(),
reinterpret_cast<void* const*>(pvec.data()), pvec.size(), addn);
}

template<typename T>
void Push(lua_State *state, const std::vector<T> &vec) {
PushVector(state, vec);
Expand Down
Loading
Loading