Wednesday, February 24, 2010

Clang and C++

I experimented a bit with how Clang compiles C++, but I'm not sure it provides much guidance.   With the classes:

class Rect {  ... };
class Square : public Rect { ... };

I end up with the llvm type declarations:

%class.Rect = type { i32, i32, i32, i32 }
%class.Square = type { [16 x i8] }

It does use bitcast to call inherited methods:

 %0 = bitcast %class.Square* %s to %class.Rect*  ; <%class.Rect*> [#uses=1]
  call void @_ZN4Rect9setBoundsEiiii(%class.Rect* %0, i32 0, i32 0, i32 10, i32 10)
  %call = call i32 @_ZN6Square4areaEv(%class.Square* %s) ; [#uses=1]

The strange names like "_ZN4Rect9setBoundsEiiii" are from "name mangling" in C++, which is how C++ provides overloading while maintaining compatibility with C which does not.  The source code name is "setBounds", and the random junk is added to make it unique. 

My C++ mojo has not been sufficient so far to really figure out how the dynamic dispatch is working, but it at least appears that the Clang front end (which is not as complete as the gcc front end) is using casts instead of using nested structures.  That doesn't mean nested structures is a bad idea ... I think either way should work.

No comments:

Post a Comment