[cfe-dev] Ownership of Stmts and Exprs, and destroying them

Doug Gregor doug.gregor at gmail.com
Mon Nov 24 19:36:50 PST 2008


On Mon, Nov 24, 2008 at 2:32 PM, Chris Lattner <clattner at apple.com> wrote:
>
> On Nov 23, 2008, at 5:25 AM, Doug Gregor wrote:
>
>> On Sun, Nov 23, 2008 at 2:54 AM, Chris Lattner <clattner at apple.com> wrote:
>>>
>>> On Nov 22, 2008, at 3:36 PM, Sebastian Redl wrote:
>>>>
>>>> Is this correct? Because I want to clean this up. I want to make the
>>>> Sema routines (and later the parser, too) not leak. So I need to know
>>>> exactly how this works.
>>>
>>> This would be great.  Probably the first place to start is to use
>>> audit the parser for places where early exits cause parsed stmts to be
>>> leaked.  Once that is done, start going through sema.  The pattern we
>>> want to use in Sema for statements is using OwningPtr to hold incoming
>>> arguments.  For example, ActOnBinOp should look like:
>>>
>>>                                   ExprTy *LHS, ExprTy *RHS) {
>>>  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
>>>  OwningPtr<Expr> lhs = (Expr *)LHS, rhs = (Expr*)RHS;
>>
>> This is too late. We want the arguments to the ActOnBinOp to be some
>> kind of smart pointer that provides transfer-of-ownership semantics
>> (basically, a C++'0x move_ptr) and knows how to delete expressions
>> properly (via Action::DestroyExpr).
>
> Sema doesn't need to call DestroyExpr: it knows these are Expr*'s.  The
> Parser needs to call Action::DestroyExpr because these are just void*'s to
> it.

Then Sema is free to take() from the smart pointer it is given into a
data structure that actually knows about Expr*'s. We do that anyway,
since we need to get the type right. The point is for the Parser-Sema
interface to clearly express when ownership is transferred: when the
Parser passes an ExprTy* it got into Sema, it's transferring ownership
to Sema; similarly, when Sema is returning an ExprResult, it is
transferring ownership of that pointer back to the Parser.

>> Similarly for ExprResult and
>> friends. That way, the type system enforces our ownership model
>> (transfer into Sema for the parameters of ActOn*, transfer out of Sema
>> on return), and we're safe from early exits.
>
> ExprResult is just a pair of success + pointer.  The actions in Sema are
> only called in the success case.

Of course. But ExprResult also (implicitly!) carries with it the
ownership of the pointer, and that's not at all clear now.

  - Doug



More information about the cfe-dev mailing list