[PATCH] D58514: Avoid needlessly copying blocks that initialize or are assigned to local auto variables to the heap

Akira Hatanaka via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Thu Feb 21 08:42:50 PST 2019


ahatanak created this revision.
ahatanak added reviewers: rjmccall, erik.pilkington.
ahatanak added a project: clang.
Herald added subscribers: jdoerfert, dexonsmith, jkorous.

This patch avoids copying blocks that initialize or are assigned to local auto variables to the heap when the local auto variables do not have their addresses taken and are declared in the same scope as the block. We can possibly add back the optimization in the ARC optimizer that was reverted in r189869 (http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20130902/186509.html), but I suspect it would be much more complicated and fragile than doing it in the front-end.

I'm not 100% sure whether it's necessary to disable this optimization when the address of the local variable is taken. We do pass a block on the stack to a function when the block is directly passed instead of first being assigned to a local variable, but clang currently doesn't copy the passed block to the heap in the callee although the block can possibly escape if the address is taken. For example:

  __strong id *g0, g1;
  
  void foo0(BlockTy b) {
    g0 = (__strong id *)&b;
    g1 = *g0; // this is just a retain, not a block copy.
  }
  
  void foo1() {
    foo0(^{...}) // block is on the stack.
  }
  
  void foo2() {
    foo1();
    ((BlockTy)g1)(); // this can crash if the block is still on the stack.
  }

rdar://problem/13289333


Repository:
  rC Clang

https://reviews.llvm.org/D58514

Files:
  include/clang/AST/Decl.h
  include/clang/AST/DeclBase.h
  include/clang/Sema/ScopeInfo.h
  lib/AST/Decl.cpp
  lib/CodeGen/CGObjC.cpp
  lib/Sema/ScopeInfo.cpp
  lib/Sema/Sema.cpp
  lib/Sema/SemaDecl.cpp
  lib/Sema/SemaExpr.cpp
  lib/Serialization/ASTReaderDecl.cpp
  lib/Serialization/ASTWriterDecl.cpp
  test/CodeGenObjC/arc-block-copy-escape.m
  test/CodeGenObjC/arc-blocks.m
  test/CodeGenObjCXX/arc-blocks.mm
  test/PCH/arc-blocks.mm

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D58514.187799.patch
Type: text/x-patch
Size: 21668 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20190221/726fa0b1/attachment-0001.bin>


More information about the cfe-commits mailing list