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