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