clang API Documentation
00001 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines the CFG and CFGBuilder classes for representing and 00011 // building Control-Flow Graphs (CFGs) from ASTs. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #include "llvm/Support/SaveAndRestore.h" 00016 #include "clang/Analysis/CFG.h" 00017 #include "clang/AST/DeclCXX.h" 00018 #include "clang/AST/StmtVisitor.h" 00019 #include "clang/AST/PrettyPrinter.h" 00020 #include "clang/AST/CharUnits.h" 00021 #include "clang/Basic/AttrKinds.h" 00022 #include "llvm/Support/GraphWriter.h" 00023 #include "llvm/Support/Allocator.h" 00024 #include "llvm/Support/Format.h" 00025 #include "llvm/ADT/DenseMap.h" 00026 #include "llvm/ADT/SmallPtrSet.h" 00027 #include "llvm/ADT/OwningPtr.h" 00028 00029 using namespace clang; 00030 00031 namespace { 00032 00033 static SourceLocation GetEndLoc(Decl *D) { 00034 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 00035 if (Expr *Ex = VD->getInit()) 00036 return Ex->getSourceRange().getEnd(); 00037 return D->getLocation(); 00038 } 00039 00040 class CFGBuilder; 00041 00042 /// The CFG builder uses a recursive algorithm to build the CFG. When 00043 /// we process an expression, sometimes we know that we must add the 00044 /// subexpressions as block-level expressions. For example: 00045 /// 00046 /// exp1 || exp2 00047 /// 00048 /// When processing the '||' expression, we know that exp1 and exp2 00049 /// need to be added as block-level expressions, even though they 00050 /// might not normally need to be. AddStmtChoice records this 00051 /// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then 00052 /// the builder has an option not to add a subexpression as a 00053 /// block-level expression. 00054 /// 00055 class AddStmtChoice { 00056 public: 00057 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 }; 00058 00059 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {} 00060 00061 bool alwaysAdd(CFGBuilder &builder, 00062 const Stmt *stmt) const; 00063 00064 /// Return a copy of this object, except with the 'always-add' bit 00065 /// set as specified. 00066 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const { 00067 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd); 00068 } 00069 00070 private: 00071 Kind kind; 00072 }; 00073 00074 /// LocalScope - Node in tree of local scopes created for C++ implicit 00075 /// destructor calls generation. It contains list of automatic variables 00076 /// declared in the scope and link to position in previous scope this scope 00077 /// began in. 00078 /// 00079 /// The process of creating local scopes is as follows: 00080 /// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), 00081 /// - Before processing statements in scope (e.g. CompoundStmt) create 00082 /// LocalScope object using CFGBuilder::ScopePos as link to previous scope 00083 /// and set CFGBuilder::ScopePos to the end of new scope, 00084 /// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points 00085 /// at this VarDecl, 00086 /// - For every normal (without jump) end of scope add to CFGBlock destructors 00087 /// for objects in the current scope, 00088 /// - For every jump add to CFGBlock destructors for objects 00089 /// between CFGBuilder::ScopePos and local scope position saved for jump 00090 /// target. Thanks to C++ restrictions on goto jumps we can be sure that 00091 /// jump target position will be on the path to root from CFGBuilder::ScopePos 00092 /// (adding any variable that doesn't need constructor to be called to 00093 /// LocalScope can break this assumption), 00094 /// 00095 class LocalScope { 00096 public: 00097 typedef BumpVector<VarDecl*> AutomaticVarsTy; 00098 00099 /// const_iterator - Iterates local scope backwards and jumps to previous 00100 /// scope on reaching the beginning of currently iterated scope. 00101 class const_iterator { 00102 const LocalScope* Scope; 00103 00104 /// VarIter is guaranteed to be greater then 0 for every valid iterator. 00105 /// Invalid iterator (with null Scope) has VarIter equal to 0. 00106 unsigned VarIter; 00107 00108 public: 00109 /// Create invalid iterator. Dereferencing invalid iterator is not allowed. 00110 /// Incrementing invalid iterator is allowed and will result in invalid 00111 /// iterator. 00112 const_iterator() 00113 : Scope(NULL), VarIter(0) {} 00114 00115 /// Create valid iterator. In case when S.Prev is an invalid iterator and 00116 /// I is equal to 0, this will create invalid iterator. 00117 const_iterator(const LocalScope& S, unsigned I) 00118 : Scope(&S), VarIter(I) { 00119 // Iterator to "end" of scope is not allowed. Handle it by going up 00120 // in scopes tree possibly up to invalid iterator in the root. 00121 if (VarIter == 0 && Scope) 00122 *this = Scope->Prev; 00123 } 00124 00125 VarDecl *const* operator->() const { 00126 assert (Scope && "Dereferencing invalid iterator is not allowed"); 00127 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 00128 return &Scope->Vars[VarIter - 1]; 00129 } 00130 VarDecl *operator*() const { 00131 return *this->operator->(); 00132 } 00133 00134 const_iterator &operator++() { 00135 if (!Scope) 00136 return *this; 00137 00138 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 00139 --VarIter; 00140 if (VarIter == 0) 00141 *this = Scope->Prev; 00142 return *this; 00143 } 00144 const_iterator operator++(int) { 00145 const_iterator P = *this; 00146 ++*this; 00147 return P; 00148 } 00149 00150 bool operator==(const const_iterator &rhs) const { 00151 return Scope == rhs.Scope && VarIter == rhs.VarIter; 00152 } 00153 bool operator!=(const const_iterator &rhs) const { 00154 return !(*this == rhs); 00155 } 00156 00157 operator bool() const { 00158 return *this != const_iterator(); 00159 } 00160 00161 int distance(const_iterator L); 00162 }; 00163 00164 friend class const_iterator; 00165 00166 private: 00167 BumpVectorContext ctx; 00168 00169 /// Automatic variables in order of declaration. 00170 AutomaticVarsTy Vars; 00171 /// Iterator to variable in previous scope that was declared just before 00172 /// begin of this scope. 00173 const_iterator Prev; 00174 00175 public: 00176 /// Constructs empty scope linked to previous scope in specified place. 00177 LocalScope(BumpVectorContext &ctx, const_iterator P) 00178 : ctx(ctx), Vars(ctx, 4), Prev(P) {} 00179 00180 /// Begin of scope in direction of CFG building (backwards). 00181 const_iterator begin() const { return const_iterator(*this, Vars.size()); } 00182 00183 void addVar(VarDecl *VD) { 00184 Vars.push_back(VD, ctx); 00185 } 00186 }; 00187 00188 /// distance - Calculates distance from this to L. L must be reachable from this 00189 /// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. 00190 /// number of scopes between this and L. 00191 int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { 00192 int D = 0; 00193 const_iterator F = *this; 00194 while (F.Scope != L.Scope) { 00195 assert (F != const_iterator() 00196 && "L iterator is not reachable from F iterator."); 00197 D += F.VarIter; 00198 F = F.Scope->Prev; 00199 } 00200 D += F.VarIter - L.VarIter; 00201 return D; 00202 } 00203 00204 /// BlockScopePosPair - Structure for specifying position in CFG during its 00205 /// build process. It consists of CFGBlock that specifies position in CFG graph 00206 /// and LocalScope::const_iterator that specifies position in LocalScope graph. 00207 struct BlockScopePosPair { 00208 BlockScopePosPair() : block(0) {} 00209 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos) 00210 : block(b), scopePosition(scopePos) {} 00211 00212 CFGBlock *block; 00213 LocalScope::const_iterator scopePosition; 00214 }; 00215 00216 /// TryResult - a class representing a variant over the values 00217 /// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool, 00218 /// and is used by the CFGBuilder to decide if a branch condition 00219 /// can be decided up front during CFG construction. 00220 class TryResult { 00221 int X; 00222 public: 00223 TryResult(bool b) : X(b ? 1 : 0) {} 00224 TryResult() : X(-1) {} 00225 00226 bool isTrue() const { return X == 1; } 00227 bool isFalse() const { return X == 0; } 00228 bool isKnown() const { return X >= 0; } 00229 void negate() { 00230 assert(isKnown()); 00231 X ^= 0x1; 00232 } 00233 }; 00234 00235 /// CFGBuilder - This class implements CFG construction from an AST. 00236 /// The builder is stateful: an instance of the builder should be used to only 00237 /// construct a single CFG. 00238 /// 00239 /// Example usage: 00240 /// 00241 /// CFGBuilder builder; 00242 /// CFG* cfg = builder.BuildAST(stmt1); 00243 /// 00244 /// CFG construction is done via a recursive walk of an AST. We actually parse 00245 /// the AST in reverse order so that the successor of a basic block is 00246 /// constructed prior to its predecessor. This allows us to nicely capture 00247 /// implicit fall-throughs without extra basic blocks. 00248 /// 00249 class CFGBuilder { 00250 typedef BlockScopePosPair JumpTarget; 00251 typedef BlockScopePosPair JumpSource; 00252 00253 ASTContext *Context; 00254 OwningPtr<CFG> cfg; 00255 00256 CFGBlock *Block; 00257 CFGBlock *Succ; 00258 JumpTarget ContinueJumpTarget; 00259 JumpTarget BreakJumpTarget; 00260 CFGBlock *SwitchTerminatedBlock; 00261 CFGBlock *DefaultCaseBlock; 00262 CFGBlock *TryTerminatedBlock; 00263 00264 // Current position in local scope. 00265 LocalScope::const_iterator ScopePos; 00266 00267 // LabelMap records the mapping from Label expressions to their jump targets. 00268 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy; 00269 LabelMapTy LabelMap; 00270 00271 // A list of blocks that end with a "goto" that must be backpatched to their 00272 // resolved targets upon completion of CFG construction. 00273 typedef std::vector<JumpSource> BackpatchBlocksTy; 00274 BackpatchBlocksTy BackpatchBlocks; 00275 00276 // A list of labels whose address has been taken (for indirect gotos). 00277 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy; 00278 LabelSetTy AddressTakenLabels; 00279 00280 bool badCFG; 00281 const CFG::BuildOptions &BuildOpts; 00282 00283 // State to track for building switch statements. 00284 bool switchExclusivelyCovered; 00285 Expr::EvalResult *switchCond; 00286 00287 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry; 00288 const Stmt *lastLookup; 00289 00290 // Caches boolean evaluations of expressions to avoid multiple re-evaluations 00291 // during construction of branches for chained logical operators. 00292 typedef llvm::DenseMap<Expr *, TryResult> CachedBoolEvalsTy; 00293 CachedBoolEvalsTy CachedBoolEvals; 00294 00295 public: 00296 explicit CFGBuilder(ASTContext *astContext, 00297 const CFG::BuildOptions &buildOpts) 00298 : Context(astContext), cfg(new CFG()), // crew a new CFG 00299 Block(NULL), Succ(NULL), 00300 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL), 00301 TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts), 00302 switchExclusivelyCovered(false), switchCond(0), 00303 cachedEntry(0), lastLookup(0) {} 00304 00305 // buildCFG - Used by external clients to construct the CFG. 00306 CFG* buildCFG(const Decl *D, Stmt *Statement); 00307 00308 bool alwaysAdd(const Stmt *stmt); 00309 00310 private: 00311 // Visitors to walk an AST and construct the CFG. 00312 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 00313 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 00314 CFGBlock *VisitBreakStmt(BreakStmt *B); 00315 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 00316 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, 00317 AddStmtChoice asc); 00318 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 00319 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 00320 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); 00321 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 00322 AddStmtChoice asc); 00323 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); 00324 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 00325 AddStmtChoice asc); 00326 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 00327 AddStmtChoice asc); 00328 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 00329 CFGBlock *VisitCaseStmt(CaseStmt *C); 00330 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 00331 CFGBlock *VisitCompoundStmt(CompoundStmt *C); 00332 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, 00333 AddStmtChoice asc); 00334 CFGBlock *VisitContinueStmt(ContinueStmt *C); 00335 CFGBlock *VisitDeclStmt(DeclStmt *DS); 00336 CFGBlock *VisitDeclSubExpr(DeclStmt *DS); 00337 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 00338 CFGBlock *VisitDoStmt(DoStmt *D); 00339 CFGBlock *VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc); 00340 CFGBlock *VisitForStmt(ForStmt *F); 00341 CFGBlock *VisitGotoStmt(GotoStmt *G); 00342 CFGBlock *VisitIfStmt(IfStmt *I); 00343 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); 00344 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 00345 CFGBlock *VisitLabelStmt(LabelStmt *L); 00346 CFGBlock *VisitLambdaExpr(LambdaExpr *L); 00347 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 00348 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 00349 CFGBlock *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 00350 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 00351 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 00352 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 00353 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 00354 CFGBlock *VisitReturnStmt(ReturnStmt *R); 00355 CFGBlock *VisitPseudoObjectExpr(PseudoObjectExpr *E); 00356 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 00357 AddStmtChoice asc); 00358 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 00359 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 00360 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); 00361 CFGBlock *VisitWhileStmt(WhileStmt *W); 00362 00363 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd); 00364 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); 00365 CFGBlock *VisitChildren(Stmt *S); 00366 CFGBlock *VisitNoRecurse(Expr *E, AddStmtChoice asc); 00367 00368 // Visitors to walk an AST and generate destructors of temporaries in 00369 // full expression. 00370 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false); 00371 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E); 00372 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E); 00373 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E, 00374 bool BindToTemporary); 00375 CFGBlock * 00376 VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E, 00377 bool BindToTemporary); 00378 00379 // NYS == Not Yet Supported 00380 CFGBlock *NYS() { 00381 badCFG = true; 00382 return Block; 00383 } 00384 00385 void autoCreateBlock() { if (!Block) Block = createBlock(); } 00386 CFGBlock *createBlock(bool add_successor = true); 00387 CFGBlock *createNoReturnBlock(); 00388 00389 CFGBlock *addStmt(Stmt *S) { 00390 return Visit(S, AddStmtChoice::AlwaysAdd); 00391 } 00392 CFGBlock *addInitializer(CXXCtorInitializer *I); 00393 void addAutomaticObjDtors(LocalScope::const_iterator B, 00394 LocalScope::const_iterator E, Stmt *S); 00395 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD); 00396 00397 // Local scopes creation. 00398 LocalScope* createOrReuseLocalScope(LocalScope* Scope); 00399 00400 void addLocalScopeForStmt(Stmt *S); 00401 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL); 00402 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL); 00403 00404 void addLocalScopeAndDtors(Stmt *S); 00405 00406 // Interface to CFGBlock - adding CFGElements. 00407 void appendStmt(CFGBlock *B, const Stmt *S) { 00408 if (alwaysAdd(S) && cachedEntry) 00409 cachedEntry->second = B; 00410 00411 // All block-level expressions should have already been IgnoreParens()ed. 00412 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S); 00413 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext()); 00414 } 00415 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) { 00416 B->appendInitializer(I, cfg->getBumpVectorContext()); 00417 } 00418 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) { 00419 B->appendBaseDtor(BS, cfg->getBumpVectorContext()); 00420 } 00421 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) { 00422 B->appendMemberDtor(FD, cfg->getBumpVectorContext()); 00423 } 00424 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { 00425 B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); 00426 } 00427 void appendAutomaticObjDtor(CFGBlock *B, VarDecl *VD, Stmt *S) { 00428 B->appendAutomaticObjDtor(VD, S, cfg->getBumpVectorContext()); 00429 } 00430 00431 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 00432 LocalScope::const_iterator B, LocalScope::const_iterator E); 00433 00434 void addSuccessor(CFGBlock *B, CFGBlock *S) { 00435 B->addSuccessor(S, cfg->getBumpVectorContext()); 00436 } 00437 00438 /// Try and evaluate an expression to an integer constant. 00439 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { 00440 if (!BuildOpts.PruneTriviallyFalseEdges) 00441 return false; 00442 return !S->isTypeDependent() && 00443 !S->isValueDependent() && 00444 S->EvaluateAsRValue(outResult, *Context); 00445 } 00446 00447 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 00448 /// if we can evaluate to a known value, otherwise return -1. 00449 TryResult tryEvaluateBool(Expr *S) { 00450 if (!BuildOpts.PruneTriviallyFalseEdges || 00451 S->isTypeDependent() || S->isValueDependent()) 00452 return TryResult(); 00453 00454 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(S)) { 00455 if (Bop->isLogicalOp()) { 00456 // Check the cache first. 00457 CachedBoolEvalsTy::iterator I = CachedBoolEvals.find(S); 00458 if (I != CachedBoolEvals.end()) 00459 return I->second; // already in map; 00460 00461 // Retrieve result at first, or the map might be updated. 00462 TryResult Result = evaluateAsBooleanConditionNoCache(S); 00463 CachedBoolEvals[S] = Result; // update or insert 00464 return Result; 00465 } 00466 } 00467 00468 return evaluateAsBooleanConditionNoCache(S); 00469 } 00470 00471 /// \brief Evaluate as boolean \param E without using the cache. 00472 TryResult evaluateAsBooleanConditionNoCache(Expr *E) { 00473 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(E)) { 00474 if (Bop->isLogicalOp()) { 00475 TryResult LHS = tryEvaluateBool(Bop->getLHS()); 00476 if (LHS.isKnown()) { 00477 // We were able to evaluate the LHS, see if we can get away with not 00478 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1 00479 if (LHS.isTrue() == (Bop->getOpcode() == BO_LOr)) 00480 return LHS.isTrue(); 00481 00482 TryResult RHS = tryEvaluateBool(Bop->getRHS()); 00483 if (RHS.isKnown()) { 00484 if (Bop->getOpcode() == BO_LOr) 00485 return LHS.isTrue() || RHS.isTrue(); 00486 else 00487 return LHS.isTrue() && RHS.isTrue(); 00488 } 00489 } else { 00490 TryResult RHS = tryEvaluateBool(Bop->getRHS()); 00491 if (RHS.isKnown()) { 00492 // We can't evaluate the LHS; however, sometimes the result 00493 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1. 00494 if (RHS.isTrue() == (Bop->getOpcode() == BO_LOr)) 00495 return RHS.isTrue(); 00496 } 00497 } 00498 00499 return TryResult(); 00500 } 00501 } 00502 00503 bool Result; 00504 if (E->EvaluateAsBooleanCondition(Result, *Context)) 00505 return Result; 00506 00507 return TryResult(); 00508 } 00509 00510 }; 00511 00512 inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, 00513 const Stmt *stmt) const { 00514 return builder.alwaysAdd(stmt) || kind == AlwaysAdd; 00515 } 00516 00517 bool CFGBuilder::alwaysAdd(const Stmt *stmt) { 00518 bool shouldAdd = BuildOpts.alwaysAdd(stmt); 00519 00520 if (!BuildOpts.forcedBlkExprs) 00521 return shouldAdd; 00522 00523 if (lastLookup == stmt) { 00524 if (cachedEntry) { 00525 assert(cachedEntry->first == stmt); 00526 return true; 00527 } 00528 return shouldAdd; 00529 } 00530 00531 lastLookup = stmt; 00532 00533 // Perform the lookup! 00534 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs; 00535 00536 if (!fb) { 00537 // No need to update 'cachedEntry', since it will always be null. 00538 assert(cachedEntry == 0); 00539 return shouldAdd; 00540 } 00541 00542 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt); 00543 if (itr == fb->end()) { 00544 cachedEntry = 0; 00545 return shouldAdd; 00546 } 00547 00548 cachedEntry = &*itr; 00549 return true; 00550 } 00551 00552 // FIXME: Add support for dependent-sized array types in C++? 00553 // Does it even make sense to build a CFG for an uninstantiated template? 00554 static const VariableArrayType *FindVA(const Type *t) { 00555 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) { 00556 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt)) 00557 if (vat->getSizeExpr()) 00558 return vat; 00559 00560 t = vt->getElementType().getTypePtr(); 00561 } 00562 00563 return 0; 00564 } 00565 00566 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 00567 /// arbitrary statement. Examples include a single expression or a function 00568 /// body (compound statement). The ownership of the returned CFG is 00569 /// transferred to the caller. If CFG construction fails, this method returns 00570 /// NULL. 00571 CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { 00572 assert(cfg.get()); 00573 if (!Statement) 00574 return NULL; 00575 00576 // Create an empty block that will serve as the exit block for the CFG. Since 00577 // this is the first block added to the CFG, it will be implicitly registered 00578 // as the exit block. 00579 Succ = createBlock(); 00580 assert(Succ == &cfg->getExit()); 00581 Block = NULL; // the EXIT block is empty. Create all other blocks lazily. 00582 00583 if (BuildOpts.AddImplicitDtors) 00584 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D)) 00585 addImplicitDtorsForDestructor(DD); 00586 00587 // Visit the statements and create the CFG. 00588 CFGBlock *B = addStmt(Statement); 00589 00590 if (badCFG) 00591 return NULL; 00592 00593 // For C++ constructor add initializers to CFG. 00594 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { 00595 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(), 00596 E = CD->init_rend(); I != E; ++I) { 00597 B = addInitializer(*I); 00598 if (badCFG) 00599 return NULL; 00600 } 00601 } 00602 00603 if (B) 00604 Succ = B; 00605 00606 // Backpatch the gotos whose label -> block mappings we didn't know when we 00607 // encountered them. 00608 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 00609 E = BackpatchBlocks.end(); I != E; ++I ) { 00610 00611 CFGBlock *B = I->block; 00612 GotoStmt *G = cast<GotoStmt>(B->getTerminator()); 00613 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 00614 00615 // If there is no target for the goto, then we are looking at an 00616 // incomplete AST. Handle this by not registering a successor. 00617 if (LI == LabelMap.end()) continue; 00618 00619 JumpTarget JT = LI->second; 00620 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition, 00621 JT.scopePosition); 00622 addSuccessor(B, JT.block); 00623 } 00624 00625 // Add successors to the Indirect Goto Dispatch block (if we have one). 00626 if (CFGBlock *B = cfg->getIndirectGotoBlock()) 00627 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 00628 E = AddressTakenLabels.end(); I != E; ++I ) { 00629 00630 // Lookup the target block. 00631 LabelMapTy::iterator LI = LabelMap.find(*I); 00632 00633 // If there is no target block that contains label, then we are looking 00634 // at an incomplete AST. Handle this by not registering a successor. 00635 if (LI == LabelMap.end()) continue; 00636 00637 addSuccessor(B, LI->second.block); 00638 } 00639 00640 // Create an empty entry block that has no predecessors. 00641 cfg->setEntry(createBlock()); 00642 00643 return cfg.take(); 00644 } 00645 00646 /// createBlock - Used to lazily create blocks that are connected 00647 /// to the current (global) succcessor. 00648 CFGBlock *CFGBuilder::createBlock(bool add_successor) { 00649 CFGBlock *B = cfg->createBlock(); 00650 if (add_successor && Succ) 00651 addSuccessor(B, Succ); 00652 return B; 00653 } 00654 00655 /// createNoReturnBlock - Used to create a block is a 'noreturn' point in the 00656 /// CFG. It is *not* connected to the current (global) successor, and instead 00657 /// directly tied to the exit block in order to be reachable. 00658 CFGBlock *CFGBuilder::createNoReturnBlock() { 00659 CFGBlock *B = createBlock(false); 00660 B->setHasNoReturnElement(); 00661 addSuccessor(B, &cfg->getExit()); 00662 return B; 00663 } 00664 00665 /// addInitializer - Add C++ base or member initializer element to CFG. 00666 CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { 00667 if (!BuildOpts.AddInitializers) 00668 return Block; 00669 00670 bool IsReference = false; 00671 bool HasTemporaries = false; 00672 00673 // Destructors of temporaries in initialization expression should be called 00674 // after initialization finishes. 00675 Expr *Init = I->getInit(); 00676 if (Init) { 00677 if (FieldDecl *FD = I->getAnyMember()) 00678 IsReference = FD->getType()->isReferenceType(); 00679 HasTemporaries = isa<ExprWithCleanups>(Init); 00680 00681 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 00682 // Generate destructors for temporaries in initialization expression. 00683 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 00684 IsReference); 00685 } 00686 } 00687 00688 autoCreateBlock(); 00689 appendInitializer(Block, I); 00690 00691 if (Init) { 00692 if (HasTemporaries) { 00693 // For expression with temporaries go directly to subexpression to omit 00694 // generating destructors for the second time. 00695 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 00696 } 00697 return Visit(Init); 00698 } 00699 00700 return Block; 00701 } 00702 00703 /// \brief Retrieve the type of the temporary object whose lifetime was 00704 /// extended by a local reference with the given initializer. 00705 static QualType getReferenceInitTemporaryType(ASTContext &Context, 00706 const Expr *Init) { 00707 while (true) { 00708 // Skip parentheses. 00709 Init = Init->IgnoreParens(); 00710 00711 // Skip through cleanups. 00712 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init)) { 00713 Init = EWC->getSubExpr(); 00714 continue; 00715 } 00716 00717 // Skip through the temporary-materialization expression. 00718 if (const MaterializeTemporaryExpr *MTE 00719 = dyn_cast<MaterializeTemporaryExpr>(Init)) { 00720 Init = MTE->GetTemporaryExpr(); 00721 continue; 00722 } 00723 00724 // Skip derived-to-base and no-op casts. 00725 if (const CastExpr *CE = dyn_cast<CastExpr>(Init)) { 00726 if ((CE->getCastKind() == CK_DerivedToBase || 00727 CE->getCastKind() == CK_UncheckedDerivedToBase || 00728 CE->getCastKind() == CK_NoOp) && 00729 Init->getType()->isRecordType()) { 00730 Init = CE->getSubExpr(); 00731 continue; 00732 } 00733 } 00734 00735 // Skip member accesses into rvalues. 00736 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Init)) { 00737 if (!ME->isArrow() && ME->getBase()->isRValue()) { 00738 Init = ME->getBase(); 00739 continue; 00740 } 00741 } 00742 00743 break; 00744 } 00745 00746 return Init->getType(); 00747 } 00748 00749 /// addAutomaticObjDtors - Add to current block automatic objects destructors 00750 /// for objects in range of local scope positions. Use S as trigger statement 00751 /// for destructors. 00752 void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, 00753 LocalScope::const_iterator E, Stmt *S) { 00754 if (!BuildOpts.AddImplicitDtors) 00755 return; 00756 00757 if (B == E) 00758 return; 00759 00760 // We need to append the destructors in reverse order, but any one of them 00761 // may be a no-return destructor which changes the CFG. As a result, buffer 00762 // this sequence up and replay them in reverse order when appending onto the 00763 // CFGBlock(s). 00764 SmallVector<VarDecl*, 10> Decls; 00765 Decls.reserve(B.distance(E)); 00766 for (LocalScope::const_iterator I = B; I != E; ++I) 00767 Decls.push_back(*I); 00768 00769 for (SmallVectorImpl<VarDecl*>::reverse_iterator I = Decls.rbegin(), 00770 E = Decls.rend(); 00771 I != E; ++I) { 00772 // If this destructor is marked as a no-return destructor, we need to 00773 // create a new block for the destructor which does not have as a successor 00774 // anything built thus far: control won't flow out of this block. 00775 QualType Ty; 00776 if ((*I)->getType()->isReferenceType()) { 00777 Ty = getReferenceInitTemporaryType(*Context, (*I)->getInit()); 00778 } else { 00779 Ty = Context->getBaseElementType((*I)->getType()); 00780 } 00781 00782 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 00783 if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) 00784 Block = createNoReturnBlock(); 00785 else 00786 autoCreateBlock(); 00787 00788 appendAutomaticObjDtor(Block, *I, S); 00789 } 00790 } 00791 00792 /// addImplicitDtorsForDestructor - Add implicit destructors generated for 00793 /// base and member objects in destructor. 00794 void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { 00795 assert (BuildOpts.AddImplicitDtors 00796 && "Can be called only when dtors should be added"); 00797 const CXXRecordDecl *RD = DD->getParent(); 00798 00799 // At the end destroy virtual base objects. 00800 for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(), 00801 VE = RD->vbases_end(); VI != VE; ++VI) { 00802 const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl(); 00803 if (!CD->hasTrivialDestructor()) { 00804 autoCreateBlock(); 00805 appendBaseDtor(Block, VI); 00806 } 00807 } 00808 00809 // Before virtual bases destroy direct base objects. 00810 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 00811 BE = RD->bases_end(); BI != BE; ++BI) { 00812 if (!BI->isVirtual()) { 00813 const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl(); 00814 if (!CD->hasTrivialDestructor()) { 00815 autoCreateBlock(); 00816 appendBaseDtor(Block, BI); 00817 } 00818 } 00819 } 00820 00821 // First destroy member objects. 00822 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 00823 FE = RD->field_end(); FI != FE; ++FI) { 00824 // Check for constant size array. Set type to array element type. 00825 QualType QT = FI->getType(); 00826 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 00827 if (AT->getSize() == 0) 00828 continue; 00829 QT = AT->getElementType(); 00830 } 00831 00832 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 00833 if (!CD->hasTrivialDestructor()) { 00834 autoCreateBlock(); 00835 appendMemberDtor(Block, &*FI); 00836 } 00837 } 00838 } 00839 00840 /// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either 00841 /// way return valid LocalScope object. 00842 LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { 00843 if (!Scope) { 00844 llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); 00845 Scope = alloc.Allocate<LocalScope>(); 00846 BumpVectorContext ctx(alloc); 00847 new (Scope) LocalScope(ctx, ScopePos); 00848 } 00849 return Scope; 00850 } 00851 00852 /// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement 00853 /// that should create implicit scope (e.g. if/else substatements). 00854 void CFGBuilder::addLocalScopeForStmt(Stmt *S) { 00855 if (!BuildOpts.AddImplicitDtors) 00856 return; 00857 00858 LocalScope *Scope = 0; 00859 00860 // For compound statement we will be creating explicit scope. 00861 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 00862 for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end() 00863 ; BI != BE; ++BI) { 00864 Stmt *SI = (*BI)->stripLabelLikeStatements(); 00865 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) 00866 Scope = addLocalScopeForDeclStmt(DS, Scope); 00867 } 00868 return; 00869 } 00870 00871 // For any other statement scope will be implicit and as such will be 00872 // interesting only for DeclStmt. 00873 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) 00874 addLocalScopeForDeclStmt(DS); 00875 } 00876 00877 /// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will 00878 /// reuse Scope if not NULL. 00879 LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, 00880 LocalScope* Scope) { 00881 if (!BuildOpts.AddImplicitDtors) 00882 return Scope; 00883 00884 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end() 00885 ; DI != DE; ++DI) { 00886 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) 00887 Scope = addLocalScopeForVarDecl(VD, Scope); 00888 } 00889 return Scope; 00890 } 00891 00892 /// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will 00893 /// create add scope for automatic objects and temporary objects bound to 00894 /// const reference. Will reuse Scope if not NULL. 00895 LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, 00896 LocalScope* Scope) { 00897 if (!BuildOpts.AddImplicitDtors) 00898 return Scope; 00899 00900 // Check if variable is local. 00901 switch (VD->getStorageClass()) { 00902 case SC_None: 00903 case SC_Auto: 00904 case SC_Register: 00905 break; 00906 default: return Scope; 00907 } 00908 00909 // Check for const references bound to temporary. Set type to pointee. 00910 QualType QT = VD->getType(); 00911 if (QT.getTypePtr()->isReferenceType()) { 00912 if (!VD->extendsLifetimeOfTemporary()) 00913 return Scope; 00914 00915 QT = getReferenceInitTemporaryType(*Context, VD->getInit()); 00916 } 00917 00918 // Check for constant size array. Set type to array element type. 00919 while (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 00920 if (AT->getSize() == 0) 00921 return Scope; 00922 QT = AT->getElementType(); 00923 } 00924 00925 // Check if type is a C++ class with non-trivial destructor. 00926 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 00927 if (!CD->hasTrivialDestructor()) { 00928 // Add the variable to scope 00929 Scope = createOrReuseLocalScope(Scope); 00930 Scope->addVar(VD); 00931 ScopePos = Scope->begin(); 00932 } 00933 return Scope; 00934 } 00935 00936 /// addLocalScopeAndDtors - For given statement add local scope for it and 00937 /// add destructors that will cleanup the scope. Will reuse Scope if not NULL. 00938 void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { 00939 if (!BuildOpts.AddImplicitDtors) 00940 return; 00941 00942 LocalScope::const_iterator scopeBeginPos = ScopePos; 00943 addLocalScopeForStmt(S); 00944 addAutomaticObjDtors(ScopePos, scopeBeginPos, S); 00945 } 00946 00947 /// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 00948 /// variables with automatic storage duration to CFGBlock's elements vector. 00949 /// Elements will be prepended to physical beginning of the vector which 00950 /// happens to be logical end. Use blocks terminator as statement that specifies 00951 /// destructors call site. 00952 /// FIXME: This mechanism for adding automatic destructors doesn't handle 00953 /// no-return destructors properly. 00954 void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 00955 LocalScope::const_iterator B, LocalScope::const_iterator E) { 00956 BumpVectorContext &C = cfg->getBumpVectorContext(); 00957 CFGBlock::iterator InsertPos 00958 = Blk->beginAutomaticObjDtorsInsert(Blk->end(), B.distance(E), C); 00959 for (LocalScope::const_iterator I = B; I != E; ++I) 00960 InsertPos = Blk->insertAutomaticObjDtor(InsertPos, *I, 00961 Blk->getTerminator()); 00962 } 00963 00964 /// Visit - Walk the subtree of a statement and add extra 00965 /// blocks for ternary operators, &&, and ||. We also process "," and 00966 /// DeclStmts (which may contain nested control-flow). 00967 CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { 00968 if (!S) { 00969 badCFG = true; 00970 return 0; 00971 } 00972 00973 if (Expr *E = dyn_cast<Expr>(S)) 00974 S = E->IgnoreParens(); 00975 00976 switch (S->getStmtClass()) { 00977 default: 00978 return VisitStmt(S, asc); 00979 00980 case Stmt::AddrLabelExprClass: 00981 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 00982 00983 case Stmt::BinaryConditionalOperatorClass: 00984 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); 00985 00986 case Stmt::BinaryOperatorClass: 00987 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 00988 00989 case Stmt::BlockExprClass: 00990 return VisitNoRecurse(cast<Expr>(S), asc); 00991 00992 case Stmt::BreakStmtClass: 00993 return VisitBreakStmt(cast<BreakStmt>(S)); 00994 00995 case Stmt::CallExprClass: 00996 case Stmt::CXXOperatorCallExprClass: 00997 case Stmt::CXXMemberCallExprClass: 00998 case Stmt::UserDefinedLiteralClass: 00999 return VisitCallExpr(cast<CallExpr>(S), asc); 01000 01001 case Stmt::CaseStmtClass: 01002 return VisitCaseStmt(cast<CaseStmt>(S)); 01003 01004 case Stmt::ChooseExprClass: 01005 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 01006 01007 case Stmt::CompoundStmtClass: 01008 return VisitCompoundStmt(cast<CompoundStmt>(S)); 01009 01010 case Stmt::ConditionalOperatorClass: 01011 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 01012 01013 case Stmt::ContinueStmtClass: 01014 return VisitContinueStmt(cast<ContinueStmt>(S)); 01015 01016 case Stmt::CXXCatchStmtClass: 01017 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 01018 01019 case Stmt::ExprWithCleanupsClass: 01020 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc); 01021 01022 case Stmt::CXXBindTemporaryExprClass: 01023 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); 01024 01025 case Stmt::CXXConstructExprClass: 01026 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); 01027 01028 case Stmt::CXXFunctionalCastExprClass: 01029 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); 01030 01031 case Stmt::CXXTemporaryObjectExprClass: 01032 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); 01033 01034 case Stmt::CXXThrowExprClass: 01035 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 01036 01037 case Stmt::CXXTryStmtClass: 01038 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 01039 01040 case Stmt::CXXForRangeStmtClass: 01041 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 01042 01043 case Stmt::DeclStmtClass: 01044 return VisitDeclStmt(cast<DeclStmt>(S)); 01045 01046 case Stmt::DefaultStmtClass: 01047 return VisitDefaultStmt(cast<DefaultStmt>(S)); 01048 01049 case Stmt::DoStmtClass: 01050 return VisitDoStmt(cast<DoStmt>(S)); 01051 01052 case Stmt::ForStmtClass: 01053 return VisitForStmt(cast<ForStmt>(S)); 01054 01055 case Stmt::GotoStmtClass: 01056 return VisitGotoStmt(cast<GotoStmt>(S)); 01057 01058 case Stmt::IfStmtClass: 01059 return VisitIfStmt(cast<IfStmt>(S)); 01060 01061 case Stmt::ImplicitCastExprClass: 01062 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); 01063 01064 case Stmt::IndirectGotoStmtClass: 01065 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 01066 01067 case Stmt::LabelStmtClass: 01068 return VisitLabelStmt(cast<LabelStmt>(S)); 01069 01070 case Stmt::LambdaExprClass: 01071 return VisitLambdaExpr(cast<LambdaExpr>(S), asc); 01072 01073 case Stmt::MemberExprClass: 01074 return VisitMemberExpr(cast<MemberExpr>(S), asc); 01075 01076 case Stmt::NullStmtClass: 01077 return Block; 01078 01079 case Stmt::ObjCAtCatchStmtClass: 01080 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 01081 01082 case Stmt::ObjCAutoreleasePoolStmtClass: 01083 return VisitObjCAutoreleasePoolStmt(cast<ObjCAutoreleasePoolStmt>(S)); 01084 01085 case Stmt::ObjCAtSynchronizedStmtClass: 01086 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 01087 01088 case Stmt::ObjCAtThrowStmtClass: 01089 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 01090 01091 case Stmt::ObjCAtTryStmtClass: 01092 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 01093 01094 case Stmt::ObjCForCollectionStmtClass: 01095 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 01096 01097 case Stmt::OpaqueValueExprClass: 01098 return Block; 01099 01100 case Stmt::PseudoObjectExprClass: 01101 return VisitPseudoObjectExpr(cast<PseudoObjectExpr>(S)); 01102 01103 case Stmt::ReturnStmtClass: 01104 return VisitReturnStmt(cast<ReturnStmt>(S)); 01105 01106 case Stmt::UnaryExprOrTypeTraitExprClass: 01107 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 01108 asc); 01109 01110 case Stmt::StmtExprClass: 01111 return VisitStmtExpr(cast<StmtExpr>(S), asc); 01112 01113 case Stmt::SwitchStmtClass: 01114 return VisitSwitchStmt(cast<SwitchStmt>(S)); 01115 01116 case Stmt::UnaryOperatorClass: 01117 return VisitUnaryOperator(cast<UnaryOperator>(S), asc); 01118 01119 case Stmt::WhileStmtClass: 01120 return VisitWhileStmt(cast<WhileStmt>(S)); 01121 } 01122 } 01123 01124 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { 01125 if (asc.alwaysAdd(*this, S)) { 01126 autoCreateBlock(); 01127 appendStmt(Block, S); 01128 } 01129 01130 return VisitChildren(S); 01131 } 01132 01133 /// VisitChildren - Visit the children of a Stmt. 01134 CFGBlock *CFGBuilder::VisitChildren(Stmt *Terminator) { 01135 CFGBlock *lastBlock = Block; 01136 for (Stmt::child_range I = Terminator->children(); I; ++I) 01137 if (Stmt *child = *I) 01138 if (CFGBlock *b = Visit(child)) 01139 lastBlock = b; 01140 01141 return lastBlock; 01142 } 01143 01144 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, 01145 AddStmtChoice asc) { 01146 AddressTakenLabels.insert(A->getLabel()); 01147 01148 if (asc.alwaysAdd(*this, A)) { 01149 autoCreateBlock(); 01150 appendStmt(Block, A); 01151 } 01152 01153 return Block; 01154 } 01155 01156 CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, 01157 AddStmtChoice asc) { 01158 if (asc.alwaysAdd(*this, U)) { 01159 autoCreateBlock(); 01160 appendStmt(Block, U); 01161 } 01162 01163 return Visit(U->getSubExpr(), AddStmtChoice()); 01164 } 01165 01166 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, 01167 AddStmtChoice asc) { 01168 if (B->isLogicalOp()) { // && or || 01169 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 01170 appendStmt(ConfluenceBlock, B); 01171 01172 if (badCFG) 01173 return 0; 01174 01175 // create the block evaluating the LHS 01176 CFGBlock *LHSBlock = createBlock(false); 01177 LHSBlock->setTerminator(B); 01178 01179 // create the block evaluating the RHS 01180 Succ = ConfluenceBlock; 01181 Block = NULL; 01182 CFGBlock *RHSBlock = addStmt(B->getRHS()); 01183 01184 if (RHSBlock) { 01185 if (badCFG) 01186 return 0; 01187 } else { 01188 // Create an empty block for cases where the RHS doesn't require 01189 // any explicit statements in the CFG. 01190 RHSBlock = createBlock(); 01191 } 01192 01193 // Generate the blocks for evaluating the LHS. 01194 Block = LHSBlock; 01195 CFGBlock *EntryLHSBlock = addStmt(B->getLHS()); 01196 01197 // See if this is a known constant. 01198 TryResult KnownVal = tryEvaluateBool(B->getLHS()); 01199 if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr)) 01200 KnownVal.negate(); 01201 01202 // Now link the LHSBlock with RHSBlock. 01203 if (B->getOpcode() == BO_LOr) { 01204 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 01205 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 01206 } else { 01207 assert(B->getOpcode() == BO_LAnd); 01208 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 01209 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 01210 } 01211 01212 return EntryLHSBlock; 01213 } 01214 01215 if (B->getOpcode() == BO_Comma) { // , 01216 autoCreateBlock(); 01217 appendStmt(Block, B); 01218 addStmt(B->getRHS()); 01219 return addStmt(B->getLHS()); 01220 } 01221 01222 if (B->isAssignmentOp()) { 01223 if (asc.alwaysAdd(*this, B)) { 01224 autoCreateBlock(); 01225 appendStmt(Block, B); 01226 } 01227 Visit(B->getLHS()); 01228 return Visit(B->getRHS()); 01229 } 01230 01231 if (asc.alwaysAdd(*this, B)) { 01232 autoCreateBlock(); 01233 appendStmt(Block, B); 01234 } 01235 01236 CFGBlock *RBlock = Visit(B->getRHS()); 01237 CFGBlock *LBlock = Visit(B->getLHS()); 01238 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr 01239 // containing a DoStmt, and the LHS doesn't create a new block, then we should 01240 // return RBlock. Otherwise we'll incorrectly return NULL. 01241 return (LBlock ? LBlock : RBlock); 01242 } 01243 01244 CFGBlock *CFGBuilder::VisitNoRecurse(Expr *E, AddStmtChoice asc) { 01245 if (asc.alwaysAdd(*this, E)) { 01246 autoCreateBlock(); 01247 appendStmt(Block, E); 01248 } 01249 return Block; 01250 } 01251 01252 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 01253 // "break" is a control-flow statement. Thus we stop processing the current 01254 // block. 01255 if (badCFG) 01256 return 0; 01257 01258 // Now create a new block that ends with the break statement. 01259 Block = createBlock(false); 01260 Block->setTerminator(B); 01261 01262 // If there is no target for the break, then we are looking at an incomplete 01263 // AST. This means that the CFG cannot be constructed. 01264 if (BreakJumpTarget.block) { 01265 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B); 01266 addSuccessor(Block, BreakJumpTarget.block); 01267 } else 01268 badCFG = true; 01269 01270 01271 return Block; 01272 } 01273 01274 static bool CanThrow(Expr *E, ASTContext &Ctx) { 01275 QualType Ty = E->getType(); 01276 if (Ty->isFunctionPointerType()) 01277 Ty = Ty->getAs<PointerType>()->getPointeeType(); 01278 else if (Ty->isBlockPointerType()) 01279 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 01280 01281 const FunctionType *FT = Ty->getAs<FunctionType>(); 01282 if (FT) { 01283 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 01284 if (Proto->getExceptionSpecType() != EST_Uninstantiated && 01285 Proto->isNothrow(Ctx)) 01286 return false; 01287 } 01288 return true; 01289 } 01290 01291 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { 01292 // Compute the callee type. 01293 QualType calleeType = C->getCallee()->getType(); 01294 if (calleeType == Context->BoundMemberTy) { 01295 QualType boundType = Expr::findBoundMemberType(C->getCallee()); 01296 01297 // We should only get a null bound type if processing a dependent 01298 // CFG. Recover by assuming nothing. 01299 if (!boundType.isNull()) calleeType = boundType; 01300 } 01301 01302 // If this is a call to a no-return function, this stops the block here. 01303 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); 01304 01305 bool AddEHEdge = false; 01306 01307 // Languages without exceptions are assumed to not throw. 01308 if (Context->getLangOpts().Exceptions) { 01309 if (BuildOpts.AddEHEdges) 01310 AddEHEdge = true; 01311 } 01312 01313 if (FunctionDecl *FD = C->getDirectCallee()) { 01314 if (FD->hasAttr<NoReturnAttr>()) 01315 NoReturn = true; 01316 if (FD->hasAttr<NoThrowAttr>()) 01317 AddEHEdge = false; 01318 } 01319 01320 if (!CanThrow(C->getCallee(), *Context)) 01321 AddEHEdge = false; 01322 01323 if (!NoReturn && !AddEHEdge) 01324 return VisitStmt(C, asc.withAlwaysAdd(true)); 01325 01326 if (Block) { 01327 Succ = Block; 01328 if (badCFG) 01329 return 0; 01330 } 01331 01332 if (NoReturn) 01333 Block = createNoReturnBlock(); 01334 else 01335 Block = createBlock(); 01336 01337 appendStmt(Block, C); 01338 01339 if (AddEHEdge) { 01340 // Add exceptional edges. 01341 if (TryTerminatedBlock) 01342 addSuccessor(Block, TryTerminatedBlock); 01343 else 01344 addSuccessor(Block, &cfg->getExit()); 01345 } 01346 01347 return VisitChildren(C); 01348 } 01349 01350 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, 01351 AddStmtChoice asc) { 01352 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 01353 appendStmt(ConfluenceBlock, C); 01354 if (badCFG) 01355 return 0; 01356 01357 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 01358 Succ = ConfluenceBlock; 01359 Block = NULL; 01360 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd); 01361 if (badCFG) 01362 return 0; 01363 01364 Succ = ConfluenceBlock; 01365 Block = NULL; 01366 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd); 01367 if (badCFG) 01368 return 0; 01369 01370 Block = createBlock(false); 01371 // See if this is a known constant. 01372 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 01373 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 01374 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 01375 Block->setTerminator(C); 01376 return addStmt(C->getCond()); 01377 } 01378 01379 01380 CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) { 01381 addLocalScopeAndDtors(C); 01382 CFGBlock *LastBlock = Block; 01383 01384 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); 01385 I != E; ++I ) { 01386 // If we hit a segment of code just containing ';' (NullStmts), we can 01387 // get a null block back. In such cases, just use the LastBlock 01388 if (CFGBlock *newBlock = addStmt(*I)) 01389 LastBlock = newBlock; 01390 01391 if (badCFG) 01392 return NULL; 01393 } 01394 01395 return LastBlock; 01396 } 01397 01398 CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, 01399 AddStmtChoice asc) { 01400 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C); 01401 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL); 01402 01403 // Create the confluence block that will "merge" the results of the ternary 01404 // expression. 01405 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 01406 appendStmt(ConfluenceBlock, C); 01407 if (badCFG) 01408 return 0; 01409 01410 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 01411 01412 // Create a block for the LHS expression if there is an LHS expression. A 01413 // GCC extension allows LHS to be NULL, causing the condition to be the 01414 // value that is returned instead. 01415 // e.g: x ?: y is shorthand for: x ? x : y; 01416 Succ = ConfluenceBlock; 01417 Block = NULL; 01418 CFGBlock *LHSBlock = 0; 01419 const Expr *trueExpr = C->getTrueExpr(); 01420 if (trueExpr != opaqueValue) { 01421 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd); 01422 if (badCFG) 01423 return 0; 01424 Block = NULL; 01425 } 01426 else 01427 LHSBlock = ConfluenceBlock; 01428 01429 // Create the block for the RHS expression. 01430 Succ = ConfluenceBlock; 01431 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); 01432 if (badCFG) 01433 return 0; 01434 01435 // Create the block that will contain the condition. 01436 Block = createBlock(false); 01437 01438 // See if this is a known constant. 01439 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 01440 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 01441 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 01442 Block->setTerminator(C); 01443 Expr *condExpr = C->getCond(); 01444 01445 if (opaqueValue) { 01446 // Run the condition expression if it's not trivially expressed in 01447 // terms of the opaque value (or if there is no opaque value). 01448 if (condExpr != opaqueValue) 01449 addStmt(condExpr); 01450 01451 // Before that, run the common subexpression if there was one. 01452 // At least one of this or the above will be run. 01453 return addStmt(BCO->getCommon()); 01454 } 01455 01456 return addStmt(condExpr); 01457 } 01458 01459 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 01460 // Check if the Decl is for an __label__. If so, elide it from the 01461 // CFG entirely. 01462 if (isa<LabelDecl>(*DS->decl_begin())) 01463 return Block; 01464 01465 // This case also handles static_asserts. 01466 if (DS->isSingleDecl()) 01467 return VisitDeclSubExpr(DS); 01468 01469 CFGBlock *B = 0; 01470 01471 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. 01472 typedef SmallVector<Decl*,10> BufTy; 01473 BufTy Buf(DS->decl_begin(), DS->decl_end()); 01474 01475 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { 01476 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 01477 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 01478 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; 01479 01480 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 01481 // automatically freed with the CFG. 01482 DeclGroupRef DG(*I); 01483 Decl *D = *I; 01484 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 01485 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 01486 01487 // Append the fake DeclStmt to block. 01488 B = VisitDeclSubExpr(DSNew); 01489 } 01490 01491 return B; 01492 } 01493 01494 /// VisitDeclSubExpr - Utility method to add block-level expressions for 01495 /// DeclStmts and initializers in them. 01496 CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) { 01497 assert(DS->isSingleDecl() && "Can handle single declarations only."); 01498 Decl *D = DS->getSingleDecl(); 01499 01500 if (isa<StaticAssertDecl>(D)) { 01501 // static_asserts aren't added to the CFG because they do not impact 01502 // runtime semantics. 01503 return Block; 01504 } 01505 01506 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 01507 01508 if (!VD) { 01509 autoCreateBlock(); 01510 appendStmt(Block, DS); 01511 return Block; 01512 } 01513 01514 bool IsReference = false; 01515 bool HasTemporaries = false; 01516 01517 // Destructors of temporaries in initialization expression should be called 01518 // after initialization finishes. 01519 Expr *Init = VD->getInit(); 01520 if (Init) { 01521 IsReference = VD->getType()->isReferenceType(); 01522 HasTemporaries = isa<ExprWithCleanups>(Init); 01523 01524 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 01525 // Generate destructors for temporaries in initialization expression. 01526 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 01527 IsReference); 01528 } 01529 } 01530 01531 autoCreateBlock(); 01532 appendStmt(Block, DS); 01533 01534 // Keep track of the last non-null block, as 'Block' can be nulled out 01535 // if the initializer expression is something like a 'while' in a 01536 // statement-expression. 01537 CFGBlock *LastBlock = Block; 01538 01539 if (Init) { 01540 if (HasTemporaries) { 01541 // For expression with temporaries go directly to subexpression to omit 01542 // generating destructors for the second time. 01543 ExprWithCleanups *EC = cast<ExprWithCleanups>(Init); 01544 if (CFGBlock *newBlock = Visit(EC->getSubExpr())) 01545 LastBlock = newBlock; 01546 } 01547 else { 01548 if (CFGBlock *newBlock = Visit(Init)) 01549 LastBlock = newBlock; 01550 } 01551 } 01552 01553 // If the type of VD is a VLA, then we must process its size expressions. 01554 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 01555 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 01556 Block = addStmt(VA->getSizeExpr()); 01557 01558 // Remove variable from local scope. 01559 if (ScopePos && VD == *ScopePos) 01560 ++ScopePos; 01561 01562 return Block ? Block : LastBlock; 01563 } 01564 01565 CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { 01566 // We may see an if statement in the middle of a basic block, or it may be the 01567 // first statement we are processing. In either case, we create a new basic 01568 // block. First, we create the blocks for the then...else statements, and 01569 // then we create the block containing the if statement. If we were in the 01570 // middle of a block, we stop processing that block. That block is then the 01571 // implicit successor for the "then" and "else" clauses. 01572 01573 // Save local scope position because in case of condition variable ScopePos 01574 // won't be restored when traversing AST. 01575 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 01576 01577 // Create local scope for possible condition variable. 01578 // Store scope position. Add implicit destructor. 01579 if (VarDecl *VD = I->getConditionVariable()) { 01580 LocalScope::const_iterator BeginScopePos = ScopePos; 01581 addLocalScopeForVarDecl(VD); 01582 addAutomaticObjDtors(ScopePos, BeginScopePos, I); 01583 } 01584 01585 // The block we were processing is now finished. Make it the successor 01586 // block. 01587 if (Block) { 01588 Succ = Block; 01589 if (badCFG) 01590 return 0; 01591 } 01592 01593 // Process the false branch. 01594 CFGBlock *ElseBlock = Succ; 01595 01596 if (Stmt *Else = I->getElse()) { 01597 SaveAndRestore<CFGBlock*> sv(Succ); 01598 01599 // NULL out Block so that the recursive call to Visit will 01600 // create a new basic block. 01601 Block = NULL; 01602 01603 // If branch is not a compound statement create implicit scope 01604 // and add destructors. 01605 if (!isa<CompoundStmt>(Else)) 01606 addLocalScopeAndDtors(Else); 01607 01608 ElseBlock = addStmt(Else); 01609 01610 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 01611 ElseBlock = sv.get(); 01612 else if (Block) { 01613 if (badCFG) 01614 return 0; 01615 } 01616 } 01617 01618 // Process the true branch. 01619 CFGBlock *ThenBlock; 01620 { 01621 Stmt *Then = I->getThen(); 01622 assert(Then); 01623 SaveAndRestore<CFGBlock*> sv(Succ); 01624 Block = NULL; 01625 01626 // If branch is not a compound statement create implicit scope 01627 // and add destructors. 01628 if (!isa<CompoundStmt>(Then)) 01629 addLocalScopeAndDtors(Then); 01630 01631 ThenBlock = addStmt(Then); 01632 01633 if (!ThenBlock) { 01634 // We can reach here if the "then" body has all NullStmts. 01635 // Create an empty block so we can distinguish between true and false 01636 // branches in path-sensitive analyses. 01637 ThenBlock = createBlock(false); 01638 addSuccessor(ThenBlock, sv.get()); 01639 } else if (Block) { 01640 if (badCFG) 01641 return 0; 01642 } 01643 } 01644 01645 // Now create a new block containing the if statement. 01646 Block = createBlock(false); 01647 01648 // Set the terminator of the new block to the If statement. 01649 Block->setTerminator(I); 01650 01651 // See if this is a known constant. 01652 const TryResult &KnownVal = tryEvaluateBool(I->getCond()); 01653 01654 // Now add the successors. 01655 addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock); 01656 addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock); 01657 01658 // Add the condition as the last statement in the new block. This may create 01659 // new blocks as the condition may contain control-flow. Any newly created 01660 // blocks will be pointed to be "Block". 01661 Block = addStmt(I->getCond()); 01662 01663 // Finally, if the IfStmt contains a condition variable, add both the IfStmt 01664 // and the condition variable initialization to the CFG. 01665 if (VarDecl *VD = I->getConditionVariable()) { 01666 if (Expr *Init = VD->getInit()) { 01667 autoCreateBlock(); 01668 appendStmt(Block, I->getConditionVariableDeclStmt()); 01669 addStmt(Init); 01670 } 01671 } 01672 01673 return Block; 01674 } 01675 01676 01677 CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) { 01678 // If we were in the middle of a block we stop processing that block. 01679 // 01680 // NOTE: If a "return" appears in the middle of a block, this means that the 01681 // code afterwards is DEAD (unreachable). We still keep a basic block 01682 // for that code; a simple "mark-and-sweep" from the entry block will be 01683 // able to report such dead blocks. 01684 01685 // Create the new block. 01686 Block = createBlock(false); 01687 01688 // The Exit block is the only successor. 01689 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R); 01690 addSuccessor(Block, &cfg->getExit()); 01691 01692 // Add the return statement to the block. This may create new blocks if R 01693 // contains control-flow (short-circuit operations). 01694 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 01695 } 01696 01697 CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 01698 // Get the block of the labeled statement. Add it to our map. 01699 addStmt(L->getSubStmt()); 01700 CFGBlock *LabelBlock = Block; 01701 01702 if (!LabelBlock) // This can happen when the body is empty, i.e. 01703 LabelBlock = createBlock(); // scopes that only contains NullStmts. 01704 01705 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 01706 "label already in map"); 01707 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 01708 01709 // Labels partition blocks, so this is the end of the basic block we were 01710 // processing (L is the block's label). Because this is label (and we have 01711 // already processed the substatement) there is no extra control-flow to worry 01712 // about. 01713 LabelBlock->setLabel(L); 01714 if (badCFG) 01715 return 0; 01716 01717 // We set Block to NULL to allow lazy creation of a new block (if necessary); 01718 Block = NULL; 01719 01720 // This block is now the implicit successor of other blocks. 01721 Succ = LabelBlock; 01722 01723 return LabelBlock; 01724 } 01725 01726 CFGBlock *CFGBuilder::VisitLambdaExpr(LambdaExpr *E, AddStmtChoice asc) { 01727 CFGBlock *LastBlock = VisitNoRecurse(E, asc); 01728 for (LambdaExpr::capture_init_iterator it = E->capture_init_begin(), 01729 et = E->capture_init_end(); it != et; ++it) { 01730 if (Expr *Init = *it) { 01731 CFGBlock *Tmp = Visit(Init); 01732 if (Tmp != 0) 01733 LastBlock = Tmp; 01734 } 01735 } 01736 return LastBlock; 01737 } 01738 01739 CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 01740 // Goto is a control-flow statement. Thus we stop processing the current 01741 // block and create a new one. 01742 01743 Block = createBlock(false); 01744 Block->setTerminator(G); 01745 01746 // If we already know the mapping to the label block add the successor now. 01747 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 01748 01749 if (I == LabelMap.end()) 01750 // We will need to backpatch this block later. 01751 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 01752 else { 01753 JumpTarget JT = I->second; 01754 addAutomaticObjDtors(ScopePos, JT.scopePosition, G); 01755 addSuccessor(Block, JT.block); 01756 } 01757 01758 return Block; 01759 } 01760 01761 CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 01762 CFGBlock *LoopSuccessor = NULL; 01763 01764 // Save local scope position because in case of condition variable ScopePos 01765 // won't be restored when traversing AST. 01766 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 01767 01768 // Create local scope for init statement and possible condition variable. 01769 // Add destructor for init statement and condition variable. 01770 // Store scope position for continue statement. 01771 if (Stmt *Init = F->getInit()) 01772 addLocalScopeForStmt(Init); 01773 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 01774 01775 if (VarDecl *VD = F->getConditionVariable()) 01776 addLocalScopeForVarDecl(VD); 01777 LocalScope::const_iterator ContinueScopePos = ScopePos; 01778 01779 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F); 01780 01781 // "for" is a control-flow statement. Thus we stop processing the current 01782 // block. 01783 if (Block) { 01784 if (badCFG) 01785 return 0; 01786 LoopSuccessor = Block; 01787 } else 01788 LoopSuccessor = Succ; 01789 01790 // Save the current value for the break targets. 01791 // All breaks should go to the code following the loop. 01792 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 01793 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 01794 01795 // Because of short-circuit evaluation, the condition of the loop can span 01796 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 01797 // evaluate the condition. 01798 CFGBlock *ExitConditionBlock = createBlock(false); 01799 CFGBlock *EntryConditionBlock = ExitConditionBlock; 01800 01801 // Set the terminator for the "exit" condition block. 01802 ExitConditionBlock->setTerminator(F); 01803 01804 // Now add the actual condition to the condition block. Because the condition 01805 // itself may contain control-flow, new blocks may be created. 01806 if (Stmt *C = F->getCond()) { 01807 Block = ExitConditionBlock; 01808 EntryConditionBlock = addStmt(C); 01809 if (badCFG) 01810 return 0; 01811 assert(Block == EntryConditionBlock || 01812 (Block == 0 && EntryConditionBlock == Succ)); 01813 01814 // If this block contains a condition variable, add both the condition 01815 // variable and initializer to the CFG. 01816 if (VarDecl *VD = F->getConditionVariable()) { 01817 if (Expr *Init = VD->getInit()) { 01818 autoCreateBlock(); 01819 appendStmt(Block, F->getConditionVariableDeclStmt()); 01820 EntryConditionBlock = addStmt(Init); 01821 assert(Block == EntryConditionBlock); 01822 } 01823 } 01824 01825 if (Block) { 01826 if (badCFG) 01827 return 0; 01828 } 01829 } 01830 01831 // The condition block is the implicit successor for the loop body as well as 01832 // any code above the loop. 01833 Succ = EntryConditionBlock; 01834 01835 // See if this is a known constant. 01836 TryResult KnownVal(true); 01837 01838 if (F->getCond()) 01839 KnownVal = tryEvaluateBool(F->getCond()); 01840 01841 // Now create the loop body. 01842 { 01843 assert(F->getBody()); 01844 01845 // Save the current values for Block, Succ, and continue targets. 01846 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 01847 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 01848 01849 // Create a new block to contain the (bottom) of the loop body. 01850 Block = NULL; 01851 01852 // Loop body should end with destructor of Condition variable (if any). 01853 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F); 01854 01855 if (Stmt *I = F->getInc()) { 01856 // Generate increment code in its own basic block. This is the target of 01857 // continue statements. 01858 Succ = addStmt(I); 01859 } else { 01860 // No increment code. Create a special, empty, block that is used as the 01861 // target block for "looping back" to the start of the loop. 01862 assert(Succ == EntryConditionBlock); 01863 Succ = Block ? Block : createBlock(); 01864 } 01865 01866 // Finish up the increment (or empty) block if it hasn't been already. 01867 if (Block) { 01868 assert(Block == Succ); 01869 if (badCFG) 01870 return 0; 01871 Block = 0; 01872 } 01873 01874 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 01875 01876 // The starting block for the loop increment is the block that should 01877 // represent the 'loop target' for looping back to the start of the loop. 01878 ContinueJumpTarget.block->setLoopTarget(F); 01879 01880 // If body is not a compound statement create implicit scope 01881 // and add destructors. 01882 if (!isa<CompoundStmt>(F->getBody())) 01883 addLocalScopeAndDtors(F->getBody()); 01884 01885 // Now populate the body block, and in the process create new blocks as we 01886 // walk the body of the loop. 01887 CFGBlock *BodyBlock = addStmt(F->getBody()); 01888 01889 if (!BodyBlock) 01890 BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);" 01891 else if (badCFG) 01892 return 0; 01893 01894 // This new body block is a successor to our "exit" condition block. 01895 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 01896 } 01897 01898 // Link up the condition block with the code that follows the loop. (the 01899 // false branch). 01900 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 01901 01902 // If the loop contains initialization, create a new block for those 01903 // statements. This block can also contain statements that precede the loop. 01904 if (Stmt *I = F->getInit()) { 01905 Block = createBlock(); 01906 return addStmt(I); 01907 } 01908 01909 // There is no loop initialization. We are thus basically a while loop. 01910 // NULL out Block to force lazy block construction. 01911 Block = NULL; 01912 Succ = EntryConditionBlock; 01913 return EntryConditionBlock; 01914 } 01915 01916 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 01917 if (asc.alwaysAdd(*this, M)) { 01918 autoCreateBlock(); 01919 appendStmt(Block, M); 01920 } 01921 return Visit(M->getBase()); 01922 } 01923 01924 CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 01925 // Objective-C fast enumeration 'for' statements: 01926 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 01927 // 01928 // for ( Type newVariable in collection_expression ) { statements } 01929 // 01930 // becomes: 01931 // 01932 // prologue: 01933 // 1. collection_expression 01934 // T. jump to loop_entry 01935 // loop_entry: 01936 // 1. side-effects of element expression 01937 // 1. ObjCForCollectionStmt [performs binding to newVariable] 01938 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 01939 // TB: 01940 // statements 01941 // T. jump to loop_entry 01942 // FB: 01943 // what comes after 01944 // 01945 // and 01946 // 01947 // Type existingItem; 01948 // for ( existingItem in expression ) { statements } 01949 // 01950 // becomes: 01951 // 01952 // the same with newVariable replaced with existingItem; the binding works 01953 // the same except that for one ObjCForCollectionStmt::getElement() returns 01954 // a DeclStmt and the other returns a DeclRefExpr. 01955 // 01956 01957 CFGBlock *LoopSuccessor = 0; 01958 01959 if (Block) { 01960 if (badCFG) 01961 return 0; 01962 LoopSuccessor = Block; 01963 Block = 0; 01964 } else 01965 LoopSuccessor = Succ; 01966 01967 // Build the condition blocks. 01968 CFGBlock *ExitConditionBlock = createBlock(false); 01969 01970 // Set the terminator for the "exit" condition block. 01971 ExitConditionBlock->setTerminator(S); 01972 01973 // The last statement in the block should be the ObjCForCollectionStmt, which 01974 // performs the actual binding to 'element' and determines if there are any 01975 // more items in the collection. 01976 appendStmt(ExitConditionBlock, S); 01977 Block = ExitConditionBlock; 01978 01979 // Walk the 'element' expression to see if there are any side-effects. We 01980 // generate new blocks as necessary. We DON'T add the statement by default to 01981 // the CFG unless it contains control-flow. 01982 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 01983 AddStmtChoice::NotAlwaysAdd); 01984 if (Block) { 01985 if (badCFG) 01986 return 0; 01987 Block = 0; 01988 } 01989 01990 // The condition block is the implicit successor for the loop body as well as 01991 // any code above the loop. 01992 Succ = EntryConditionBlock; 01993 01994 // Now create the true branch. 01995 { 01996 // Save the current values for Succ, continue and break targets. 01997 SaveAndRestore<CFGBlock*> save_Succ(Succ); 01998 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 01999 save_break(BreakJumpTarget); 02000 02001 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 02002 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 02003 02004 CFGBlock *BodyBlock = addStmt(S->getBody()); 02005 02006 if (!BodyBlock) 02007 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 02008 else if (Block) { 02009 if (badCFG) 02010 return 0; 02011 } 02012 02013 // This new body block is a successor to our "exit" condition block. 02014 addSuccessor(ExitConditionBlock, BodyBlock); 02015 } 02016 02017 // Link up the condition block with the code that follows the loop. 02018 // (the false branch). 02019 addSuccessor(ExitConditionBlock, LoopSuccessor); 02020 02021 // Now create a prologue block to contain the collection expression. 02022 Block = createBlock(); 02023 return addStmt(S->getCollection()); 02024 } 02025 02026 CFGBlock *CFGBuilder::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { 02027 // Inline the body. 02028 return addStmt(S->getSubStmt()); 02029 // TODO: consider adding cleanups for the end of @autoreleasepool scope. 02030 } 02031 02032 CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 02033 // FIXME: Add locking 'primitives' to CFG for @synchronized. 02034 02035 // Inline the body. 02036 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 02037 02038 // The sync body starts its own basic block. This makes it a little easier 02039 // for diagnostic clients. 02040 if (SyncBlock) { 02041 if (badCFG) 02042 return 0; 02043 02044 Block = 0; 02045 Succ = SyncBlock; 02046 } 02047 02048 // Add the @synchronized to the CFG. 02049 autoCreateBlock(); 02050 appendStmt(Block, S); 02051 02052 // Inline the sync expression. 02053 return addStmt(S->getSynchExpr()); 02054 } 02055 02056 CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 02057 // FIXME 02058 return NYS(); 02059 } 02060 02061 CFGBlock *CFGBuilder::VisitPseudoObjectExpr(PseudoObjectExpr *E) { 02062 autoCreateBlock(); 02063 02064 // Add the PseudoObject as the last thing. 02065 appendStmt(Block, E); 02066 02067 CFGBlock *lastBlock = Block; 02068 02069 // Before that, evaluate all of the semantics in order. In 02070 // CFG-land, that means appending them in reverse order. 02071 for (unsigned i = E->getNumSemanticExprs(); i != 0; ) { 02072 Expr *Semantic = E->getSemanticExpr(--i); 02073 02074 // If the semantic is an opaque value, we're being asked to bind 02075 // it to its source expression. 02076 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic)) 02077 Semantic = OVE->getSourceExpr(); 02078 02079 if (CFGBlock *B = Visit(Semantic)) 02080 lastBlock = B; 02081 } 02082 02083 return lastBlock; 02084 } 02085 02086 CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 02087 CFGBlock *LoopSuccessor = NULL; 02088 02089 // Save local scope position because in case of condition variable ScopePos 02090 // won't be restored when traversing AST. 02091 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 02092 02093 // Create local scope for possible condition variable. 02094 // Store scope position for continue statement. 02095 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 02096 if (VarDecl *VD = W->getConditionVariable()) { 02097 addLocalScopeForVarDecl(VD); 02098 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 02099 } 02100 02101 // "while" is a control-flow statement. Thus we stop processing the current 02102 // block. 02103 if (Block) { 02104 if (badCFG) 02105 return 0; 02106 LoopSuccessor = Block; 02107 Block = 0; 02108 } else 02109 LoopSuccessor = Succ; 02110 02111 // Because of short-circuit evaluation, the condition of the loop can span 02112 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 02113 // evaluate the condition. 02114 CFGBlock *ExitConditionBlock = createBlock(false); 02115 CFGBlock *EntryConditionBlock = ExitConditionBlock; 02116 02117 // Set the terminator for the "exit" condition block. 02118 ExitConditionBlock->setTerminator(W); 02119 02120 // Now add the actual condition to the condition block. Because the condition 02121 // itself may contain control-flow, new blocks may be created. Thus we update 02122 // "Succ" after adding the condition. 02123 if (Stmt *C = W->getCond()) { 02124 Block = ExitConditionBlock; 02125 EntryConditionBlock = addStmt(C); 02126 // The condition might finish the current 'Block'. 02127 Block = EntryConditionBlock; 02128 02129 // If this block contains a condition variable, add both the condition 02130 // variable and initializer to the CFG. 02131 if (VarDecl *VD = W->getConditionVariable()) { 02132 if (Expr *Init = VD->getInit()) { 02133 autoCreateBlock(); 02134 appendStmt(Block, W->getConditionVariableDeclStmt()); 02135 EntryConditionBlock = addStmt(Init); 02136 assert(Block == EntryConditionBlock); 02137 } 02138 } 02139 02140 if (Block) { 02141 if (badCFG) 02142 return 0; 02143 } 02144 } 02145 02146 // The condition block is the implicit successor for the loop body as well as 02147 // any code above the loop. 02148 Succ = EntryConditionBlock; 02149 02150 // See if this is a known constant. 02151 const TryResult& KnownVal = tryEvaluateBool(W->getCond()); 02152 02153 // Process the loop body. 02154 { 02155 assert(W->getBody()); 02156 02157 // Save the current values for Block, Succ, and continue and break targets 02158 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 02159 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 02160 save_break(BreakJumpTarget); 02161 02162 // Create an empty block to represent the transition block for looping back 02163 // to the head of the loop. 02164 Block = 0; 02165 assert(Succ == EntryConditionBlock); 02166 Succ = createBlock(); 02167 Succ->setLoopTarget(W); 02168 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 02169 02170 // All breaks should go to the code following the loop. 02171 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 02172 02173 // NULL out Block to force lazy instantiation of blocks for the body. 02174 Block = NULL; 02175 02176 // Loop body should end with destructor of Condition variable (if any). 02177 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 02178 02179 // If body is not a compound statement create implicit scope 02180 // and add destructors. 02181 if (!isa<CompoundStmt>(W->getBody())) 02182 addLocalScopeAndDtors(W->getBody()); 02183 02184 // Create the body. The returned block is the entry to the loop body. 02185 CFGBlock *BodyBlock = addStmt(W->getBody()); 02186 02187 if (!BodyBlock) 02188 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 02189 else if (Block) { 02190 if (badCFG) 02191 return 0; 02192 } 02193 02194 // Add the loop body entry as a successor to the condition. 02195 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 02196 } 02197 02198 // Link up the condition block with the code that follows the loop. (the 02199 // false branch). 02200 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 02201 02202 // There can be no more statements in the condition block since we loop back 02203 // to this block. NULL out Block to force lazy creation of another block. 02204 Block = NULL; 02205 02206 // Return the condition block, which is the dominating block for the loop. 02207 Succ = EntryConditionBlock; 02208 return EntryConditionBlock; 02209 } 02210 02211 02212 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 02213 // FIXME: For now we pretend that @catch and the code it contains does not 02214 // exit. 02215 return Block; 02216 } 02217 02218 CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 02219 // FIXME: This isn't complete. We basically treat @throw like a return 02220 // statement. 02221 02222 // If we were in the middle of a block we stop processing that block. 02223 if (badCFG) 02224 return 0; 02225 02226 // Create the new block. 02227 Block = createBlock(false); 02228 02229 // The Exit block is the only successor. 02230 addSuccessor(Block, &cfg->getExit()); 02231 02232 // Add the statement to the block. This may create new blocks if S contains 02233 // control-flow (short-circuit operations). 02234 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 02235 } 02236 02237 CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 02238 // If we were in the middle of a block we stop processing that block. 02239 if (badCFG) 02240 return 0; 02241 02242 // Create the new block. 02243 Block = createBlock(false); 02244 02245 if (TryTerminatedBlock) 02246 // The current try statement is the only successor. 02247 addSuccessor(Block, TryTerminatedBlock); 02248 else 02249 // otherwise the Exit block is the only successor. 02250 addSuccessor(Block, &cfg->getExit()); 02251 02252 // Add the statement to the block. This may create new blocks if S contains 02253 // control-flow (short-circuit operations). 02254 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 02255 } 02256 02257 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 02258 CFGBlock *LoopSuccessor = NULL; 02259 02260 // "do...while" is a control-flow statement. Thus we stop processing the 02261 // current block. 02262 if (Block) { 02263 if (badCFG) 02264 return 0; 02265 LoopSuccessor = Block; 02266 } else 02267 LoopSuccessor = Succ; 02268 02269 // Because of short-circuit evaluation, the condition of the loop can span 02270 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 02271 // evaluate the condition. 02272 CFGBlock *ExitConditionBlock = createBlock(false); 02273 CFGBlock *EntryConditionBlock = ExitConditionBlock; 02274 02275 // Set the terminator for the "exit" condition block. 02276 ExitConditionBlock->setTerminator(D); 02277 02278 // Now add the actual condition to the condition block. Because the condition 02279 // itself may contain control-flow, new blocks may be created. 02280 if (Stmt *C = D->getCond()) { 02281 Block = ExitConditionBlock; 02282 EntryConditionBlock = addStmt(C); 02283 if (Block) { 02284 if (badCFG) 02285 return 0; 02286 } 02287 } 02288 02289 // The condition block is the implicit successor for the loop body. 02290 Succ = EntryConditionBlock; 02291 02292 // See if this is a known constant. 02293 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 02294 02295 // Process the loop body. 02296 CFGBlock *BodyBlock = NULL; 02297 { 02298 assert(D->getBody()); 02299 02300 // Save the current values for Block, Succ, and continue and break targets 02301 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 02302 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 02303 save_break(BreakJumpTarget); 02304 02305 // All continues within this loop should go to the condition block 02306 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 02307 02308 // All breaks should go to the code following the loop. 02309 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 02310 02311 // NULL out Block to force lazy instantiation of blocks for the body. 02312 Block = NULL; 02313 02314 // If body is not a compound statement create implicit scope 02315 // and add destructors. 02316 if (!isa<CompoundStmt>(D->getBody())) 02317 addLocalScopeAndDtors(D->getBody()); 02318 02319 // Create the body. The returned block is the entry to the loop body. 02320 BodyBlock = addStmt(D->getBody()); 02321 02322 if (!BodyBlock) 02323 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 02324 else if (Block) { 02325 if (badCFG) 02326 return 0; 02327 } 02328 02329 if (!KnownVal.isFalse()) { 02330 // Add an intermediate block between the BodyBlock and the 02331 // ExitConditionBlock to represent the "loop back" transition. Create an 02332 // empty block to represent the transition block for looping back to the 02333 // head of the loop. 02334 // FIXME: Can we do this more efficiently without adding another block? 02335 Block = NULL; 02336 Succ = BodyBlock; 02337 CFGBlock *LoopBackBlock = createBlock(); 02338 LoopBackBlock->setLoopTarget(D); 02339 02340 // Add the loop body entry as a successor to the condition. 02341 addSuccessor(ExitConditionBlock, LoopBackBlock); 02342 } 02343 else 02344 addSuccessor(ExitConditionBlock, NULL); 02345 } 02346 02347 // Link up the condition block with the code that follows the loop. 02348 // (the false branch). 02349 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 02350 02351 // There can be no more statements in the body block(s) since we loop back to 02352 // the body. NULL out Block to force lazy creation of another block. 02353 Block = NULL; 02354 02355 // Return the loop body, which is the dominating block for the loop. 02356 Succ = BodyBlock; 02357 return BodyBlock; 02358 } 02359 02360 CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 02361 // "continue" is a control-flow statement. Thus we stop processing the 02362 // current block. 02363 if (badCFG) 02364 return 0; 02365 02366 // Now create a new block that ends with the continue statement. 02367 Block = createBlock(false); 02368 Block->setTerminator(C); 02369 02370 // If there is no target for the continue, then we are looking at an 02371 // incomplete AST. This means the CFG cannot be constructed. 02372 if (ContinueJumpTarget.block) { 02373 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C); 02374 addSuccessor(Block, ContinueJumpTarget.block); 02375 } else 02376 badCFG = true; 02377 02378 return Block; 02379 } 02380 02381 CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 02382 AddStmtChoice asc) { 02383 02384 if (asc.alwaysAdd(*this, E)) { 02385 autoCreateBlock(); 02386 appendStmt(Block, E); 02387 } 02388 02389 // VLA types have expressions that must be evaluated. 02390 CFGBlock *lastBlock = Block; 02391 02392 if (E->isArgumentType()) { 02393 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 02394 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 02395 lastBlock = addStmt(VA->getSizeExpr()); 02396 } 02397 return lastBlock; 02398 } 02399 02400 /// VisitStmtExpr - Utility method to handle (nested) statement 02401 /// expressions (a GCC extension). 02402 CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 02403 if (asc.alwaysAdd(*this, SE)) { 02404 autoCreateBlock(); 02405 appendStmt(Block, SE); 02406 } 02407 return VisitCompoundStmt(SE->getSubStmt()); 02408 } 02409 02410 CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 02411 // "switch" is a control-flow statement. Thus we stop processing the current 02412 // block. 02413 CFGBlock *SwitchSuccessor = NULL; 02414 02415 // Save local scope position because in case of condition variable ScopePos 02416 // won't be restored when traversing AST. 02417 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 02418 02419 // Create local scope for possible condition variable. 02420 // Store scope position. Add implicit destructor. 02421 if (VarDecl *VD = Terminator->getConditionVariable()) { 02422 LocalScope::const_iterator SwitchBeginScopePos = ScopePos; 02423 addLocalScopeForVarDecl(VD); 02424 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator); 02425 } 02426 02427 if (Block) { 02428 if (badCFG) 02429 return 0; 02430 SwitchSuccessor = Block; 02431 } else SwitchSuccessor = Succ; 02432 02433 // Save the current "switch" context. 02434 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 02435 save_default(DefaultCaseBlock); 02436 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 02437 02438 // Set the "default" case to be the block after the switch statement. If the 02439 // switch statement contains a "default:", this value will be overwritten with 02440 // the block for that code. 02441 DefaultCaseBlock = SwitchSuccessor; 02442 02443 // Create a new block that will contain the switch statement. 02444 SwitchTerminatedBlock = createBlock(false); 02445 02446 // Now process the switch body. The code after the switch is the implicit 02447 // successor. 02448 Succ = SwitchSuccessor; 02449 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 02450 02451 // When visiting the body, the case statements should automatically get linked 02452 // up to the switch. We also don't keep a pointer to the body, since all 02453 // control-flow from the switch goes to case/default statements. 02454 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 02455 Block = NULL; 02456 02457 // For pruning unreachable case statements, save the current state 02458 // for tracking the condition value. 02459 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 02460 false); 02461 02462 // Determine if the switch condition can be explicitly evaluated. 02463 assert(Terminator->getCond() && "switch condition must be non-NULL"); 02464 Expr::EvalResult result; 02465 bool b = tryEvaluate(Terminator->getCond(), result); 02466 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 02467 b ? &result : 0); 02468 02469 // If body is not a compound statement create implicit scope 02470 // and add destructors. 02471 if (!isa<CompoundStmt>(Terminator->getBody())) 02472 addLocalScopeAndDtors(Terminator->getBody()); 02473 02474 addStmt(Terminator->getBody()); 02475 if (Block) { 02476 if (badCFG) 02477 return 0; 02478 } 02479 02480 // If we have no "default:" case, the default transition is to the code 02481 // following the switch body. Moreover, take into account if all the 02482 // cases of a switch are covered (e.g., switching on an enum value). 02483 addSuccessor(SwitchTerminatedBlock, 02484 switchExclusivelyCovered || Terminator->isAllEnumCasesCovered() 02485 ? 0 : DefaultCaseBlock); 02486 02487 // Add the terminator and condition in the switch block. 02488 SwitchTerminatedBlock->setTerminator(Terminator); 02489 Block = SwitchTerminatedBlock; 02490 Block = addStmt(Terminator->getCond()); 02491 02492 // Finally, if the SwitchStmt contains a condition variable, add both the 02493 // SwitchStmt and the condition variable initialization to the CFG. 02494 if (VarDecl *VD = Terminator->getConditionVariable()) { 02495 if (Expr *Init = VD->getInit()) { 02496 autoCreateBlock(); 02497 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 02498 addStmt(Init); 02499 } 02500 } 02501 02502 return Block; 02503 } 02504 02505 static bool shouldAddCase(bool &switchExclusivelyCovered, 02506 const Expr::EvalResult *switchCond, 02507 const CaseStmt *CS, 02508 ASTContext &Ctx) { 02509 if (!switchCond) 02510 return true; 02511 02512 bool addCase = false; 02513 02514 if (!switchExclusivelyCovered) { 02515 if (switchCond->Val.isInt()) { 02516 // Evaluate the LHS of the case value. 02517 const llvm::APSInt &lhsInt = CS->getLHS()->EvaluateKnownConstInt(Ctx); 02518 const llvm::APSInt &condInt = switchCond->Val.getInt(); 02519 02520 if (condInt == lhsInt) { 02521 addCase = true; 02522 switchExclusivelyCovered = true; 02523 } 02524 else if (condInt < lhsInt) { 02525 if (const Expr *RHS = CS->getRHS()) { 02526 // Evaluate the RHS of the case value. 02527 const llvm::APSInt &V2 = RHS->EvaluateKnownConstInt(Ctx); 02528 if (V2 <= condInt) { 02529 addCase = true; 02530 switchExclusivelyCovered = true; 02531 } 02532 } 02533 } 02534 } 02535 else 02536 addCase = true; 02537 } 02538 return addCase; 02539 } 02540 02541 CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 02542 // CaseStmts are essentially labels, so they are the first statement in a 02543 // block. 02544 CFGBlock *TopBlock = 0, *LastBlock = 0; 02545 02546 if (Stmt *Sub = CS->getSubStmt()) { 02547 // For deeply nested chains of CaseStmts, instead of doing a recursion 02548 // (which can blow out the stack), manually unroll and create blocks 02549 // along the way. 02550 while (isa<CaseStmt>(Sub)) { 02551 CFGBlock *currentBlock = createBlock(false); 02552 currentBlock->setLabel(CS); 02553 02554 if (TopBlock) 02555 addSuccessor(LastBlock, currentBlock); 02556 else 02557 TopBlock = currentBlock; 02558 02559 addSuccessor(SwitchTerminatedBlock, 02560 shouldAddCase(switchExclusivelyCovered, switchCond, 02561 CS, *Context) 02562 ? currentBlock : 0); 02563 02564 LastBlock = currentBlock; 02565 CS = cast<CaseStmt>(Sub); 02566 Sub = CS->getSubStmt(); 02567 } 02568 02569 addStmt(Sub); 02570 } 02571 02572 CFGBlock *CaseBlock = Block; 02573 if (!CaseBlock) 02574 CaseBlock = createBlock(); 02575 02576 // Cases statements partition blocks, so this is the top of the basic block we 02577 // were processing (the "case XXX:" is the label). 02578 CaseBlock->setLabel(CS); 02579 02580 if (badCFG) 02581 return 0; 02582 02583 // Add this block to the list of successors for the block with the switch 02584 // statement. 02585 assert(SwitchTerminatedBlock); 02586 addSuccessor(SwitchTerminatedBlock, 02587 shouldAddCase(switchExclusivelyCovered, switchCond, 02588 CS, *Context) 02589 ? CaseBlock : 0); 02590 02591 // We set Block to NULL to allow lazy creation of a new block (if necessary) 02592 Block = NULL; 02593 02594 if (TopBlock) { 02595 addSuccessor(LastBlock, CaseBlock); 02596 Succ = TopBlock; 02597 } else { 02598 // This block is now the implicit successor of other blocks. 02599 Succ = CaseBlock; 02600 } 02601 02602 return Succ; 02603 } 02604 02605 CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 02606 if (Terminator->getSubStmt()) 02607 addStmt(Terminator->getSubStmt()); 02608 02609 DefaultCaseBlock = Block; 02610 02611 if (!DefaultCaseBlock) 02612 DefaultCaseBlock = createBlock(); 02613 02614 // Default statements partition blocks, so this is the top of the basic block 02615 // we were processing (the "default:" is the label). 02616 DefaultCaseBlock->setLabel(Terminator); 02617 02618 if (badCFG) 02619 return 0; 02620 02621 // Unlike case statements, we don't add the default block to the successors 02622 // for the switch statement immediately. This is done when we finish 02623 // processing the switch statement. This allows for the default case 02624 // (including a fall-through to the code after the switch statement) to always 02625 // be the last successor of a switch-terminated block. 02626 02627 // We set Block to NULL to allow lazy creation of a new block (if necessary) 02628 Block = NULL; 02629 02630 // This block is now the implicit successor of other blocks. 02631 Succ = DefaultCaseBlock; 02632 02633 return DefaultCaseBlock; 02634 } 02635 02636 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 02637 // "try"/"catch" is a control-flow statement. Thus we stop processing the 02638 // current block. 02639 CFGBlock *TrySuccessor = NULL; 02640 02641 if (Block) { 02642 if (badCFG) 02643 return 0; 02644 TrySuccessor = Block; 02645 } else TrySuccessor = Succ; 02646 02647 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 02648 02649 // Create a new block that will contain the try statement. 02650 CFGBlock *NewTryTerminatedBlock = createBlock(false); 02651 // Add the terminator in the try block. 02652 NewTryTerminatedBlock->setTerminator(Terminator); 02653 02654 bool HasCatchAll = false; 02655 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 02656 // The code after the try is the implicit successor. 02657 Succ = TrySuccessor; 02658 CXXCatchStmt *CS = Terminator->getHandler(h); 02659 if (CS->getExceptionDecl() == 0) { 02660 HasCatchAll = true; 02661 } 02662 Block = NULL; 02663 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 02664 if (CatchBlock == 0) 02665 return 0; 02666 // Add this block to the list of successors for the block with the try 02667 // statement. 02668 addSuccessor(NewTryTerminatedBlock, CatchBlock); 02669 } 02670 if (!HasCatchAll) { 02671 if (PrevTryTerminatedBlock) 02672 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 02673 else 02674 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 02675 } 02676 02677 // The code after the try is the implicit successor. 02678 Succ = TrySuccessor; 02679 02680 // Save the current "try" context. 02681 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock); 02682 cfg->addTryDispatchBlock(TryTerminatedBlock); 02683 02684 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 02685 Block = NULL; 02686 Block = addStmt(Terminator->getTryBlock()); 02687 return Block; 02688 } 02689 02690 CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 02691 // CXXCatchStmt are treated like labels, so they are the first statement in a 02692 // block. 02693 02694 // Save local scope position because in case of exception variable ScopePos 02695 // won't be restored when traversing AST. 02696 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 02697 02698 // Create local scope for possible exception variable. 02699 // Store scope position. Add implicit destructor. 02700 if (VarDecl *VD = CS->getExceptionDecl()) { 02701 LocalScope::const_iterator BeginScopePos = ScopePos; 02702 addLocalScopeForVarDecl(VD); 02703 addAutomaticObjDtors(ScopePos, BeginScopePos, CS); 02704 } 02705 02706 if (CS->getHandlerBlock()) 02707 addStmt(CS->getHandlerBlock()); 02708 02709 CFGBlock *CatchBlock = Block; 02710 if (!CatchBlock) 02711 CatchBlock = createBlock(); 02712 02713 // CXXCatchStmt is more than just a label. They have semantic meaning 02714 // as well, as they implicitly "initialize" the catch variable. Add 02715 // it to the CFG as a CFGElement so that the control-flow of these 02716 // semantics gets captured. 02717 appendStmt(CatchBlock, CS); 02718 02719 // Also add the CXXCatchStmt as a label, to mirror handling of regular 02720 // labels. 02721 CatchBlock->setLabel(CS); 02722 02723 // Bail out if the CFG is bad. 02724 if (badCFG) 02725 return 0; 02726 02727 // We set Block to NULL to allow lazy creation of a new block (if necessary) 02728 Block = NULL; 02729 02730 return CatchBlock; 02731 } 02732 02733 CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 02734 // C++0x for-range statements are specified as [stmt.ranged]: 02735 // 02736 // { 02737 // auto && __range = range-init; 02738 // for ( auto __begin = begin-expr, 02739 // __end = end-expr; 02740 // __begin != __end; 02741 // ++__begin ) { 02742 // for-range-declaration = *__begin; 02743 // statement 02744 // } 02745 // } 02746 02747 // Save local scope position before the addition of the implicit variables. 02748 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 02749 02750 // Create local scopes and destructors for range, begin and end variables. 02751 if (Stmt *Range = S->getRangeStmt()) 02752 addLocalScopeForStmt(Range); 02753 if (Stmt *BeginEnd = S->getBeginEndStmt()) 02754 addLocalScopeForStmt(BeginEnd); 02755 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S); 02756 02757 LocalScope::const_iterator ContinueScopePos = ScopePos; 02758 02759 // "for" is a control-flow statement. Thus we stop processing the current 02760 // block. 02761 CFGBlock *LoopSuccessor = NULL; 02762 if (Block) { 02763 if (badCFG) 02764 return 0; 02765 LoopSuccessor = Block; 02766 } else 02767 LoopSuccessor = Succ; 02768 02769 // Save the current value for the break targets. 02770 // All breaks should go to the code following the loop. 02771 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 02772 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 02773 02774 // The block for the __begin != __end expression. 02775 CFGBlock *ConditionBlock = createBlock(false); 02776 ConditionBlock->setTerminator(S); 02777 02778 // Now add the actual condition to the condition block. 02779 if (Expr *C = S->getCond()) { 02780 Block = ConditionBlock; 02781 CFGBlock *BeginConditionBlock = addStmt(C); 02782 if (badCFG) 02783 return 0; 02784 assert(BeginConditionBlock == ConditionBlock && 02785 "condition block in for-range was unexpectedly complex"); 02786 (void)BeginConditionBlock; 02787 } 02788 02789 // The condition block is the implicit successor for the loop body as well as 02790 // any code above the loop. 02791 Succ = ConditionBlock; 02792 02793 // See if this is a known constant. 02794 TryResult KnownVal(true); 02795 02796 if (S->getCond()) 02797 KnownVal = tryEvaluateBool(S->getCond()); 02798 02799 // Now create the loop body. 02800 { 02801 assert(S->getBody()); 02802 02803 // Save the current values for Block, Succ, and continue targets. 02804 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 02805 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 02806 02807 // Generate increment code in its own basic block. This is the target of 02808 // continue statements. 02809 Block = 0; 02810 Succ = addStmt(S->getInc()); 02811 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 02812 02813 // The starting block for the loop increment is the block that should 02814 // represent the 'loop target' for looping back to the start of the loop. 02815 ContinueJumpTarget.block->setLoopTarget(S); 02816 02817 // Finish up the increment block and prepare to start the loop body. 02818 assert(Block); 02819 if (badCFG) 02820 return 0; 02821 Block = 0; 02822 02823 02824 // Add implicit scope and dtors for loop variable. 02825 addLocalScopeAndDtors(S->getLoopVarStmt()); 02826 02827 // Populate a new block to contain the loop body and loop variable. 02828 Block = addStmt(S->getBody()); 02829 if (badCFG) 02830 return 0; 02831 Block = addStmt(S->getLoopVarStmt()); 02832 if (badCFG) 02833 return 0; 02834 02835 // This new body block is a successor to our condition block. 02836 addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : Block); 02837 } 02838 02839 // Link up the condition block with the code that follows the loop (the 02840 // false branch). 02841 addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor); 02842 02843 // Add the initialization statements. 02844 Block = createBlock(); 02845 addStmt(S->getBeginEndStmt()); 02846 return addStmt(S->getRangeStmt()); 02847 } 02848 02849 CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 02850 AddStmtChoice asc) { 02851 if (BuildOpts.AddImplicitDtors) { 02852 // If adding implicit destructors visit the full expression for adding 02853 // destructors of temporaries. 02854 VisitForTemporaryDtors(E->getSubExpr()); 02855 02856 // Full expression has to be added as CFGStmt so it will be sequenced 02857 // before destructors of it's temporaries. 02858 asc = asc.withAlwaysAdd(true); 02859 } 02860 return Visit(E->getSubExpr(), asc); 02861 } 02862 02863 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 02864 AddStmtChoice asc) { 02865 if (asc.alwaysAdd(*this, E)) { 02866 autoCreateBlock(); 02867 appendStmt(Block, E); 02868 02869 // We do not want to propagate the AlwaysAdd property. 02870 asc = asc.withAlwaysAdd(false); 02871 } 02872 return Visit(E->getSubExpr(), asc); 02873 } 02874 02875 CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 02876 AddStmtChoice asc) { 02877 autoCreateBlock(); 02878 appendStmt(Block, C); 02879 02880 return VisitChildren(C); 02881 } 02882 02883 CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 02884 AddStmtChoice asc) { 02885 if (asc.alwaysAdd(*this, E)) { 02886 autoCreateBlock(); 02887 appendStmt(Block, E); 02888 // We do not want to propagate the AlwaysAdd property. 02889 asc = asc.withAlwaysAdd(false); 02890 } 02891 return Visit(E->getSubExpr(), asc); 02892 } 02893 02894 CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 02895 AddStmtChoice asc) { 02896 autoCreateBlock(); 02897 appendStmt(Block, C); 02898 return VisitChildren(C); 02899 } 02900 02901 CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 02902 AddStmtChoice asc) { 02903 if (asc.alwaysAdd(*this, E)) { 02904 autoCreateBlock(); 02905 appendStmt(Block, E); 02906 } 02907 return Visit(E->getSubExpr(), AddStmtChoice()); 02908 } 02909 02910 CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 02911 // Lazily create the indirect-goto dispatch block if there isn't one already. 02912 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 02913 02914 if (!IBlock) { 02915 IBlock = createBlock(false); 02916 cfg->setIndirectGotoBlock(IBlock); 02917 } 02918 02919 // IndirectGoto is a control-flow statement. Thus we stop processing the 02920 // current block and create a new one. 02921 if (badCFG) 02922 return 0; 02923 02924 Block = createBlock(false); 02925 Block->setTerminator(I); 02926 addSuccessor(Block, IBlock); 02927 return addStmt(I->getTarget()); 02928 } 02929 02930 CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 02931 tryAgain: 02932 if (!E) { 02933 badCFG = true; 02934 return NULL; 02935 } 02936 switch (E->getStmtClass()) { 02937 default: 02938 return VisitChildrenForTemporaryDtors(E); 02939 02940 case Stmt::BinaryOperatorClass: 02941 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 02942 02943 case Stmt::CXXBindTemporaryExprClass: 02944 return VisitCXXBindTemporaryExprForTemporaryDtors( 02945 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 02946 02947 case Stmt::BinaryConditionalOperatorClass: 02948 case Stmt::ConditionalOperatorClass: 02949 return VisitConditionalOperatorForTemporaryDtors( 02950 cast<AbstractConditionalOperator>(E), BindToTemporary); 02951 02952 case Stmt::ImplicitCastExprClass: 02953 // For implicit cast we want BindToTemporary to be passed further. 02954 E = cast<CastExpr>(E)->getSubExpr(); 02955 goto tryAgain; 02956 02957 case Stmt::ParenExprClass: 02958 E = cast<ParenExpr>(E)->getSubExpr(); 02959 goto tryAgain; 02960 02961 case Stmt::MaterializeTemporaryExprClass: 02962 E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(); 02963 goto tryAgain; 02964 } 02965 } 02966 02967 CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 02968 // When visiting children for destructors we want to visit them in reverse 02969 // order. Because there's no reverse iterator for children must to reverse 02970 // them in helper vector. 02971 typedef SmallVector<Stmt *, 4> ChildrenVect; 02972 ChildrenVect ChildrenRev; 02973 for (Stmt::child_range I = E->children(); I; ++I) { 02974 if (*I) ChildrenRev.push_back(*I); 02975 } 02976 02977 CFGBlock *B = Block; 02978 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 02979 L = ChildrenRev.rend(); I != L; ++I) { 02980 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 02981 B = R; 02982 } 02983 return B; 02984 } 02985 02986 CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 02987 if (E->isLogicalOp()) { 02988 // Destructors for temporaries in LHS expression should be called after 02989 // those for RHS expression. Even if this will unnecessarily create a block, 02990 // this block will be used at least by the full expression. 02991 autoCreateBlock(); 02992 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 02993 if (badCFG) 02994 return NULL; 02995 02996 Succ = ConfluenceBlock; 02997 Block = NULL; 02998 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 02999 03000 if (RHSBlock) { 03001 if (badCFG) 03002 return NULL; 03003 03004 // If RHS expression did produce destructors we need to connect created 03005 // blocks to CFG in same manner as for binary operator itself. 03006 CFGBlock *LHSBlock = createBlock(false); 03007 LHSBlock->setTerminator(CFGTerminator(E, true)); 03008 03009 // For binary operator LHS block is before RHS in list of predecessors 03010 // of ConfluenceBlock. 03011 std::reverse(ConfluenceBlock->pred_begin(), 03012 ConfluenceBlock->pred_end()); 03013 03014 // See if this is a known constant. 03015 TryResult KnownVal = tryEvaluateBool(E->getLHS()); 03016 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 03017 KnownVal.negate(); 03018 03019 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 03020 // itself. 03021 if (E->getOpcode() == BO_LOr) { 03022 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 03023 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 03024 } else { 03025 assert (E->getOpcode() == BO_LAnd); 03026 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 03027 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 03028 } 03029 03030 Block = LHSBlock; 03031 return LHSBlock; 03032 } 03033 03034 Block = ConfluenceBlock; 03035 return ConfluenceBlock; 03036 } 03037 03038 if (E->isAssignmentOp()) { 03039 // For assignment operator (=) LHS expression is visited 03040 // before RHS expression. For destructors visit them in reverse order. 03041 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 03042 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 03043 return LHSBlock ? LHSBlock : RHSBlock; 03044 } 03045 03046 // For any other binary operator RHS expression is visited before 03047 // LHS expression (order of children). For destructors visit them in reverse 03048 // order. 03049 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 03050 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 03051 return RHSBlock ? RHSBlock : LHSBlock; 03052 } 03053 03054 CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 03055 CXXBindTemporaryExpr *E, bool BindToTemporary) { 03056 // First add destructors for temporaries in subexpression. 03057 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 03058 if (!BindToTemporary) { 03059 // If lifetime of temporary is not prolonged (by assigning to constant 03060 // reference) add destructor for it. 03061 03062 // If the destructor is marked as a no-return destructor, we need to create 03063 // a new block for the destructor which does not have as a successor 03064 // anything built thus far. Control won't flow out of this block. 03065 const CXXDestructorDecl *Dtor = E->getTemporary()->getDestructor(); 03066 if (cast<FunctionType>(Dtor->getType())->getNoReturnAttr()) 03067 Block = createNoReturnBlock(); 03068 else 03069 autoCreateBlock(); 03070 03071 appendTemporaryDtor(Block, E); 03072 B = Block; 03073 } 03074 return B; 03075 } 03076 03077 CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 03078 AbstractConditionalOperator *E, bool BindToTemporary) { 03079 // First add destructors for condition expression. Even if this will 03080 // unnecessarily create a block, this block will be used at least by the full 03081 // expression. 03082 autoCreateBlock(); 03083 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 03084 if (badCFG) 03085 return NULL; 03086 if (BinaryConditionalOperator *BCO 03087 = dyn_cast<BinaryConditionalOperator>(E)) { 03088 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon()); 03089 if (badCFG) 03090 return NULL; 03091 } 03092 03093 // Try to add block with destructors for LHS expression. 03094 CFGBlock *LHSBlock = NULL; 03095 Succ = ConfluenceBlock; 03096 Block = NULL; 03097 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary); 03098 if (badCFG) 03099 return NULL; 03100 03101 // Try to add block with destructors for RHS expression; 03102 Succ = ConfluenceBlock; 03103 Block = NULL; 03104 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(), 03105 BindToTemporary); 03106 if (badCFG) 03107 return NULL; 03108 03109 if (!RHSBlock && !LHSBlock) { 03110 // If neither LHS nor RHS expression had temporaries to destroy don't create 03111 // more blocks. 03112 Block = ConfluenceBlock; 03113 return Block; 03114 } 03115 03116 Block = createBlock(false); 03117 Block->setTerminator(CFGTerminator(E, true)); 03118 03119 // See if this is a known constant. 03120 const TryResult &KnownVal = tryEvaluateBool(E->getCond()); 03121 03122 if (LHSBlock) { 03123 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 03124 } else if (KnownVal.isFalse()) { 03125 addSuccessor(Block, NULL); 03126 } else { 03127 addSuccessor(Block, ConfluenceBlock); 03128 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 03129 } 03130 03131 if (!RHSBlock) 03132 RHSBlock = ConfluenceBlock; 03133 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 03134 03135 return Block; 03136 } 03137 03138 } // end anonymous namespace 03139 03140 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 03141 /// no successors or predecessors. If this is the first block created in the 03142 /// CFG, it is automatically set to be the Entry and Exit of the CFG. 03143 CFGBlock *CFG::createBlock() { 03144 bool first_block = begin() == end(); 03145 03146 // Create the block. 03147 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 03148 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC, this); 03149 Blocks.push_back(Mem, BlkBVC); 03150 03151 // If this is the first block, set it as the Entry and Exit. 03152 if (first_block) 03153 Entry = Exit = &back(); 03154 03155 // Return the block. 03156 return &back(); 03157 } 03158 03159 /// buildCFG - Constructs a CFG from an AST. Ownership of the returned 03160 /// CFG is returned to the caller. 03161 CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, 03162 const BuildOptions &BO) { 03163 CFGBuilder Builder(C, BO); 03164 return Builder.buildCFG(D, Statement); 03165 } 03166 03167 const CXXDestructorDecl * 03168 CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 03169 switch (getKind()) { 03170 case CFGElement::Invalid: 03171 case CFGElement::Statement: 03172 case CFGElement::Initializer: 03173 llvm_unreachable("getDestructorDecl should only be used with " 03174 "ImplicitDtors"); 03175 case CFGElement::AutomaticObjectDtor: { 03176 const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl(); 03177 QualType ty = var->getType(); 03178 ty = ty.getNonReferenceType(); 03179 while (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 03180 ty = arrayType->getElementType(); 03181 } 03182 const RecordType *recordType = ty->getAs<RecordType>(); 03183 const CXXRecordDecl *classDecl = 03184 cast<CXXRecordDecl>(recordType->getDecl()); 03185 return classDecl->getDestructor(); 03186 } 03187 case CFGElement::TemporaryDtor: { 03188 const CXXBindTemporaryExpr *bindExpr = 03189 cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr(); 03190 const CXXTemporary *temp = bindExpr->getTemporary(); 03191 return temp->getDestructor(); 03192 } 03193 case CFGElement::BaseDtor: 03194 case CFGElement::MemberDtor: 03195 03196 // Not yet supported. 03197 return 0; 03198 } 03199 llvm_unreachable("getKind() returned bogus value"); 03200 } 03201 03202 bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { 03203 if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) { 03204 QualType ty = cdecl->getType(); 03205 return cast<FunctionType>(ty)->getNoReturnAttr(); 03206 } 03207 return false; 03208 } 03209 03210 //===----------------------------------------------------------------------===// 03211 // CFG: Queries for BlkExprs. 03212 //===----------------------------------------------------------------------===// 03213 03214 namespace { 03215 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 03216 } 03217 03218 static void FindSubExprAssignments(const Stmt *S, 03219 llvm::SmallPtrSet<const Expr*,50>& Set) { 03220 if (!S) 03221 return; 03222 03223 for (Stmt::const_child_range I = S->children(); I; ++I) { 03224 const Stmt *child = *I; 03225 if (!child) 03226 continue; 03227 03228 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 03229 if (B->isAssignmentOp()) Set.insert(B); 03230 03231 FindSubExprAssignments(child, Set); 03232 } 03233 } 03234 03235 static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 03236 BlkExprMapTy* M = new BlkExprMapTy(); 03237 03238 // Look for assignments that are used as subexpressions. These are the only 03239 // assignments that we want to *possibly* register as a block-level 03240 // expression. Basically, if an assignment occurs both in a subexpression and 03241 // at the block-level, it is a block-level expression. 03242 llvm::SmallPtrSet<const Expr*,50> SubExprAssignments; 03243 03244 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 03245 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 03246 if (const CFGStmt *S = BI->getAs<CFGStmt>()) 03247 FindSubExprAssignments(S->getStmt(), SubExprAssignments); 03248 03249 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 03250 03251 // Iterate over the statements again on identify the Expr* and Stmt* at the 03252 // block-level that are block-level expressions. 03253 03254 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 03255 const CFGStmt *CS = BI->getAs<CFGStmt>(); 03256 if (!CS) 03257 continue; 03258 if (const Expr *Exp = dyn_cast<Expr>(CS->getStmt())) { 03259 assert((Exp->IgnoreParens() == Exp) && "No parens on block-level exps"); 03260 03261 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 03262 // Assignment expressions that are not nested within another 03263 // expression are really "statements" whose value is never used by 03264 // another expression. 03265 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 03266 continue; 03267 } else if (const StmtExpr *SE = dyn_cast<StmtExpr>(Exp)) { 03268 // Special handling for statement expressions. The last statement in 03269 // the statement expression is also a block-level expr. 03270 const CompoundStmt *C = SE->getSubStmt(); 03271 if (!C->body_empty()) { 03272 const Stmt *Last = C->body_back(); 03273 if (const Expr *LastEx = dyn_cast<Expr>(Last)) 03274 Last = LastEx->IgnoreParens(); 03275 unsigned x = M->size(); 03276 (*M)[Last] = x; 03277 } 03278 } 03279 03280 unsigned x = M->size(); 03281 (*M)[Exp] = x; 03282 } 03283 } 03284 03285 // Look at terminators. The condition is a block-level expression. 03286 03287 Stmt *S = (*I)->getTerminatorCondition(); 03288 03289 if (S && M->find(S) == M->end()) { 03290 unsigned x = M->size(); 03291 (*M)[S] = x; 03292 } 03293 } 03294 03295 return M; 03296 } 03297 03298 CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt *S) { 03299 assert(S != NULL); 03300 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 03301 03302 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 03303 BlkExprMapTy::iterator I = M->find(S); 03304 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 03305 } 03306 03307 unsigned CFG::getNumBlkExprs() { 03308 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 03309 return M->size(); 03310 03311 // We assume callers interested in the number of BlkExprs will want 03312 // the map constructed if it doesn't already exist. 03313 BlkExprMap = (void*) PopulateBlkExprMap(*this); 03314 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 03315 } 03316 03317 //===----------------------------------------------------------------------===// 03318 // Filtered walking of the CFG. 03319 //===----------------------------------------------------------------------===// 03320 03321 bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 03322 const CFGBlock *From, const CFGBlock *To) { 03323 03324 if (To && F.IgnoreDefaultsWithCoveredEnums) { 03325 // If the 'To' has no label or is labeled but the label isn't a 03326 // CaseStmt then filter this edge. 03327 if (const SwitchStmt *S = 03328 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 03329 if (S->isAllEnumCasesCovered()) { 03330 const Stmt *L = To->getLabel(); 03331 if (!L || !isa<CaseStmt>(L)) 03332 return true; 03333 } 03334 } 03335 } 03336 03337 return false; 03338 } 03339 03340 //===----------------------------------------------------------------------===// 03341 // Cleanup: CFG dstor. 03342 //===----------------------------------------------------------------------===// 03343 03344 CFG::~CFG() { 03345 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 03346 } 03347 03348 //===----------------------------------------------------------------------===// 03349 // CFG pretty printing 03350 //===----------------------------------------------------------------------===// 03351 03352 namespace { 03353 03354 class StmtPrinterHelper : public PrinterHelper { 03355 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 03356 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 03357 StmtMapTy StmtMap; 03358 DeclMapTy DeclMap; 03359 signed currentBlock; 03360 unsigned currentStmt; 03361 const LangOptions &LangOpts; 03362 public: 03363 03364 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 03365 : currentBlock(0), currentStmt(0), LangOpts(LO) 03366 { 03367 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 03368 unsigned j = 1; 03369 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 03370 BI != BEnd; ++BI, ++j ) { 03371 if (const CFGStmt *SE = BI->getAs<CFGStmt>()) { 03372 const Stmt *stmt= SE->getStmt(); 03373 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 03374 StmtMap[stmt] = P; 03375 03376 switch (stmt->getStmtClass()) { 03377 case Stmt::DeclStmtClass: 03378 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 03379 break; 03380 case Stmt::IfStmtClass: { 03381 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 03382 if (var) 03383 DeclMap[var] = P; 03384 break; 03385 } 03386 case Stmt::ForStmtClass: { 03387 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 03388 if (var) 03389 DeclMap[var] = P; 03390 break; 03391 } 03392 case Stmt::WhileStmtClass: { 03393 const VarDecl *var = 03394 cast<WhileStmt>(stmt)->getConditionVariable(); 03395 if (var) 03396 DeclMap[var] = P; 03397 break; 03398 } 03399 case Stmt::SwitchStmtClass: { 03400 const VarDecl *var = 03401 cast<SwitchStmt>(stmt)->getConditionVariable(); 03402 if (var) 03403 DeclMap[var] = P; 03404 break; 03405 } 03406 case Stmt::CXXCatchStmtClass: { 03407 const VarDecl *var = 03408 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 03409 if (var) 03410 DeclMap[var] = P; 03411 break; 03412 } 03413 default: 03414 break; 03415 } 03416 } 03417 } 03418 } 03419 } 03420 03421 03422 virtual ~StmtPrinterHelper() {} 03423 03424 const LangOptions &getLangOpts() const { return LangOpts; } 03425 void setBlockID(signed i) { currentBlock = i; } 03426 void setStmtID(unsigned i) { currentStmt = i; } 03427 03428 virtual bool handledStmt(Stmt *S, raw_ostream &OS) { 03429 StmtMapTy::iterator I = StmtMap.find(S); 03430 03431 if (I == StmtMap.end()) 03432 return false; 03433 03434 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 03435 && I->second.second == currentStmt) { 03436 return false; 03437 } 03438 03439 OS << "[B" << I->second.first << "." << I->second.second << "]"; 03440 return true; 03441 } 03442 03443 bool handleDecl(const Decl *D, raw_ostream &OS) { 03444 DeclMapTy::iterator I = DeclMap.find(D); 03445 03446 if (I == DeclMap.end()) 03447 return false; 03448 03449 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 03450 && I->second.second == currentStmt) { 03451 return false; 03452 } 03453 03454 OS << "[B" << I->second.first << "." << I->second.second << "]"; 03455 return true; 03456 } 03457 }; 03458 } // end anonymous namespace 03459 03460 03461 namespace { 03462 class CFGBlockTerminatorPrint 03463 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 03464 03465 raw_ostream &OS; 03466 StmtPrinterHelper* Helper; 03467 PrintingPolicy Policy; 03468 public: 03469 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 03470 const PrintingPolicy &Policy) 03471 : OS(os), Helper(helper), Policy(Policy) {} 03472 03473 void VisitIfStmt(IfStmt *I) { 03474 OS << "if "; 03475 I->getCond()->printPretty(OS,Helper,Policy); 03476 } 03477 03478 // Default case. 03479 void VisitStmt(Stmt *Terminator) { 03480 Terminator->printPretty(OS, Helper, Policy); 03481 } 03482 03483 void VisitForStmt(ForStmt *F) { 03484 OS << "for (" ; 03485 if (F->getInit()) 03486 OS << "..."; 03487 OS << "; "; 03488 if (Stmt *C = F->getCond()) 03489 C->printPretty(OS, Helper, Policy); 03490 OS << "; "; 03491 if (F->getInc()) 03492 OS << "..."; 03493 OS << ")"; 03494 } 03495 03496 void VisitWhileStmt(WhileStmt *W) { 03497 OS << "while " ; 03498 if (Stmt *C = W->getCond()) 03499 C->printPretty(OS, Helper, Policy); 03500 } 03501 03502 void VisitDoStmt(DoStmt *D) { 03503 OS << "do ... while "; 03504 if (Stmt *C = D->getCond()) 03505 C->printPretty(OS, Helper, Policy); 03506 } 03507 03508 void VisitSwitchStmt(SwitchStmt *Terminator) { 03509 OS << "switch "; 03510 Terminator->getCond()->printPretty(OS, Helper, Policy); 03511 } 03512 03513 void VisitCXXTryStmt(CXXTryStmt *CS) { 03514 OS << "try ..."; 03515 } 03516 03517 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 03518 C->getCond()->printPretty(OS, Helper, Policy); 03519 OS << " ? ... : ..."; 03520 } 03521 03522 void VisitChooseExpr(ChooseExpr *C) { 03523 OS << "__builtin_choose_expr( "; 03524 C->getCond()->printPretty(OS, Helper, Policy); 03525 OS << " )"; 03526 } 03527 03528 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 03529 OS << "goto *"; 03530 I->getTarget()->printPretty(OS, Helper, Policy); 03531 } 03532 03533 void VisitBinaryOperator(BinaryOperator* B) { 03534 if (!B->isLogicalOp()) { 03535 VisitExpr(B); 03536 return; 03537 } 03538 03539 B->getLHS()->printPretty(OS, Helper, Policy); 03540 03541 switch (B->getOpcode()) { 03542 case BO_LOr: 03543 OS << " || ..."; 03544 return; 03545 case BO_LAnd: 03546 OS << " && ..."; 03547 return; 03548 default: 03549 llvm_unreachable("Invalid logical operator."); 03550 } 03551 } 03552 03553 void VisitExpr(Expr *E) { 03554 E->printPretty(OS, Helper, Policy); 03555 } 03556 }; 03557 } // end anonymous namespace 03558 03559 static void print_elem(raw_ostream &OS, StmtPrinterHelper* Helper, 03560 const CFGElement &E) { 03561 if (const CFGStmt *CS = E.getAs<CFGStmt>()) { 03562 const Stmt *S = CS->getStmt(); 03563 03564 if (Helper) { 03565 03566 // special printing for statement-expressions. 03567 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 03568 const CompoundStmt *Sub = SE->getSubStmt(); 03569 03570 if (Sub->children()) { 03571 OS << "({ ... ; "; 03572 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 03573 OS << " })\n"; 03574 return; 03575 } 03576 } 03577 // special printing for comma expressions. 03578 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 03579 if (B->getOpcode() == BO_Comma) { 03580 OS << "... , "; 03581 Helper->handledStmt(B->getRHS(),OS); 03582 OS << '\n'; 03583 return; 03584 } 03585 } 03586 } 03587 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 03588 03589 if (isa<CXXOperatorCallExpr>(S)) { 03590 OS << " (OperatorCall)"; 03591 } 03592 else if (isa<CXXBindTemporaryExpr>(S)) { 03593 OS << " (BindTemporary)"; 03594 } 03595 else if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(S)) { 03596 OS << " (CXXConstructExpr, " << CCE->getType().getAsString() << ")"; 03597 } 03598 else if (const CastExpr *CE = dyn_cast<CastExpr>(S)) { 03599 OS << " (" << CE->getStmtClassName() << ", " 03600 << CE->getCastKindName() 03601 << ", " << CE->getType().getAsString() 03602 << ")"; 03603 } 03604 03605 // Expressions need a newline. 03606 if (isa<Expr>(S)) 03607 OS << '\n'; 03608 03609 } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) { 03610 const CXXCtorInitializer *I = IE->getInitializer(); 03611 if (I->isBaseInitializer()) 03612 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 03613 else OS << I->getAnyMember()->getName(); 03614 03615 OS << "("; 03616 if (Expr *IE = I->getInit()) 03617 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 03618 OS << ")"; 03619 03620 if (I->isBaseInitializer()) 03621 OS << " (Base initializer)\n"; 03622 else OS << " (Member initializer)\n"; 03623 03624 } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){ 03625 const VarDecl *VD = DE->getVarDecl(); 03626 Helper->handleDecl(VD, OS); 03627 03628 const Type* T = VD->getType().getTypePtr(); 03629 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 03630 T = RT->getPointeeType().getTypePtr(); 03631 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 03632 T = ET; 03633 03634 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 03635 OS << " (Implicit destructor)\n"; 03636 03637 } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) { 03638 const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); 03639 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 03640 OS << " (Base object destructor)\n"; 03641 03642 } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) { 03643 const FieldDecl *FD = ME->getFieldDecl(); 03644 03645 const Type *T = FD->getType().getTypePtr(); 03646 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 03647 T = ET; 03648 03649 OS << "this->" << FD->getName(); 03650 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 03651 OS << " (Member object destructor)\n"; 03652 03653 } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) { 03654 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); 03655 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 03656 OS << " (Temporary object destructor)\n"; 03657 } 03658 } 03659 03660 static void print_block(raw_ostream &OS, const CFG* cfg, 03661 const CFGBlock &B, 03662 StmtPrinterHelper* Helper, bool print_edges, 03663 bool ShowColors) { 03664 03665 if (Helper) 03666 Helper->setBlockID(B.getBlockID()); 03667 03668 // Print the header. 03669 if (ShowColors) 03670 OS.changeColor(raw_ostream::YELLOW, true); 03671 03672 OS << "\n [B" << B.getBlockID(); 03673 03674 if (&B == &cfg->getEntry()) 03675 OS << " (ENTRY)]\n"; 03676 else if (&B == &cfg->getExit()) 03677 OS << " (EXIT)]\n"; 03678 else if (&B == cfg->getIndirectGotoBlock()) 03679 OS << " (INDIRECT GOTO DISPATCH)]\n"; 03680 else 03681 OS << "]\n"; 03682 03683 if (ShowColors) 03684 OS.resetColor(); 03685 03686 // Print the label of this block. 03687 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 03688 03689 if (print_edges) 03690 OS << " "; 03691 03692 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 03693 OS << L->getName(); 03694 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 03695 OS << "case "; 03696 C->getLHS()->printPretty(OS, Helper, 03697 PrintingPolicy(Helper->getLangOpts())); 03698 if (C->getRHS()) { 03699 OS << " ... "; 03700 C->getRHS()->printPretty(OS, Helper, 03701 PrintingPolicy(Helper->getLangOpts())); 03702 } 03703 } else if (isa<DefaultStmt>(Label)) 03704 OS << "default"; 03705 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 03706 OS << "catch ("; 03707 if (CS->getExceptionDecl()) 03708 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 03709 0); 03710 else 03711 OS << "..."; 03712 OS << ")"; 03713 03714 } else 03715 llvm_unreachable("Invalid label statement in CFGBlock."); 03716 03717 OS << ":\n"; 03718 } 03719 03720 // Iterate through the statements in the block and print them. 03721 unsigned j = 1; 03722 03723 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 03724 I != E ; ++I, ++j ) { 03725 03726 // Print the statement # in the basic block and the statement itself. 03727 if (print_edges) 03728 OS << " "; 03729 03730 OS << llvm::format("%3d", j) << ": "; 03731 03732 if (Helper) 03733 Helper->setStmtID(j); 03734 03735 print_elem(OS, Helper, *I); 03736 } 03737 03738 // Print the terminator of this block. 03739 if (B.getTerminator()) { 03740 if (ShowColors) 03741 OS.changeColor(raw_ostream::GREEN); 03742 03743 OS << " T: "; 03744 03745 if (Helper) Helper->setBlockID(-1); 03746 03747 CFGBlockTerminatorPrint TPrinter(OS, Helper, 03748 PrintingPolicy(Helper->getLangOpts())); 03749 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 03750 OS << '\n'; 03751 03752 if (ShowColors) 03753 OS.resetColor(); 03754 } 03755 03756 if (print_edges) { 03757 // Print the predecessors of this block. 03758 if (!B.pred_empty()) { 03759 const raw_ostream::Colors Color = raw_ostream::BLUE; 03760 if (ShowColors) 03761 OS.changeColor(Color); 03762 OS << " Preds " ; 03763 if (ShowColors) 03764 OS.resetColor(); 03765 OS << '(' << B.pred_size() << "):"; 03766 unsigned i = 0; 03767 03768 if (ShowColors) 03769 OS.changeColor(Color); 03770 03771 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 03772 I != E; ++I, ++i) { 03773 03774 if (i == 8 || (i-8) == 0) 03775 OS << "\n "; 03776 03777 OS << " B" << (*I)->getBlockID(); 03778 } 03779 03780 if (ShowColors) 03781 OS.resetColor(); 03782 03783 OS << '\n'; 03784 } 03785 03786 // Print the successors of this block. 03787 if (!B.succ_empty()) { 03788 const raw_ostream::Colors Color = raw_ostream::MAGENTA; 03789 if (ShowColors) 03790 OS.changeColor(Color); 03791 OS << " Succs "; 03792 if (ShowColors) 03793 OS.resetColor(); 03794 OS << '(' << B.succ_size() << "):"; 03795 unsigned i = 0; 03796 03797 if (ShowColors) 03798 OS.changeColor(Color); 03799 03800 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 03801 I != E; ++I, ++i) { 03802 03803 if (i == 8 || (i-8) % 10 == 0) 03804 OS << "\n "; 03805 03806 if (*I) 03807 OS << " B" << (*I)->getBlockID(); 03808 else 03809 OS << " NULL"; 03810 } 03811 03812 if (ShowColors) 03813 OS.resetColor(); 03814 OS << '\n'; 03815 } 03816 } 03817 } 03818 03819 03820 /// dump - A simple pretty printer of a CFG that outputs to stderr. 03821 void CFG::dump(const LangOptions &LO, bool ShowColors) const { 03822 print(llvm::errs(), LO, ShowColors); 03823 } 03824 03825 /// print - A simple pretty printer of a CFG that outputs to an ostream. 03826 void CFG::print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const { 03827 StmtPrinterHelper Helper(this, LO); 03828 03829 // Print the entry block. 03830 print_block(OS, this, getEntry(), &Helper, true, ShowColors); 03831 03832 // Iterate through the CFGBlocks and print them one by one. 03833 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 03834 // Skip the entry block, because we already printed it. 03835 if (&(**I) == &getEntry() || &(**I) == &getExit()) 03836 continue; 03837 03838 print_block(OS, this, **I, &Helper, true, ShowColors); 03839 } 03840 03841 // Print the exit block. 03842 print_block(OS, this, getExit(), &Helper, true, ShowColors); 03843 OS << '\n'; 03844 OS.flush(); 03845 } 03846 03847 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 03848 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO, 03849 bool ShowColors) const { 03850 print(llvm::errs(), cfg, LO, ShowColors); 03851 } 03852 03853 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 03854 /// Generally this will only be called from CFG::print. 03855 void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 03856 const LangOptions &LO, bool ShowColors) const { 03857 StmtPrinterHelper Helper(cfg, LO); 03858 print_block(OS, cfg, *this, &Helper, true, ShowColors); 03859 OS << '\n'; 03860 } 03861 03862 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 03863 void CFGBlock::printTerminator(raw_ostream &OS, 03864 const LangOptions &LO) const { 03865 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 03866 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 03867 } 03868 03869 Stmt *CFGBlock::getTerminatorCondition() { 03870 Stmt *Terminator = this->Terminator; 03871 if (!Terminator) 03872 return NULL; 03873 03874 Expr *E = NULL; 03875 03876 switch (Terminator->getStmtClass()) { 03877 default: 03878 break; 03879 03880 case Stmt::ForStmtClass: 03881 E = cast<ForStmt>(Terminator)->getCond(); 03882 break; 03883 03884 case Stmt::WhileStmtClass: 03885 E = cast<WhileStmt>(Terminator)->getCond(); 03886 break; 03887 03888 case Stmt::DoStmtClass: 03889 E = cast<DoStmt>(Terminator)->getCond(); 03890 break; 03891 03892 case Stmt::IfStmtClass: 03893 E = cast<IfStmt>(Terminator)->getCond(); 03894 break; 03895 03896 case Stmt::ChooseExprClass: 03897 E = cast<ChooseExpr>(Terminator)->getCond(); 03898 break; 03899 03900 case Stmt::IndirectGotoStmtClass: 03901 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 03902 break; 03903 03904 case Stmt::SwitchStmtClass: 03905 E = cast<SwitchStmt>(Terminator)->getCond(); 03906 break; 03907 03908 case Stmt::BinaryConditionalOperatorClass: 03909 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 03910 break; 03911 03912 case Stmt::ConditionalOperatorClass: 03913 E = cast<ConditionalOperator>(Terminator)->getCond(); 03914 break; 03915 03916 case Stmt::BinaryOperatorClass: // '&&' and '||' 03917 E = cast<BinaryOperator>(Terminator)->getLHS(); 03918 break; 03919 03920 case Stmt::ObjCForCollectionStmtClass: 03921 return Terminator; 03922 } 03923 03924 return E ? E->IgnoreParens() : NULL; 03925 } 03926 03927 //===----------------------------------------------------------------------===// 03928 // CFG Graphviz Visualization 03929 //===----------------------------------------------------------------------===// 03930 03931 03932 #ifndef NDEBUG 03933 static StmtPrinterHelper* GraphHelper; 03934 #endif 03935 03936 void CFG::viewCFG(const LangOptions &LO) const { 03937 #ifndef NDEBUG 03938 StmtPrinterHelper H(this, LO); 03939 GraphHelper = &H; 03940 llvm::ViewGraph(this,"CFG"); 03941 GraphHelper = NULL; 03942 #endif 03943 } 03944 03945 namespace llvm { 03946 template<> 03947 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 03948 03949 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 03950 03951 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { 03952 03953 #ifndef NDEBUG 03954 std::string OutSStr; 03955 llvm::raw_string_ostream Out(OutSStr); 03956 print_block(Out,Graph, *Node, GraphHelper, false, false); 03957 std::string& OutStr = Out.str(); 03958 03959 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 03960 03961 // Process string output to make it nicer... 03962 for (unsigned i = 0; i != OutStr.length(); ++i) 03963 if (OutStr[i] == '\n') { // Left justify 03964 OutStr[i] = '\\'; 03965 OutStr.insert(OutStr.begin()+i+1, 'l'); 03966 } 03967 03968 return OutStr; 03969 #else 03970 return ""; 03971 #endif 03972 } 03973 }; 03974 } // end namespace llvm