[cfe-dev] Visiting statements of a CFG one time
Stefan Schulze Frielinghaus via cfe-dev
cfe-dev at lists.llvm.org
Wed Sep 9 04:54:46 PDT 2020
On Tue, Sep 08, 2020 at 10:15:31AM -0400, Andrew Sutton wrote:
> I ran into exactly this problem last week. I wanted to visit top-level
> statements (and expressions since expression-statements are just
> expressions) and recursively work through their ASTs. I just wrote a small
> pre-pass over the CFG elements that would construct a set of top-level
> statements by noting which expressions occurred as subexpressions and then
> extract the statements from there.
>
> There's probably a better way to do this, but here's what my implementation
> of that function looks like.
>
> void findStatements(CFGBlock *B, llvm::SmallVectorImpl<const Stmt *>
> &SS) {
> llvm::SmallDenseMap<const Stmt*, bool> Map;
>
> // Mark subexpressions of each element in the block.
> for (auto I = B->begin(); I != B->end(); ++I) {
> CFGElement E = *I;
> if (auto SE = E.getAs<CFGStmt>()) {
> const Stmt *S = SE->getStmt();
> for (const Stmt *K : S->children())
> Map[K] = true;
> }
> }
>
> // Any expressions not in Map are statements.
> for (auto I = B->begin(); I != B->end(); ++I) {
> CFGElement E = *I;
> if (auto SE = E.getAs<CFGStmt>()) {
> const Stmt *S = SE->getStmt();
> if (Map.find(S) == Map.end())
> SS.push_back(S);
> }
> }
> }
Interesting, though I think you need to do it recursively since
children() is not recursive. In my case one of the expressions which
got pulled out had an extra ParenExpr around in the embedded expression.
I will further play around with this idea.
Thanks,
Stefan
More information about the cfe-dev
mailing list