From cdb40c37f9f9a89d146ccc7526f399eea5659cbf Mon Sep 17 00:00:00 2001 From: kotijekriv Date: Thu, 12 Nov 2026 18:47:16 +0100 Subject: [PATCH 1/4] cmake: function-visibility.txt, which callers must see which callees' bodies One entry per caller, with the callees whose bodies it must see when it is compiled, fully qualified as the definitions are written: OpenSHC::funcA OpenSHC::funcB 87 entries, 127 edges, sorted by the caller's address. Every edge is a tu_merge.py measurement: pasting the callee into the caller's unit raises the caller's quick_diff ratio, and for callers with several callees a leave-one-out over the full set decided which are needed together. In all 127 the callee is at a lower address than its caller. Twelve measured gains are left out because they cannot be same-file edges: in seven the callee is at a higher address than its caller, and the other five would put a callee into a unit with callers that measure worse when they see it. 23 names are not on main yet. 22 are Map::Units Update callers: they were measured on our local branches reimpl/units-B-development and reimpl/units-A-development (UpdateCamel is also on the local reimpl/units-B-round2-100), and gynt's reimpl/map-units-updatefunctions has drafts of all 22. The 23rd is UnitsState::changeDestinationByAmount from #378. A generator skips names it cannot find. The measurements are in the PR description. Co-authored-by: Gynt Co-Authored-By: Claude Opus 5.5 --- cmake/function-visibility.txt | 214 ++++++++++++++++++++++++++++++++++ 1 file changed, 214 insertions(+) create mode 100644 cmake/function-visibility.txt diff --git a/cmake/function-visibility.txt b/cmake/function-visibility.txt new file mode 100644 index 0000000000..3368e445da --- /dev/null +++ b/cmake/function-visibility.txt @@ -0,0 +1,214 @@ +OpenSHC::Map::Buildings::BuildingsState::getSpriteID2 + OpenSHC::Map::Buildings::BuildingsState::convertCommandBuildingTypeToBuildingType +OpenSHC::Map::Buildings::BuildingsState::getStorageBuildingForResourceTypeAndAmount + OpenSHC::Map::Buildings::BuildingsState::getBuildingStorageTypeForResourceType +OpenSHC::Map::Buildings::BuildingsState::getResourceSpace + OpenSHC::Map::Buildings::BuildingsState::getResourceCountThatCanBeDeposited + OpenSHC::Map::Buildings::BuildingsState::getBuildingStorageTypeForResourceType +OpenSHC::Map::Buildings::BuildingsState::getBuildingCost + OpenSHC::Map::Buildings::BuildingsState::convertCommandBuildingTypeToBuildingType +OpenSHC::Map::Buildings::BuildingsState::updateNeededEmployeeCount + OpenSHC::Map::Buildings::BuildingsState::hasWorker +OpenSHC::Map::Buildings::BuildingsState::canUnitReachBuildingPerimeter + OpenSHC::Map::Buildings::BuildingsState::getBuildingHeightForBuildingID +OpenSHC::Map::Buildings::UpdateFletchersWorkshop + OpenSHC::Map::Buildings::BuildingsState::updateVisuallyActiveState +OpenSHC::Map::Buildings::UpdateBlacksmithsWorkshop + OpenSHC::Map::Buildings::BuildingsState::updateVisuallyActiveState +OpenSHC::Map::Buildings::UpdatePoleturnersWorkshop + OpenSHC::Map::Buildings::BuildingsState::updateVisuallyActiveState +OpenSHC::Map::Buildings::UpdateArmorersWorkshop + OpenSHC::Map::Buildings::BuildingsState::updateVisuallyActiveState +OpenSHC::Map::Buildings::UpdateBakery + OpenSHC::Map::Buildings::BuildingsState::updateVisuallyActiveState +OpenSHC::Map::Buildings::UpdateInn + OpenSHC::Map::Buildings::BuildingsState::updateVisuallyActiveState +OpenSHC::Map::Buildings::UpdateStables + OpenSHC::Map::Buildings::BuildingsState::validateBuildingTetheredUnits +OpenSHC::Map::Buildings::UpdateBadBuildingGallows + OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter +OpenSHC::Map::Buildings::UpdateBadBuildingGibbet + OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter +OpenSHC::Map::Buildings::UpdateBadBuildingDungeon + OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter +OpenSHC::Map::Buildings::UpdateBadBuildingStretchingRack + OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter +OpenSHC::Map::Buildings::BuildingsState::hasBuildingAsNeighbour + OpenSHC::Map::Buildings::BuildingsState::setupBuildingEntrancesOffset +OpenSHC::Map::Buildings::BuildingsState::findParticularBuilding + OpenSHC::Map::Buildings::BuildingsState::setupBuildingEntrancesOffset +OpenSHC::Map::Buildings::BuildingsState::findAccessibleAreaNearBuildingLocation + OpenSHC::Map::Buildings::BuildingsState::setupBuildingEntrancesOffset +OpenSHC::Map::Buildings::BuildingsState::addResourceToStockpile + OpenSHC::Map::Buildings::BuildingsState::extendResourceCountdownForPlayerBuildingsOfType +OpenSHC::Map::Buildings::BuildingsState::addResourceToGranary + OpenSHC::Map::Buildings::BuildingsState::getResourceCountThatCanBeDeposited +OpenSHC::Map::Buildings::BuildingsState::addResourceToArmory + OpenSHC::Map::Buildings::BuildingsState::getArmoryIDIfSpaceLeft +OpenSHC::Map::Buildings::BuildingsState::processResourceLoss + OpenSHC::Map::Buildings::BuildingsState::getBuildingStorageTypeForResourceType +OpenSHC::Map::Buildings::UpdateIronMine + OpenSHC::Map::Buildings::BuildingsState::getBuildingResourceAmountByUid +OpenSHC::Map::Buildings::BuildingsState::destroyBuildingAndLinkedDuplicates + OpenSHC::Map::Buildings::BuildingsState::destroySignpostData +OpenSHC::Map::Buildings::BuildingsState::buildingIsAccessible + OpenSHC::Map::Buildings::BuildingsState::getBuildingHeightForBuildingID +OpenSHC::UI::MenuItems::BuildMenu::MenuItemActionHandler_BuildMenu_UnitActionButtons + OpenSHC::UI::Helpers::SetTribesPatrolButtonPressed +OpenSHC::UI::Rendering::TextureRenderCore::renderInterfaceOrBuildingOccupationArea + OpenSHC::UI::Rendering::InitBlendFilterArraysUnk +OpenSHC::UI::Rendering::TextureRenderCore::renderGmWithPreparedAlphaMask + OpenSHC::UI::Rendering::InitBlendFilterArraysUnk +OpenSHC::UI::Rendering::TextureRenderCore::transformTilesetToRGB565 + OpenSHC::UI::Rendering::TextureRenderCore::transformTileObjectToRGB565 +OpenSHC::Game::GameStateStructures::clearEnemyRelatedStructures + OpenSHC::Game::GameStateStructures::setVariousGameStateToInitialValues +OpenSHC::Game::GameStateStructures::getSalesPrice + OpenSHC::Game::GameStateStructures::getSellResourceAmount +OpenSHC::UI::MenuItems::General::MenuItemRenderFunction_General_RenderCurrentButtonWithPossibleAlphaTexOnScreenMenuSurface + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::Rendering::RenderCurrentNotActiveButtonWithPossibleAlphaTexOnCurrentSurfaceUnk + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::Rendering::RenderButtonImageWithBlending + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::ChooseRandomNumberOfEnemies::MenuItemRenderFunction_ChooseRandomNumberOfEnemies_Main + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::Rendering::RenderCurrentButtonOnScreenMenu + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::Rendering::RenderCurrentButtonToScreenMenuWithBlendingUnk + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::MapEditorLandscaping::MenuItemRenderFunction_MapEditorLandscaping_GeneralButtons + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_BarracksWeaponAvailability + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_WorkshopWeaponSelection + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_DrawbridgeOpenClose + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_GatehouseOpenClose + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_GeneralButtonRender + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_SelectBuySellGoods + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemActionHandler_BuildingAndStatusMenu_BarrackUnitPortraits + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_MercenaryPostPortraits + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_EngineerAndMonkPortraits + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::UI::MenuItems::BuildingAndStatusMenu::MenuItemRenderFunction_BuildingAndStatusMenu_TunnelerPortrait + OpenSHC::UI::Rendering::ButtonGmData::getPictureNumberInGm +OpenSHC::Input::MouseState::updateRightDragCameraControl + OpenSHC::Map::Navigation::DirectionAlgorithmState::getMouseVectorLengthBasedOnDirection +OpenSHC::IO::ResourceManager::swapMapDataWithNextMap + OpenSHC::IO::LowLevelMemory::copyData +OpenSHC::IO::ResourceManager::readFirstPartOfCurrentResourceIntoMemory + OpenSHC::IO::LowLevelMemory::putFileNameAndAppendFileExtension +OpenSHC::IO::ResourceManager::readNextPartOfCurrentResourceIntoMemory + OpenSHC::IO::LowLevelMemory::putFileNameAndAppendFileExtension +OpenSHC::IO::DecoderState::encodeData + OpenSHC::IO::LowLevelMemory::copyData +OpenSHC::IO::DecoderState::decodeData + OpenSHC::IO::LowLevelMemory::copyData +OpenSHC::Synchrony::GameSynchronyState::processSyncPacket + OpenSHC::Synchrony::GameSynchronyState::translateMultiplayerIDsIntoPlayerIDs +OpenSHC::Synchrony::GameSynchronyState::receiveAllTransmittedCommands + OpenSHC::Synchrony::GameSynchronyState::translateMultiplayerIDsIntoPlayerIDs +OpenSHC::Map::TileMapState::updateMoatCountdownTimers + OpenSHC::Map::TileMapState::recountTotalOwnedMoats +OpenSHC::UI::HoveredState::Constructor_HoveredState + OpenSHC::UI::HoveredState::clearHoveredState +OpenSHC::Map::Units::UpdateBurningMan + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasTunnelerNotFinishedDigging +OpenSHC::Map::Units::UpdateCamel + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateMiner + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateInnkeeper + OpenSHC::Map::Buildings::BuildingsState::getBuildingResourceAmountByUid + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateMerchant + OpenSHC::Game::GameStateStructures::activateTraderState + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateMerchantHorse + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateLady + OpenSHC::Map::Units::UnitsState::makeUnitStopWalkingByClearingPathProgressState + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::changeDestinationByAmount +OpenSHC::Map::Units::UpdateJuggler + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::hasTunnelerNotFinishedDigging +OpenSHC::Map::Units::UpdateFireEater + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::hasTunnelerNotFinishedDigging + OpenSHC::Map::Units::UnitsState::changeDestinationByAmount +OpenSHC::Map::Units::UpdateQuarryMason + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState +OpenSHC::Map::Units::UpdateHopsFarmer + OpenSHC::Map::Units::IncrementAndOptionalUpdateAVValueRelated + OpenSHC::Map::Units::SetStateToFreetimeWalking + OpenSHC::Map::Units::ComputeGoodsProduced + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateAppleFarmer + OpenSHC::Map::Units::IncrementAndOptionalUpdateAVValueRelated + OpenSHC::Map::Units::SetStateToFreetimeWalking + OpenSHC::Map::Units::ComputeGoodsProduced + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateDairyFarmer + OpenSHC::Map::Units::IncrementAndOptionalUpdateAVValueRelated + OpenSHC::Map::Units::SetStateToFreetimeWalking + OpenSHC::Map::Units::CheckUnitProductionPaused + OpenSHC::Map::Units::ComputeGoodsProduced + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdatePikeman + OpenSHC::Rendering::ViewportRenderState::xyAreValid + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::changeDestinationByAmount +OpenSHC::Map::Units::UpdateMaceman + OpenSHC::Rendering::ViewportRenderState::xyAreValid + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::changeDestinationByAmount +OpenSHC::Map::Units::UpdateSwordsman + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateKnight + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateDrunkard + OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState + OpenSHC::Map::Units::UnitsState::hasTunnelerNotFinishedDigging +OpenSHC::Map::Units::UpdateCatapult + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::deselectUnit +OpenSHC::Map::Units::UpdateTrebuchet + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::deselectUnit +OpenSHC::Map::Units::UpdateMangonel + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::deselectUnit +OpenSHC::Map::Units::UpdateBallista + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::deselectUnit +OpenSHC::Map::Units::UpdateSlave + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateAssassin + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateArabianSwordsman + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination +OpenSHC::Map::Units::UpdateFireBallista + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination + OpenSHC::Map::Units::UnitsState::deselectUnit +OpenSHC::Map::Units::UpdateHorseArcher + OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination From b14878a1ad1e6543b64ebb0195f8a802bd13a1e1 Mon Sep 17 00:00:00 2001 From: kotijekriv Date: Thu, 12 Nov 2026 18:52:27 +0100 Subject: [PATCH 2/4] cmake: optional wrapper units built from function-visibility.txt With -DOPENSHC_FUNCTION_VISIBILITY_UNITS=ON, configure runs cmake/function-visibility-units.py. It groups every caller of cmake/function-visibility.txt with the callees whose bodies it must see (one group per connected set, since a function is defined once) and writes one wrapper .cpp per group that #includes the members. The wrappers replace their members in the build, and the members leave the /GL list; the wrappers are built without /GL. Off by default; nothing changes without the option. Groups are formed over files, so a .cpp that defines several listed functions is included once. A group whose members define the same internal-linkage name (a file-scope static or anything in an anonymous namespace) is not wrapped, and its files build as before. Manifest names with no .cpp in the build are skipped and listed at configure time. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 31 ++++++ cmake/function-visibility-units.py | 171 +++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 cmake/function-visibility-units.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e84eee9dc..f1c96b6519 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -139,6 +139,37 @@ endif() # For now, we set the /GL flag for a select number of files. Setting the /GL flag in *both* the caller and callee function # implementation removes the unnecessary mov ecx instruction from the callers code. file_dependent_read_list("${CMAKE_SOURCE_DIR}/cmake/compiler-flags-gl.txt" COMPILER_FLAG_GL_FILES) + +# Optional, off by default: compile each caller of cmake/function-visibility.txt in one translation unit with the +# callees whose bodies it must see, instead of relying on /GL. cmake/function-visibility-units.py groups the +# listed functions and writes one wrapper .cpp per group that #includes its members. The wrappers replace their +# members in the build, and the members leave the /GL list; the wrappers themselves are built without /GL. +option(OPENSHC_FUNCTION_VISIBILITY_UNITS "Build the function-visibility.txt groups as wrapper units, not /GL" OFF) +if(OPENSHC_FUNCTION_VISIBILITY_UNITS) + find_package(Python3 REQUIRED COMPONENTS Interpreter) + set(VISIBILITY_DIR "${CMAKE_BINARY_DIR}/function-visibility-units") + file(MAKE_DIRECTORY "${VISIBILITY_DIR}") + string(REPLACE ";" "\n" VISIBILITY_SOURCES_TEXT "${OPENSHC_SOURCES}") + file(WRITE "${VISIBILITY_DIR}/sources.txt" "${VISIBILITY_SOURCES_TEXT}\n") + file_add_depends("${CMAKE_SOURCE_DIR}/cmake/function-visibility.txt") + file_add_depends("${CMAKE_SOURCE_DIR}/cmake/function-visibility-units.py") + execute_process( + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/cmake/function-visibility-units.py" + "${CMAKE_SOURCE_DIR}" "${CMAKE_SOURCE_DIR}/cmake/function-visibility.txt" + "${VISIBILITY_DIR}/sources.txt" "${VISIBILITY_DIR}" + RESULT_VARIABLE VISIBILITY_RESULT + ) + if(NOT VISIBILITY_RESULT EQUAL 0) + message(FATAL_ERROR "cmake/function-visibility-units.py failed") + endif() + include("${VISIBILITY_DIR}/units.cmake") + if(OPENSHC_VISIBILITY_MEMBER_FILES) + list(REMOVE_ITEM OPENSHC_SOURCES ${OPENSHC_VISIBILITY_MEMBER_FILES}) + list(REMOVE_ITEM COMPILER_FLAG_GL_FILES ${OPENSHC_VISIBILITY_MEMBER_FILES}) + endif() + list(APPEND OPENSHC_SOURCES ${OPENSHC_VISIBILITY_UNIT_FILES}) +endif() + set_source_files_properties(${COMPILER_FLAG_GL_FILES} PROPERTIES COMPILE_OPTIONS /GL) diff --git a/cmake/function-visibility-units.py b/cmake/function-visibility-units.py new file mode 100644 index 0000000000..085cdafe41 --- /dev/null +++ b/cmake/function-visibility-units.py @@ -0,0 +1,171 @@ +"""Generate the translation units that cmake/function-visibility.txt asks for. + + python cmake/function-visibility-units.py ROOT MANIFEST SOURCES_LIST OUT_DIR + +Called by CMakeLists.txt when OPENSHC_FUNCTION_VISIBILITY_UNITS is ON. The manifest lists, per caller, the callees +whose bodies the caller must see when it is compiled. A function can be defined only once, so every caller and callee +joined by an entry ends up in one group, and each group becomes one wrapper file that #includes its members' .cpp +files. The build then compiles the wrappers instead of the members, and the members leave the /GL list. + +ROOT the source tree (CMAKE_SOURCE_DIR) +MANIFEST cmake/function-visibility.txt +SOURCES_LIST a file with the build's OpenSHC sources, one per line, as CMake has them +OUT_DIR where the wrappers and units.cmake are written (in the build tree) + +units.cmake sets OPENSHC_VISIBILITY_UNIT_FILES (the wrappers) and OPENSHC_VISIBILITY_MEMBER_FILES (the sources they +replace, spelled as in SOURCES_LIST). Only sources in the build are grouped; an entry whose caller or callee is not +in the build simply has no effect. + +Two things would break a wrapper: +- a .cpp included twice: groups are formed over files, not functions, so a file that defines several listed + functions lands in exactly one group; +- two members defining the same internal-linkage name (a file-scope `static`, or anything in an anonymous + namespace): such a group is not wrapped, its files build as before, and the clash is printed. The check reads the + source line by line rather than parsing it, so a `{` or `}` inside a string literal or a comment can hide a + static from it. A clash it misses is not silent: the wrapper then fails to compile (C2084, function already has a + body). + +Names in the manifest that no .cpp in the build defines are skipped, and their count and names are printed. +""" +import io +import os +import re +import sys + +MARK = re.compile(r'// FUNCTION: STRONGHOLDCRUSADER 0x[0-9A-Fa-f]+[^\n]*\n') +NAMESPACE = re.compile(r'namespace\s+(\w+)\s*\{|(\{)|\}') + + +def read(path): + return io.open(path, encoding='utf-8', errors='replace').read() + + +def defined_names(text): + """Fully qualified names of the functions marked in TEXT, as the definitions spell them.""" + names = [] + for m in MARK.finditer(text): + stack = [] # namespace name, or None for any other brace + for t in NAMESPACE.finditer(text, 0, m.start()): + if t.group(1) or t.group(2): + stack.append(t.group(1)) + elif stack: + stack.pop() + d = re.search(r'([\w:]+)\s*\(', text[m.end():]) + if d: + names.append('::'.join([n for n in stack if n] + [d.group(1)])) + return names + + +def internal_names(text): + """Names with internal linkage defined at file scope: `static` definitions directly inside namespaces, and + whatever an anonymous namespace defines at its own top level. Comments and strings are not stripped: a false + hit only makes a group fall back to separate files, and a brace inside one can hide a name (see the module + docstring).""" + names = set() + stack = [] # one entry per open brace: 'ns', 'anon' or 'block' + decl = re.compile(r'^(?:static\s+)?(?:[\w:<>,*&]+\s+)+[*&]*(\w+)\s*(?:\(|=|\[|;)') + for raw in text.splitlines(): + line = raw.strip() + if line.startswith(('//', '#')): + continue + at_ns_scope = all(k in ('ns', 'anon') for k in stack) + if at_ns_scope: + m = decl.match(line) + if m and (line.startswith('static') or (stack and stack[-1] == 'anon')): + names.add(m.group(1)) + for tok in re.finditer(r'namespace\s+\w+\s*\{|namespace\s*\{|\{|\}', line): + t = tok.group(0) + if t == '}': + if stack: + stack.pop() + elif t.startswith('namespace'): + stack.append('anon' if re.match(r'namespace\s*\{', t) else 'ns') + else: + stack.append('block') + return names + + +def main(argv): + root, manifest, sources_list, out_dir = argv + root = os.path.abspath(root) + sources = [l.strip() for l in io.open(sources_list, encoding='utf-8') if l.strip()] + + def key(path): + return os.path.normcase(os.path.abspath(os.path.join(root, path))) + in_build = dict((key(s), s) for s in sources) + + where = {} # qualified name -> source entry + for d, _, files in os.walk(os.path.join(root, 'src', 'OpenSHC')): + for f in files: + if f.endswith('.cpp'): + p = os.path.join(d, f) + if os.path.normcase(os.path.abspath(p)) in in_build: + for n in defined_names(read(p)): + where.setdefault(n, in_build[os.path.normcase(os.path.abspath(p))]) + + entries, cur = [], None + for number, line in enumerate(io.open(manifest, encoding='utf-8'), 1): + if not line.strip(): + continue + if line.startswith((' ', '\t')): + if cur is None: + sys.exit('%s:%d: an indented callee before any caller; each entry starts with an unindented caller' + % (manifest, number)) + cur[1].append(line.strip()) + else: + cur = (line.strip(), []) + entries.append(cur) + + parent = {} + + def find(x): + parent.setdefault(x, x) + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + missing = set() + for caller, callees in entries: + missing.update(n for n in [caller] + callees if n not in where) + if caller not in where: + continue + for c in callees: + if c in where and where[c] != where[caller]: + parent[find(where[caller])] = find(where[c]) + if missing: + print('function-visibility: %d names have no .cpp in this build and are skipped: %s' + % (len(missing), ', '.join(sorted(missing)))) + groups = {} + for f in list(parent): + groups.setdefault(find(f), []).append(f) + + if not os.path.isdir(out_dir): + os.makedirs(out_dir) + units, members = [], [] + order = dict((s, i) for i, s in enumerate(sources)) + for g in sorted((sorted(g, key=order.get) for g in groups.values()), key=lambda g: order[g[0]]): + seen, clash = {}, [] + for f in g: + for n in internal_names(read(os.path.join(root, f))): + if n in seen: + clash.append('%s (%s and %s)' % (n, seen[n], f)) + seen.setdefault(n, f) + if clash: + print('function-visibility: not grouping %d files, internal names clash: %s' % (len(g), '; '.join(clash))) + continue + path = os.path.join(out_dir, 'unit_%03d.cpp' % len(units)).replace(os.sep, '/') + text = '// Generated from cmake/function-visibility.txt by cmake/function-visibility-units.py. Do not edit.\n' + text += ''.join('#include "%s"\n' % os.path.join(root, f).replace(os.sep, '/') for f in g) + if not os.path.exists(path) or read(path) != text: # unchanged wrappers keep their timestamps + io.open(path, 'w', encoding='utf-8', newline='\n').write(text) + units.append(path) + members.extend(g) + with io.open(os.path.join(out_dir, 'units.cmake'), 'w', encoding='utf-8', newline='\n') as o: + o.write('set(OPENSHC_VISIBILITY_UNIT_FILES\n%s)\n' % ''.join(' "%s"\n' % u for u in units)) + o.write('set(OPENSHC_VISIBILITY_MEMBER_FILES\n%s)\n' % ''.join(' "%s"\n' % m for m in members)) + print('function-visibility: %d units holding %d source files' % (len(units), len(members))) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) From 6ba3369ad4c1a07016426aaf9536fab05073a094 Mon Sep 17 00:00:00 2001 From: kotijekriv Date: Sat, 14 Nov 2026 00:15:55 +0100 Subject: [PATCH 3/4] cmake: Gibbet and StretchingRack no longer need updateBuildingSignpostCounter's body #290 rewrote UpdateBadBuildingGibbet and UpdateBadBuildingStretchingRack so that they reach 100% without /GL. On main (ea63a49d9), tu_merge.py gives both 1.0000 in all three layouts: the caller alone, the callee's body pasted before it, and pasted after it (45 of 45 and 41 of 41 instructions). Seeing updateBuildingSignpostCounter no longer helps either of them, so their two entries go. The callee keeps its other two callers, UpdateBadBuildingGallows and UpdateBadBuildingDungeon. The manifest now has 85 entries and 125 edges. On main's sources the wrapper generator from #399 makes 24 units holding 91 source files (93 before), with no internal-name clashes and the same 23 names not on main yet. Co-Authored-By: Claude Opus 5.5 --- cmake/function-visibility.txt | 4 ---- 1 file changed, 4 deletions(-) diff --git a/cmake/function-visibility.txt b/cmake/function-visibility.txt index 3368e445da..308f5892bd 100644 --- a/cmake/function-visibility.txt +++ b/cmake/function-visibility.txt @@ -27,12 +27,8 @@ OpenSHC::Map::Buildings::UpdateStables OpenSHC::Map::Buildings::BuildingsState::validateBuildingTetheredUnits OpenSHC::Map::Buildings::UpdateBadBuildingGallows OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter -OpenSHC::Map::Buildings::UpdateBadBuildingGibbet - OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter OpenSHC::Map::Buildings::UpdateBadBuildingDungeon OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter -OpenSHC::Map::Buildings::UpdateBadBuildingStretchingRack - OpenSHC::Map::Buildings::BuildingsState::updateBuildingSignpostCounter OpenSHC::Map::Buildings::BuildingsState::hasBuildingAsNeighbour OpenSHC::Map::Buildings::BuildingsState::setupBuildingEntrancesOffset OpenSHC::Map::Buildings::BuildingsState::findParticularBuilding From e7be371348279b520c842063472c71fd8a7489e6 Mon Sep 17 00:00:00 2001 From: kotijekriv Date: Sat, 21 Nov 2026 00:44:14 +0100 Subject: [PATCH 4/4] cmake: UpdateMerchant must not see activateTraderState's body The entry for UpdateMerchant listed GameStateStructures::activateTraderState. That edge was measured on a 93.8% draft of UpdateMerchant. The function has since landed on main at 100% (#409), and it reaches that under /GL without the body: activateTraderState.cpp is not on the /GL list. With the body in its unit the caller keeps the unit slot in esi across the call, where the original reads it again, so the original's caller did not know it. Measured on main 3458fea34 with #399's wrapper build (-DOPENSHC_FUNCTION_VISIBILITY_UNITS=ON), reccmp, raw: UpdateMerchant reads 100.0 under /GL, 90.0 with the wrappers before this change and 100.0 after it. It was the only one of the 150 functions in that build (main's /GL list plus every file the manifest names) whose raw number differed between /GL and the wrappers, and none differs now. The manifest now has 85 entries and 124 edges. On main's sources the generator makes 24 units holding 92 source files (93 before). Co-Authored-By: Claude Fable 5.2 --- cmake/function-visibility.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/cmake/function-visibility.txt b/cmake/function-visibility.txt index 308f5892bd..f1c385c59c 100644 --- a/cmake/function-visibility.txt +++ b/cmake/function-visibility.txt @@ -129,7 +129,6 @@ OpenSHC::Map::Units::UpdateInnkeeper OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination OpenSHC::Map::Units::UpdateMerchant - OpenSHC::Game::GameStateStructures::activateTraderState OpenSHC::Map::Units::UnitsState::checkIfCitizenUnitIsAliveBasedOnState OpenSHC::Map::Units::UnitsState::hasUnitReachedDestination OpenSHC::Map::Units::UpdateMerchantHorse