1 #include "clang/Analysis/Analyses/LiveVariables.h"
2 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
3 
4 #include "clang/AST/Stmt.h"
5 #include "clang/Analysis/CFG.h"
6 #include "clang/Analysis/AnalysisContext.h"
7 #include "clang/AST/StmtVisitor.h"
8 
9 #include "llvm/ADT/PostOrderIterator.h"
10 #include "llvm/ADT/DenseMap.h"
11 
12 #include <deque>
13 #include <algorithm>
14 #include <vector>
15 
16 using namespace clang;
17 
18 namespace {
19 
20 class DataflowWorklist {
21   SmallVector<const CFGBlock *, 20> worklist;
22   llvm::BitVector enqueuedBlocks;
23   PostOrderCFGView *POV;
24 public:
25   DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
26     : enqueuedBlocks(cfg.getNumBlockIDs()),
27       POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
28 
29   void enqueueBlock(const CFGBlock *block);
30   void enqueueSuccessors(const CFGBlock *block);
31   void enqueuePredecessors(const CFGBlock *block);
32 
33   const CFGBlock *dequeue();
34 
35   void sortWorklist();
36 };
37 
38 }
39 
40 void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
41   if (block && !enqueuedBlocks[block->getBlockID()]) {
42     enqueuedBlocks[block->getBlockID()] = true;
43     worklist.push_back(block);
44   }
45 }
46 
47 void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) {
48   const unsigned OldWorklistSize = worklist.size();
49   for (CFGBlock::const_succ_iterator I = block->succ_begin(),
50        E = block->succ_end(); I != E; ++I) {
51     enqueueBlock(*I);
52   }
53 
54   if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
55     return;
56 
57   sortWorklist();
58 }
59 
60 void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
61   const unsigned OldWorklistSize = worklist.size();
62   for (CFGBlock::const_pred_iterator I = block->pred_begin(),
63        E = block->pred_end(); I != E; ++I) {
64     enqueueBlock(*I);
65   }
66 
67   if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
68     return;
69 
70   sortWorklist();
71 }
72 
73 void DataflowWorklist::sortWorklist() {
74   std::sort(worklist.begin(), worklist.end(), POV->getComparator());
75 }
76 
77 const CFGBlock *DataflowWorklist::dequeue() {
78   if (worklist.empty())
79     return 0;
80   const CFGBlock *b = worklist.back();
81   worklist.pop_back();
82   enqueuedBlocks[b->getBlockID()] = false;
83   return b;
84 }
85 
86 namespace {
87 class LiveVariablesImpl {
88 public:
89   AnalysisDeclContext &analysisContext;
90   std::vector<LiveVariables::LivenessValues> cfgBlockValues;
91   llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
92   llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
93   llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
94   llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
95   llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
96   llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
97   const bool killAtAssign;
98 
99   LiveVariables::LivenessValues
100   merge(LiveVariables::LivenessValues valsA,
101         LiveVariables::LivenessValues valsB);
102 
103   LiveVariables::LivenessValues runOnBlock(const CFGBlock *block,
104                                            LiveVariables::LivenessValues val,
105                                            LiveVariables::Observer *obs = 0);
106 
107   void dumpBlockLiveness(const SourceManager& M);
108 
109   LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
110     : analysisContext(ac),
111       SSetFact(false), // Do not canonicalize ImmutableSets by default.
112       DSetFact(false), // This is a *major* performance win.
113       killAtAssign(KillAtAssign) {}
114 };
115 }
116 
117 static LiveVariablesImpl &getImpl(void *x) {
118   return *((LiveVariablesImpl *) x);
119 }
120 
121 //===----------------------------------------------------------------------===//
122 // Operations and queries on LivenessValues.
123 //===----------------------------------------------------------------------===//
124 
125 bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
126   return liveStmts.contains(S);
127 }
128 
129 bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
130   return liveDecls.contains(D);
131 }
132 
133 namespace {
134   template <typename SET>
135   SET mergeSets(SET A, SET B) {
136     if (A.isEmpty())
137       return B;
138 
139     for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
140       A = A.add(*it);
141     }
142     return A;
143   }
144 }
145 
146 LiveVariables::LivenessValues
147 LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
148                          LiveVariables::LivenessValues valsB) {
149 
150   llvm::ImmutableSetRef<const Stmt *>
151     SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
152     SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
153 
154 
155   llvm::ImmutableSetRef<const VarDecl *>
156     DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
157     DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
158 
159 
160   SSetRefA = mergeSets(SSetRefA, SSetRefB);
161   DSetRefA = mergeSets(DSetRefA, DSetRefB);
162 
163   // asImmutableSet() canonicalizes the tree, allowing us to do an easy
164   // comparison afterwards.
165   return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
166                                        DSetRefA.asImmutableSet());
167 }
168 
169 bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
170   return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
171 }
172 
173 //===----------------------------------------------------------------------===//
174 // Query methods.
175 //===----------------------------------------------------------------------===//
176 
177 static bool isAlwaysAlive(const VarDecl *D) {
178   return D->hasGlobalStorage();
179 }
180 
181 bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
182   return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
183 }
184 
185 bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
186   return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
187 }
188 
189 bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
190   return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
191 }
192 
193 //===----------------------------------------------------------------------===//
194 // Dataflow computation.
195 //===----------------------------------------------------------------------===//
196 
197 namespace {
198 class TransferFunctions : public StmtVisitor<TransferFunctions> {
199   LiveVariablesImpl &LV;
200   LiveVariables::LivenessValues &val;
201   LiveVariables::Observer *observer;
202   const CFGBlock *currentBlock;
203 public:
204   TransferFunctions(LiveVariablesImpl &im,
205                     LiveVariables::LivenessValues &Val,
206                     LiveVariables::Observer *Observer,
207                     const CFGBlock *CurrentBlock)
208   : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
209 
210   void VisitBinaryOperator(BinaryOperator *BO);
211   void VisitBlockExpr(BlockExpr *BE);
212   void VisitDeclRefExpr(DeclRefExpr *DR);
213   void VisitDeclStmt(DeclStmt *DS);
214   void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
215   void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
216   void VisitUnaryOperator(UnaryOperator *UO);
217   void Visit(Stmt *S);
218 };
219 }
220 
221 static const VariableArrayType *FindVA(QualType Ty) {
222   const Type *ty = Ty.getTypePtr();
223   while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
224     if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
225       if (VAT->getSizeExpr())
226         return VAT;
227 
228     ty = VT->getElementType().getTypePtr();
229   }
230 
231   return 0;
232 }
233 
234 static const Stmt *LookThroughStmt(const Stmt *S) {
235   while (S) {
236     if (const Expr *Ex = dyn_cast<Expr>(S))
237       S = Ex->IgnoreParens();
238     if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
239       S = OVE->getSourceExpr();
240       continue;
241     }
242     break;
243   }
244   return S;
245 }
246 
247 static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
248                         llvm::ImmutableSet<const Stmt *>::Factory &F,
249                         const Stmt *S) {
250   Set = F.add(Set, LookThroughStmt(S));
251 }
252 
253 void TransferFunctions::Visit(Stmt *S) {
254   if (observer)
255     observer->observeStmt(S, currentBlock, val);
256 
257   StmtVisitor<TransferFunctions>::Visit(S);
258 
259   if (isa<Expr>(S)) {
260     val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
261   }
262 
263   // Mark all children expressions live.
264 
265   switch (S->getStmtClass()) {
266     default:
267       break;
268     case Stmt::StmtExprClass: {
269       // For statement expressions, look through the compound statement.
270       S = cast<StmtExpr>(S)->getSubStmt();
271       break;
272     }
273     case Stmt::CXXMemberCallExprClass: {
274       // Include the implicit "this" pointer as being live.
275       CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
276       if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
277         AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
278       }
279       break;
280     }
281     case Stmt::DeclStmtClass: {
282       const DeclStmt *DS = cast<DeclStmt>(S);
283       if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
284         for (const VariableArrayType* VA = FindVA(VD->getType());
285              VA != 0; VA = FindVA(VA->getElementType())) {
286           AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
287         }
288       }
289       break;
290     }
291     case Stmt::PseudoObjectExprClass: {
292       // A pseudo-object operation only directly consumes its result
293       // expression.
294       Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
295       if (!child) return;
296       if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
297         child = OV->getSourceExpr();
298       child = child->IgnoreParens();
299       val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
300       return;
301     }
302 
303     // FIXME: These cases eventually shouldn't be needed.
304     case Stmt::ExprWithCleanupsClass: {
305       S = cast<ExprWithCleanups>(S)->getSubExpr();
306       break;
307     }
308     case Stmt::CXXBindTemporaryExprClass: {
309       S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
310       break;
311     }
312     case Stmt::UnaryExprOrTypeTraitExprClass: {
313       // No need to unconditionally visit subexpressions.
314       return;
315     }
316   }
317 
318   for (Stmt::child_iterator it = S->child_begin(), ei = S->child_end();
319        it != ei; ++it) {
320     if (Stmt *child = *it)
321       AddLiveStmt(val.liveStmts, LV.SSetFact, child);
322   }
323 }
324 
325 void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
326   if (B->isAssignmentOp()) {
327     if (!LV.killAtAssign)
328       return;
329 
330     // Assigning to a variable?
331     Expr *LHS = B->getLHS()->IgnoreParens();
332 
333     if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
334       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
335         // Assignments to references don't kill the ref's address
336         if (VD->getType()->isReferenceType())
337           return;
338 
339         if (!isAlwaysAlive(VD)) {
340           // The variable is now dead.
341           val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
342         }
343 
344         if (observer)
345           observer->observerKill(DR);
346       }
347   }
348 }
349 
350 void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
351   AnalysisDeclContext::referenced_decls_iterator I, E;
352   llvm::tie(I, E) =
353     LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl());
354   for ( ; I != E ; ++I) {
355     const VarDecl *VD = *I;
356     if (isAlwaysAlive(VD))
357       continue;
358     val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
359   }
360 }
361 
362 void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
363   if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
364     if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
365       val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
366 }
367 
368 void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
369   for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE = DS->decl_end();
370        DI != DE; ++DI)
371     if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) {
372       if (!isAlwaysAlive(VD))
373         val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
374     }
375 }
376 
377 void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
378   // Kill the iteration variable.
379   DeclRefExpr *DR = 0;
380   const VarDecl *VD = 0;
381 
382   Stmt *element = OS->getElement();
383   if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
384     VD = cast<VarDecl>(DS->getSingleDecl());
385   }
386   else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
387     VD = cast<VarDecl>(DR->getDecl());
388   }
389 
390   if (VD) {
391     val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
392     if (observer && DR)
393       observer->observerKill(DR);
394   }
395 }
396 
397 void TransferFunctions::
398 VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
399 {
400   // While sizeof(var) doesn't technically extend the liveness of 'var', it
401   // does extent the liveness of metadata if 'var' is a VariableArrayType.
402   // We handle that special case here.
403   if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
404     return;
405 
406   const Expr *subEx = UE->getArgumentExpr();
407   if (subEx->getType()->isVariableArrayType()) {
408     assert(subEx->isLValue());
409     val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
410   }
411 }
412 
413 void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
414   // Treat ++/-- as a kill.
415   // Note we don't actually have to do anything if we don't have an observer,
416   // since a ++/-- acts as both a kill and a "use".
417   if (!observer)
418     return;
419 
420   switch (UO->getOpcode()) {
421   default:
422     return;
423   case UO_PostInc:
424   case UO_PostDec:
425   case UO_PreInc:
426   case UO_PreDec:
427     break;
428   }
429 
430   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
431     if (isa<VarDecl>(DR->getDecl())) {
432       // Treat ++/-- as a kill.
433       observer->observerKill(DR);
434     }
435 }
436 
437 LiveVariables::LivenessValues
438 LiveVariablesImpl::runOnBlock(const CFGBlock *block,
439                               LiveVariables::LivenessValues val,
440                               LiveVariables::Observer *obs) {
441 
442   TransferFunctions TF(*this, val, obs, block);
443 
444   // Visit the terminator (if any).
445   if (const Stmt *term = block->getTerminator())
446     TF.Visit(const_cast<Stmt*>(term));
447 
448   // Apply the transfer function for all Stmts in the block.
449   for (CFGBlock::const_reverse_iterator it = block->rbegin(),
450        ei = block->rend(); it != ei; ++it) {
451     const CFGElement &elem = *it;
452     if (!isa<CFGStmt>(elem))
453       continue;
454 
455     const Stmt *S = cast<CFGStmt>(elem).getStmt();
456     TF.Visit(const_cast<Stmt*>(S));
457     stmtsToLiveness[S] = val;
458   }
459   return val;
460 }
461 
462 void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
463   const CFG *cfg = getImpl(impl).analysisContext.getCFG();
464   for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
465     getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
466 }
467 
468 LiveVariables::LiveVariables(void *im) : impl(im) {}
469 
470 LiveVariables::~LiveVariables() {
471   delete (LiveVariablesImpl*) impl;
472 }
473 
474 LiveVariables *
475 LiveVariables::computeLiveness(AnalysisDeclContext &AC,
476                                  bool killAtAssign) {
477 
478   // No CFG?  Bail out.
479   CFG *cfg = AC.getCFG();
480   if (!cfg)
481     return 0;
482 
483   LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
484 
485   // Construct the dataflow worklist.  Enqueue the exit block as the
486   // start of the analysis.
487   DataflowWorklist worklist(*cfg, AC);
488   llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
489 
490   // FIXME: we should enqueue using post order.
491   for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
492     const CFGBlock *block = *it;
493     worklist.enqueueBlock(block);
494 
495     // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
496     // We need to do this because we lack context in the reverse analysis
497     // to determine if a DeclRefExpr appears in such a context, and thus
498     // doesn't constitute a "use".
499     if (killAtAssign)
500       for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
501            bi != be; ++bi) {
502         if (const CFGStmt *cs = bi->getAs<CFGStmt>()) {
503           if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(cs->getStmt())) {
504             if (BO->getOpcode() == BO_Assign) {
505               if (const DeclRefExpr *DR =
506                     dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
507                 LV->inAssignment[DR] = 1;
508               }
509             }
510           }
511         }
512       }
513   }
514 
515   worklist.sortWorklist();
516 
517   while (const CFGBlock *block = worklist.dequeue()) {
518     // Determine if the block's end value has changed.  If not, we
519     // have nothing left to do for this block.
520     LivenessValues &prevVal = LV->blocksEndToLiveness[block];
521 
522     // Merge the values of all successor blocks.
523     LivenessValues val;
524     for (CFGBlock::const_succ_iterator it = block->succ_begin(),
525                                        ei = block->succ_end(); it != ei; ++it) {
526       if (const CFGBlock *succ = *it) {
527         val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
528       }
529     }
530 
531     if (!everAnalyzedBlock[block->getBlockID()])
532       everAnalyzedBlock[block->getBlockID()] = true;
533     else if (prevVal.equals(val))
534       continue;
535 
536     prevVal = val;
537 
538     // Update the dataflow value for the start of this block.
539     LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
540 
541     // Enqueue the value to the predecessors.
542     worklist.enqueuePredecessors(block);
543   }
544 
545   return new LiveVariables(LV);
546 }
547 
548 static bool compare_entries(const CFGBlock *A, const CFGBlock *B) {
549   return A->getBlockID() < B->getBlockID();
550 }
551 
552 static bool compare_vd_entries(const Decl *A, const Decl *B) {
553   SourceLocation ALoc = A->getLocStart();
554   SourceLocation BLoc = B->getLocStart();
555   return ALoc.getRawEncoding() < BLoc.getRawEncoding();
556 }
557 
558 void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
559   getImpl(impl).dumpBlockLiveness(M);
560 }
561 
562 void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
563   std::vector<const CFGBlock *> vec;
564   for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
565        it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
566        it != ei; ++it) {
567     vec.push_back(it->first);
568   }
569   std::sort(vec.begin(), vec.end(), compare_entries);
570 
571   std::vector<const VarDecl*> declVec;
572 
573   for (std::vector<const CFGBlock *>::iterator
574         it = vec.begin(), ei = vec.end(); it != ei; ++it) {
575     llvm::errs() << "\n[ B" << (*it)->getBlockID()
576                  << " (live variables at block exit) ]\n";
577 
578     LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
579     declVec.clear();
580 
581     for (llvm::ImmutableSet<const VarDecl *>::iterator si =
582           vals.liveDecls.begin(),
583           se = vals.liveDecls.end(); si != se; ++si) {
584       declVec.push_back(*si);
585     }
586 
587     std::sort(declVec.begin(), declVec.end(), compare_vd_entries);
588 
589     for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
590          de = declVec.end(); di != de; ++di) {
591       llvm::errs() << " " << (*di)->getDeclName().getAsString()
592                    << " <";
593       (*di)->getLocation().dump(M);
594       llvm::errs() << ">\n";
595     }
596   }
597   llvm::errs() << "\n";
598 }
599 
600 const void *LiveVariables::getTag() { static int x; return &x; }
601 const void *RelaxedLiveVariables::getTag() { static int x; return &x; }
602