[cfe-dev] Cannot access the offset of a virtual base class in a given case

Xiaolong Tang xiaolong.snake at gmail.com
Mon Aug 22 07:01:33 PDT 2011


Hi Everyone, 

I have a question about the layout of a C++ record. 

Given the following class hierarchy:

// A virtual class
class Foo {
public:
  virtual void f() {};
};

// A virtual class
class Bar {
public:
  virtual void g() {};
};

// Two virtual bases 
class Zoo : virtual public Foo, virtual public Bar {
public:
  int x;
  int y;
  virtual void g() { x = x + y; };
  virtual void f() { x = x - y; };
};


Following is the code I use to access the offset of the virtual bases of a
class: 
    
    // Suppose that "Record" denotes a RecordDecl

    // The layout code generation for the backend, e.g., LLVM IR
    const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(Record);
    // In C++ mode
    const CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);

    // Virtual bases 
    for (CXXRecordDecl::base_class_const_iterator I = CXXRecord->vbases_begin(),
         E = CXXRecord->vbases_end(); I != E; ++I) {
      // The type of a virtual base 	 
      const RecordType *BaseTy = I->getType()->getAs<RecordType>();
      // The decl of the virtual base
      const CXXRecordDecl *BaseDecl = dyn_cast<CXXRecordDecl>(BaseTy->getDecl());
      // Accessing the index of the base 
      unsigned fieldNo  = Layout.getVirtualBaseIndex(BaseDecl);
    }

Fed with the given class hierarchy, the last statement of the above
code, i.e., "getVirtualBaseIndex(BaseDecl)", causes an assertion
failure. 

  Assertion failed: (CompleteObjectVirtualBases.count(base) && "Invalid virtual base!"), ...

The failure means that the virtual base "Foo" is not in the
layout mapping from the virtual bases of the class "Zoo" to their
offsets. So, can someone point out any hints about this missing? 

P.S. When the class "Foo" contains one data member, the above
issue goes away. 


Xiaolong








More information about the cfe-dev mailing list