[cfe-users] Quickly find the CXCursor for a declaration based on the cursors name?

via cfe-users cfe-users at lists.llvm.org
Fri Jan 22 04:09:20 PST 2016


Hi,

I am using libclang to process large PCH files. Within the translation units for the PCH files I need to locate the CXCursor of a declaration based on an arbitrary name. Currently I use something similar to the following which is terrible performance wise:

// start a search in this translation unit for a CXCursor to a declaration called "SomeNameToSearchFor", the CXType is not known in advance.
CXCursor result;
clang_visitChildren( clang_getTranslationUnitCursor( tu ), findDeclaration, &result );

// recurse into the TU and check *every* declaration name to see if it matches to one I want...
enum CXChildVisitResult findDeclaration( CXCursor cursor, CXCursor parent, CXClientData data )
{
	CXCursorKind kind = clang_getCursorKind( cursor );

	// ignore anything that is not a declaration
	if( !clang_isDeclaration( kind ) )
		return CXChildVisitResult::CXChildVisit_Continue;
		
	CXType type = clang_getCursorType( cursor );

	if( type.kind == CXTypeKind::CXType_Unexposed )
		type = clang_getCanonicalType( type );

	CXString spell = clang_getCursorSpelling( cursor );

	// Check if this name is the one I want...
	if( strcmp( clang_getCString( spell ), "SomeNameToSearchFor" ) == 0 )
	{
		*(CXCursor *)data = cursor;
		
		return CXChildVisitResult::CXChildVisit_Break;
	}
	
	// Recurse into namespace/class/struct/union declaration in order to keep searching inside them...
	if( kind == CXCursorKind::CXCursor_Namespace || kind == CXCursorKind::CXCursor_ClassDecl || kind == CXCursorKind::CXCursor_StructDecl || kind == CXCursorKind::CXCursor_UnionDecl )
	{
		if( clang_visitChildren( cursor, findDeclaration, data ) != 0 )
			return CXChildVisitResult::CXChildVisit_Break;
	}
	
	return CXChildVisitResult::CXChildVisit_Continue;
}

One option is to create a hash map of every declaration cursor (the maps value) and its name (the maps key) and then just do an O(1) lookup into that map for a corresponding cursor should one exist. However I am wondering if something like this is already available within clang so I can avoid the overhead as the PCH files can be huge.

Is there an existing technique to do a fast search of a declaration name for a cursor?

Thanks!

 - M.




More information about the cfe-users mailing list