When looking for module, HeaderSearch::lookupModule iterates through search paths, parses modulemaps, eagerly creates Module instances and caches them in ModuleMap. When first called, it will correctly note usage of the search path that discovered the returned module. On subsequent calls, however, it can pull previously created Module from ModuleMap without noting the search path was used.
This patch fixes that. This requires HeaderSearch to be able to go from Module to the index of corresponding search path. This is achieved by adding a callback to the modulemap parser, intercepting creations of Module instances and pairing them with the current search path index.
The outlined solution doesn't handle all corner cases, though. It's possible for clients to use HeaderSearch to lookup module B, which could parse an unrelated modulemap and create instance of module A. The client can then look up module A directly in ModuleMap, avoiding the logic in HeaderSearch that makes -Rsearch-path-usage work.