20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/PostOrderIterator.h" 22 #include "llvm/ADT/PriorityQueue.h" 23 #include "llvm/Support/raw_ostream.h" 27 using namespace clang;
31 class DataflowWorklist {
32 llvm::BitVector enqueuedBlocks;
34 llvm::PriorityQueue<const CFGBlock *, SmallVector<const CFGBlock *, 20>,
39 : enqueuedBlocks(cfg.getNumBlockIDs()),
41 worklist(POV->getComparator()) {}
43 void enqueueBlock(
const CFGBlock *block);
44 void enqueuePredecessors(
const CFGBlock *block);
52 if (block && !enqueuedBlocks[block->
getBlockID()]) {
58 void DataflowWorklist::enqueuePredecessors(
const clang::CFGBlock *block) {
60 E = block->
pred_end(); I != E; ++I) {
65 const CFGBlock *DataflowWorklist::dequeue() {
75 class LiveVariablesImpl {
78 llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
79 llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
80 llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
81 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
82 llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
83 llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
84 llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
85 const bool killAtAssign;
99 : analysisContext(ac),
103 killAtAssign(KillAtAssign) {}
108 return *((LiveVariablesImpl *) x);
116 return liveStmts.contains(S);
120 if (
const auto *DD = dyn_cast<DecompositionDecl>(D)) {
123 alive |= liveBindings.contains(BD);
126 return liveDecls.contains(D);
130 template <
typename SET>
131 SET mergeSets(SET A, SET B) {
135 for (
typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
142 void LiveVariables::Observer::anchor() { }
148 llvm::ImmutableSetRef<const Stmt *>
149 SSetRefA(valsA.
liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
150 SSetRefB(valsB.
liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
153 llvm::ImmutableSetRef<const VarDecl *>
154 DSetRefA(valsA.
liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
155 DSetRefB(valsB.
liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
157 llvm::ImmutableSetRef<const BindingDecl *>
158 BSetRefA(valsA.
liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
159 BSetRefB(valsB.
liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
161 SSetRefA = mergeSets(SSetRefA, SSetRefB);
162 DSetRefA = mergeSets(DSetRefA, DSetRefB);
163 BSetRefA = mergeSets(BSetRefA, BSetRefB);
168 DSetRefA.asImmutableSet(),
169 BSetRefA.asImmutableSet());
193 return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
201 class TransferFunctions :
public StmtVisitor<TransferFunctions> {
202 LiveVariablesImpl &LV;
207 TransferFunctions(LiveVariablesImpl &im,
211 : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
226 while (
const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
228 if (VAT->getSizeExpr())
231 ty = VT->getElementType().getTypePtr();
239 if (
const Expr *Ex = dyn_cast<Expr>(S))
240 S = Ex->IgnoreParens();
241 if (
const FullExpr *FE = dyn_cast<FullExpr>(S)) {
242 S = FE->getSubExpr();
246 S = OVE->getSourceExpr();
255 llvm::ImmutableSet<const Stmt *>::Factory &F,
260 void TransferFunctions::Visit(
Stmt *S) {
262 observer->observeStmt(S, currentBlock, val);
267 val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
275 case Stmt::StmtExprClass: {
277 S = cast<StmtExpr>(S)->getSubStmt();
280 case Stmt::CXXMemberCallExprClass: {
284 AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
288 case Stmt::ObjCMessageExprClass: {
292 val.liveDecls = LV.DSetFact.add(val.liveDecls,
293 LV.analysisContext.getSelfDecl());
296 case Stmt::DeclStmtClass: {
297 const DeclStmt *DS = cast<DeclStmt>(S);
300 VA !=
nullptr; VA =
FindVA(VA->getElementType())) {
301 AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
306 case Stmt::PseudoObjectExprClass: {
309 Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
312 child = OV->getSourceExpr();
314 val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
319 case Stmt::ExprWithCleanupsClass: {
320 S = cast<ExprWithCleanups>(S)->getSubExpr();
323 case Stmt::CXXBindTemporaryExprClass: {
324 S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
327 case Stmt::UnaryExprOrTypeTraitExprClass: {
331 case Stmt::IfStmtClass: {
335 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<IfStmt>(S)->getCond());
338 case Stmt::WhileStmtClass: {
342 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<WhileStmt>(S)->getCond());
345 case Stmt::DoStmtClass: {
349 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<DoStmt>(S)->getCond());
352 case Stmt::ForStmtClass: {
356 AddLiveStmt(val.liveStmts, LV.SSetFact, cast<ForStmt>(S)->getCond());
375 if (!LV.killAtAssign)
381 if (
DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
382 const Decl* D = DR->getDecl();
385 if (
const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
386 Killed = !BD->getType()->isReferenceType();
388 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
389 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
392 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
396 if (Killed && observer)
397 observer->observerKill(DR);
402 void TransferFunctions::VisitBlockExpr(
BlockExpr *BE) {
404 LV.analysisContext.getReferencedBlockVars(BE->
getBlockDecl())) {
407 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
411 void TransferFunctions::VisitDeclRefExpr(
DeclRefExpr *DR) {
413 bool InAssignment = LV.inAssignment[DR];
414 if (
const auto *BD = dyn_cast<BindingDecl>(D)) {
416 val.liveBindings = LV.BSetFact.
add(val.liveBindings, BD);
417 }
else if (
const auto *VD = dyn_cast<VarDecl>(D)) {
419 val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
423 void TransferFunctions::VisitDeclStmt(
DeclStmt *DS) {
424 for (
const auto *DI : DS->
decls()) {
425 if (
const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
426 for (
const auto *BD : DD->bindings())
427 val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
428 }
else if (
const auto *VD = dyn_cast<VarDecl>(DI)) {
430 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
441 if (
DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
444 else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
445 VD = cast<VarDecl>(DR->
getDecl());
449 val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
451 observer->observerKill(DR);
455 void TransferFunctions::
467 val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->
IgnoreParens());
471 void TransferFunctions::VisitUnaryOperator(
UnaryOperator *UO) {
490 if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
492 observer->observerKill(DR);
502 TransferFunctions TF(*
this, val, obs, block);
506 TF.Visit(const_cast<Stmt*>(term));
510 ei = block->
rend(); it != ei; ++it) {
523 TF.Visit(const_cast<Stmt*>(S));
524 stmtsToLiveness[S] = val;
530 const CFG *cfg =
getImpl(impl).analysisContext.getCFG();
532 getImpl(impl).runOnBlock(*it,
getImpl(impl).blocksEndToLiveness[*it], &obs);
535 LiveVariables::LiveVariables(
void *im) : impl(im) {}
538 delete (LiveVariablesImpl*) impl;
555 LiveVariablesImpl *LV =
new LiveVariablesImpl(AC, killAtAssign);
559 DataflowWorklist worklist(*cfg, AC);
565 worklist.enqueueBlock(block);
576 if (
const auto *BO = dyn_cast<BinaryOperator>(stmt)) {
577 if (BO->getOpcode() == BO_Assign) {
579 dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
580 LV->inAssignment[DR] = 1;
588 while (
const CFGBlock *block = worklist.dequeue()) {
596 ei = block->
succ_end(); it != ei; ++it) {
598 val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
603 everAnalyzedBlock[block->
getBlockID()] =
true;
604 else if (prevVal.
equals(val))
610 LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
613 worklist.enqueuePredecessors(block);
620 getImpl(impl).dumpBlockLiveness(M);
623 void LiveVariablesImpl::dumpBlockLiveness(
const SourceManager &M) {
624 std::vector<const CFGBlock *> vec;
625 for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
626 it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
628 vec.push_back(it->first);
634 std::vector<const VarDecl*> declVec;
636 for (std::vector<const CFGBlock *>::iterator
637 it = vec.begin(), ei = vec.end(); it != ei; ++it) {
638 llvm::errs() <<
"\n[ B" << (*it)->getBlockID()
639 <<
" (live variables at block exit) ]\n";
644 for (llvm::ImmutableSet<const VarDecl *>::iterator si =
646 se = vals.
liveDecls.end(); si != se; ++si) {
647 declVec.push_back(*si);
650 llvm::sort(declVec, [](
const Decl *A,
const Decl *B) {
654 for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
655 de = declVec.end(); di != de; ++di) {
656 llvm::errs() <<
" " << (*di)->getDeclName().getAsString()
658 (*di)->getLocation().print(llvm::errs(), M);
659 llvm::errs() <<
">\n";
662 llvm::errs() <<
"\n";
666 getImpl(impl).dumpStmtLiveness(M);
669 void LiveVariablesImpl::dumpStmtLiveness(
const SourceManager &M) {
671 for (
auto I : *analysisContext.getCFG()) {
673 llvm::errs() <<
"\n[ B" << I->getBlockID()
674 <<
" (live statements at block exit) ]\n";
675 for (
auto S : blocksEndToLiveness[I].liveStmts) {
676 llvm::errs() <<
"\n";
679 llvm::errs() <<
"\n";
The receiver is the instance of the superclass object.
const BlockDecl * getBlockDecl() const
static const VariableArrayType * FindVA(QualType Ty)
A (possibly-)qualified type.
static bool isAlwaysAlive(const VarDecl *D)
static const Stmt * LookThroughStmt(const Stmt *S)
AdjacentBlocks::const_iterator const_pred_iterator
static LiveVariables * computeLiveness(AnalysisDeclContext &analysisContext, bool killAtAssign)
Compute the liveness information for a given CFG.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
succ_iterator succ_begin()
Stmt - This represents one statement.
unsigned getBlockID() const
Decl - This represents one declaration (or definition), e.g.
Expr * getImplicitObjectArgument() const
Retrieves the implicit object argument for the member call.
SourceLocation getBeginLoc() const LLVM_READONLY
The base class of the type hierarchy.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
static const void * getTag()
Represents a variable declaration or definition.
llvm::ImmutableSet< const BindingDecl * > liveBindings
bool equals(const LivenessValues &V) const
static bool isAssignmentOp(Opcode Opc)
bool isVariableArrayType() const
FullExpr - Represents a "full-expression" node.
AnalysisDeclContext contains the context data for the function or method under analysis.
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
bool isReferenceType() const
void runOnAllBlocks(Observer &obs)
AdjacentBlocks::const_iterator const_succ_iterator
static bool runOnBlock(const CFGBlock *block, const CFG &cfg, AnalysisDeclContext &ac, CFGBlockValues &vals, const ClassifyRefs &classification, llvm::BitVector &wasAnalyzed, UninitVariablesHandler &handler)
bool isLive(const CFGBlock *B, const VarDecl *D)
Return true if a variable is live at the end of a specified block.
A builtin binary operation expression such as "x + y" or "x <= y".
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
A binding in a decomposition declaration.
~LiveVariables() override
CFGBlockListTy::const_iterator const_iterator
static const void * getTag()
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
Represents a single basic block in a source-level CFG.
This represents one expression.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
ElementList::const_iterator const_iterator
An expression that sends a message to the given Objective-C object or class.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
static LiveVariablesImpl & getImpl(void *x)
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
reverse_iterator rbegin()
CFGTerminator getTerminator()
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
void dumpBlockLiveness(const SourceManager &M)
Print to stderr the variable liveness information associated with each basic block.
Expr * getSubExpr() const
static void AddLiveStmt(llvm::ImmutableSet< const Stmt *> &Set, llvm::ImmutableSet< const Stmt *>::Factory &F, const Stmt *S)
Represents a call to a member function that may be written either with member call syntax (e...
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
llvm::ImmutableSet< const VarDecl * > liveDecls
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
UnaryExprOrTypeTrait getKind() const
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
bool isArgumentType() const
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
pred_iterator pred_begin()
Dataflow Directional Tag Classes.
bool isLive(const Stmt *S) const
StmtClass getStmtClass() const
const Decl * getSingleDecl() const
llvm::ImmutableSet< const Stmt * > liveStmts
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
Represents Objective-C's collection statement.
void dumpStmtLiveness(const SourceManager &M)
Print to stderr the statement liveness information associated with each basic block.
Represents a top-level expression in a basic block.
RetTy Visit(PTR(Stmt) S, ParamTys... P)
A reference to a declared variable, function, enum, etc.
Represents a C array with a specified size that is not an integer-constant-expression.
static bool writeShouldKill(const VarDecl *VD)
This class handles loading and caching of source files into memory.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.