diff --git a/llvm/include/llvm/IR/BasicBlock.h b/llvm/include/llvm/IR/BasicBlock.h --- a/llvm/include/llvm/IR/BasicBlock.h +++ b/llvm/include/llvm/IR/BasicBlock.h @@ -390,6 +390,11 @@ /// direct branches, switches, etc. to it. bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; } + /// Returns true if there are any uses of the address of this basic block + /// that are call instructions (which may allow the address of this basic + /// block to escape). + bool addressPotentiallyEscapesFunction(); + /// Update all phi nodes in this basic block's successors to refer to basic /// block \p New instead of to it. void replaceSuccessorsPhiUsesWith(BasicBlock *New); diff --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp --- a/llvm/lib/Analysis/InlineCost.cpp +++ b/llvm/lib/Analysis/InlineCost.cpp @@ -1832,7 +1832,7 @@ // see an indirect branch that ends up being dead code at a particular call // site. If the blockaddress escapes the function, e.g., via a global // variable, inlining may lead to an invalid cross-function reference. - if (BB->hasAddressTaken()) + if (BB->hasAddressTaken() && BB->addressPotentiallyEscapesFunction()) return "blockaddress"; // Analyze the cost of this block. If we blow through the threshold, this @@ -2082,7 +2082,7 @@ if (isa(BI->getTerminator())) return "contains indirect branches"; - if (BI->hasAddressTaken()) + if (BI->hasAddressTaken() && BI->addressPotentiallyEscapesFunction()) return "uses block address"; for (auto &II : *BI) { diff --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp --- a/llvm/lib/IR/BasicBlock.cpp +++ b/llvm/lib/IR/BasicBlock.cpp @@ -442,6 +442,14 @@ return New; } +bool BasicBlock::addressPotentiallyEscapesFunction() { + for (const Use& U : BlockAddress::get(this)->uses()) + if (const CallInst* CI = dyn_cast(U)) + if (!CI->paramHasAttr(U.getOperandNo(), Attribute::NoCapture)) + return true; + return false; +} + void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) { Instruction *TI = getTerminator(); if (!TI)