CFG.cpp revision a1364be341550d71dff27dd8de0c6872ba6c707e
1//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the CFG and CFGBuilder classes for representing and 11// building Control-Flow Graphs (CFGs) from ASTs. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Analysis/Support/SaveAndRestore.h" 16#include "clang/Analysis/CFG.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/StmtVisitor.h" 19#include "clang/AST/PrettyPrinter.h" 20#include "clang/AST/CharUnits.h" 21#include "llvm/Support/GraphWriter.h" 22#include "llvm/Support/Allocator.h" 23#include "llvm/Support/Format.h" 24#include "llvm/ADT/DenseMap.h" 25#include "llvm/ADT/SmallPtrSet.h" 26#include "llvm/ADT/OwningPtr.h" 27 28using namespace clang; 29 30namespace { 31 32static SourceLocation GetEndLoc(Decl *D) { 33 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 34 if (Expr *Ex = VD->getInit()) 35 return Ex->getSourceRange().getEnd(); 36 return D->getLocation(); 37} 38 39class CFGBuilder; 40 41/// The CFG builder uses a recursive algorithm to build the CFG. When 42/// we process an expression, sometimes we know that we must add the 43/// subexpressions as block-level expressions. For example: 44/// 45/// exp1 || exp2 46/// 47/// When processing the '||' expression, we know that exp1 and exp2 48/// need to be added as block-level expressions, even though they 49/// might not normally need to be. AddStmtChoice records this 50/// contextual information. If AddStmtChoice is 'NotAlwaysAdd', then 51/// the builder has an option not to add a subexpression as a 52/// block-level expression. 53/// 54class AddStmtChoice { 55public: 56 enum Kind { NotAlwaysAdd = 0, AlwaysAdd = 1 }; 57 58 AddStmtChoice(Kind a_kind = NotAlwaysAdd) : kind(a_kind) {} 59 60 bool alwaysAdd(CFGBuilder &builder, 61 const Stmt *stmt) const; 62 63 /// Return a copy of this object, except with the 'always-add' bit 64 /// set as specified. 65 AddStmtChoice withAlwaysAdd(bool alwaysAdd) const { 66 return AddStmtChoice(alwaysAdd ? AlwaysAdd : NotAlwaysAdd); 67 } 68 69private: 70 Kind kind; 71}; 72 73/// LocalScope - Node in tree of local scopes created for C++ implicit 74/// destructor calls generation. It contains list of automatic variables 75/// declared in the scope and link to position in previous scope this scope 76/// began in. 77/// 78/// The process of creating local scopes is as follows: 79/// - Init CFGBuilder::ScopePos with invalid position (equivalent for null), 80/// - Before processing statements in scope (e.g. CompoundStmt) create 81/// LocalScope object using CFGBuilder::ScopePos as link to previous scope 82/// and set CFGBuilder::ScopePos to the end of new scope, 83/// - On every occurrence of VarDecl increase CFGBuilder::ScopePos if it points 84/// at this VarDecl, 85/// - For every normal (without jump) end of scope add to CFGBlock destructors 86/// for objects in the current scope, 87/// - For every jump add to CFGBlock destructors for objects 88/// between CFGBuilder::ScopePos and local scope position saved for jump 89/// target. Thanks to C++ restrictions on goto jumps we can be sure that 90/// jump target position will be on the path to root from CFGBuilder::ScopePos 91/// (adding any variable that doesn't need constructor to be called to 92/// LocalScope can break this assumption), 93/// 94class LocalScope { 95public: 96 typedef BumpVector<VarDecl*> AutomaticVarsTy; 97 98 /// const_iterator - Iterates local scope backwards and jumps to previous 99 /// scope on reaching the beginning of currently iterated scope. 100 class const_iterator { 101 const LocalScope* Scope; 102 103 /// VarIter is guaranteed to be greater then 0 for every valid iterator. 104 /// Invalid iterator (with null Scope) has VarIter equal to 0. 105 unsigned VarIter; 106 107 public: 108 /// Create invalid iterator. Dereferencing invalid iterator is not allowed. 109 /// Incrementing invalid iterator is allowed and will result in invalid 110 /// iterator. 111 const_iterator() 112 : Scope(NULL), VarIter(0) {} 113 114 /// Create valid iterator. In case when S.Prev is an invalid iterator and 115 /// I is equal to 0, this will create invalid iterator. 116 const_iterator(const LocalScope& S, unsigned I) 117 : Scope(&S), VarIter(I) { 118 // Iterator to "end" of scope is not allowed. Handle it by going up 119 // in scopes tree possibly up to invalid iterator in the root. 120 if (VarIter == 0 && Scope) 121 *this = Scope->Prev; 122 } 123 124 VarDecl *const* operator->() const { 125 assert (Scope && "Dereferencing invalid iterator is not allowed"); 126 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 127 return &Scope->Vars[VarIter - 1]; 128 } 129 VarDecl *operator*() const { 130 return *this->operator->(); 131 } 132 133 const_iterator &operator++() { 134 if (!Scope) 135 return *this; 136 137 assert (VarIter != 0 && "Iterator has invalid value of VarIter member"); 138 --VarIter; 139 if (VarIter == 0) 140 *this = Scope->Prev; 141 return *this; 142 } 143 const_iterator operator++(int) { 144 const_iterator P = *this; 145 ++*this; 146 return P; 147 } 148 149 bool operator==(const const_iterator &rhs) const { 150 return Scope == rhs.Scope && VarIter == rhs.VarIter; 151 } 152 bool operator!=(const const_iterator &rhs) const { 153 return !(*this == rhs); 154 } 155 156 operator bool() const { 157 return *this != const_iterator(); 158 } 159 160 int distance(const_iterator L); 161 }; 162 163 friend class const_iterator; 164 165private: 166 BumpVectorContext ctx; 167 168 /// Automatic variables in order of declaration. 169 AutomaticVarsTy Vars; 170 /// Iterator to variable in previous scope that was declared just before 171 /// begin of this scope. 172 const_iterator Prev; 173 174public: 175 /// Constructs empty scope linked to previous scope in specified place. 176 LocalScope(BumpVectorContext &ctx, const_iterator P) 177 : ctx(ctx), Vars(ctx, 4), Prev(P) {} 178 179 /// Begin of scope in direction of CFG building (backwards). 180 const_iterator begin() const { return const_iterator(*this, Vars.size()); } 181 182 void addVar(VarDecl *VD) { 183 Vars.push_back(VD, ctx); 184 } 185}; 186 187/// distance - Calculates distance from this to L. L must be reachable from this 188/// (with use of ++ operator). Cost of calculating the distance is linear w.r.t. 189/// number of scopes between this and L. 190int LocalScope::const_iterator::distance(LocalScope::const_iterator L) { 191 int D = 0; 192 const_iterator F = *this; 193 while (F.Scope != L.Scope) { 194 assert (F != const_iterator() 195 && "L iterator is not reachable from F iterator."); 196 D += F.VarIter; 197 F = F.Scope->Prev; 198 } 199 D += F.VarIter - L.VarIter; 200 return D; 201} 202 203/// BlockScopePosPair - Structure for specifying position in CFG during its 204/// build process. It consists of CFGBlock that specifies position in CFG graph 205/// and LocalScope::const_iterator that specifies position in LocalScope graph. 206struct BlockScopePosPair { 207 BlockScopePosPair() : block(0) {} 208 BlockScopePosPair(CFGBlock *b, LocalScope::const_iterator scopePos) 209 : block(b), scopePosition(scopePos) {} 210 211 CFGBlock *block; 212 LocalScope::const_iterator scopePosition; 213}; 214 215/// TryResult - a class representing a variant over the values 216/// 'true', 'false', or 'unknown'. This is returned by tryEvaluateBool, 217/// and is used by the CFGBuilder to decide if a branch condition 218/// can be decided up front during CFG construction. 219class TryResult { 220 int X; 221public: 222 TryResult(bool b) : X(b ? 1 : 0) {} 223 TryResult() : X(-1) {} 224 225 bool isTrue() const { return X == 1; } 226 bool isFalse() const { return X == 0; } 227 bool isKnown() const { return X >= 0; } 228 void negate() { 229 assert(isKnown()); 230 X ^= 0x1; 231 } 232}; 233 234/// CFGBuilder - This class implements CFG construction from an AST. 235/// The builder is stateful: an instance of the builder should be used to only 236/// construct a single CFG. 237/// 238/// Example usage: 239/// 240/// CFGBuilder builder; 241/// CFG* cfg = builder.BuildAST(stmt1); 242/// 243/// CFG construction is done via a recursive walk of an AST. We actually parse 244/// the AST in reverse order so that the successor of a basic block is 245/// constructed prior to its predecessor. This allows us to nicely capture 246/// implicit fall-throughs without extra basic blocks. 247/// 248class CFGBuilder { 249 typedef BlockScopePosPair JumpTarget; 250 typedef BlockScopePosPair JumpSource; 251 252 ASTContext *Context; 253 llvm::OwningPtr<CFG> cfg; 254 255 CFGBlock *Block; 256 CFGBlock *Succ; 257 JumpTarget ContinueJumpTarget; 258 JumpTarget BreakJumpTarget; 259 CFGBlock *SwitchTerminatedBlock; 260 CFGBlock *DefaultCaseBlock; 261 CFGBlock *TryTerminatedBlock; 262 263 // Current position in local scope. 264 LocalScope::const_iterator ScopePos; 265 266 // LabelMap records the mapping from Label expressions to their jump targets. 267 typedef llvm::DenseMap<LabelDecl*, JumpTarget> LabelMapTy; 268 LabelMapTy LabelMap; 269 270 // A list of blocks that end with a "goto" that must be backpatched to their 271 // resolved targets upon completion of CFG construction. 272 typedef std::vector<JumpSource> BackpatchBlocksTy; 273 BackpatchBlocksTy BackpatchBlocks; 274 275 // A list of labels whose address has been taken (for indirect gotos). 276 typedef llvm::SmallPtrSet<LabelDecl*, 5> LabelSetTy; 277 LabelSetTy AddressTakenLabels; 278 279 bool badCFG; 280 const CFG::BuildOptions &BuildOpts; 281 282 // State to track for building switch statements. 283 bool switchExclusivelyCovered; 284 Expr::EvalResult *switchCond; 285 286 CFG::BuildOptions::ForcedBlkExprs::value_type *cachedEntry; 287 const Stmt *lastLookup; 288 289public: 290 explicit CFGBuilder(ASTContext *astContext, 291 const CFG::BuildOptions &buildOpts) 292 : Context(astContext), cfg(new CFG()), // crew a new CFG 293 Block(NULL), Succ(NULL), 294 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL), 295 TryTerminatedBlock(NULL), badCFG(false), BuildOpts(buildOpts), 296 switchExclusivelyCovered(false), switchCond(0), 297 cachedEntry(0), lastLookup(0) {} 298 299 // buildCFG - Used by external clients to construct the CFG. 300 CFG* buildCFG(const Decl *D, Stmt *Statement); 301 302 bool alwaysAdd(const Stmt *stmt); 303 304private: 305 // Visitors to walk an AST and construct the CFG. 306 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc); 307 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc); 308 CFGBlock *VisitBlockExpr(BlockExpr *E, AddStmtChoice asc); 309 CFGBlock *VisitBreakStmt(BreakStmt *B); 310 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S); 311 CFGBlock *VisitExprWithCleanups(ExprWithCleanups *E, 312 AddStmtChoice asc); 313 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T); 314 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S); 315 CFGBlock *VisitCXXForRangeStmt(CXXForRangeStmt *S); 316 CFGBlock *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 317 AddStmtChoice asc); 318 CFGBlock *VisitCXXConstructExpr(CXXConstructExpr *C, AddStmtChoice asc); 319 CFGBlock *VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 320 AddStmtChoice asc); 321 CFGBlock *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 322 AddStmtChoice asc); 323 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc); 324 CFGBlock *VisitCaseStmt(CaseStmt *C); 325 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc); 326 CFGBlock *VisitCompoundStmt(CompoundStmt *C); 327 CFGBlock *VisitConditionalOperator(AbstractConditionalOperator *C, 328 AddStmtChoice asc); 329 CFGBlock *VisitContinueStmt(ContinueStmt *C); 330 CFGBlock *VisitDeclStmt(DeclStmt *DS); 331 CFGBlock *VisitDeclSubExpr(DeclStmt *DS); 332 CFGBlock *VisitDefaultStmt(DefaultStmt *D); 333 CFGBlock *VisitDoStmt(DoStmt *D); 334 CFGBlock *VisitForStmt(ForStmt *F); 335 CFGBlock *VisitGotoStmt(GotoStmt *G); 336 CFGBlock *VisitIfStmt(IfStmt *I); 337 CFGBlock *VisitImplicitCastExpr(ImplicitCastExpr *E, AddStmtChoice asc); 338 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I); 339 CFGBlock *VisitLabelStmt(LabelStmt *L); 340 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc); 341 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 342 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 343 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 344 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S); 345 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 346 CFGBlock *VisitReturnStmt(ReturnStmt *R); 347 CFGBlock *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 348 AddStmtChoice asc); 349 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc); 350 CFGBlock *VisitSwitchStmt(SwitchStmt *S); 351 CFGBlock *VisitUnaryOperator(UnaryOperator *U, AddStmtChoice asc); 352 CFGBlock *VisitWhileStmt(WhileStmt *W); 353 354 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd); 355 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc); 356 CFGBlock *VisitChildren(Stmt *S); 357 358 // Visitors to walk an AST and generate destructors of temporaries in 359 // full expression. 360 CFGBlock *VisitForTemporaryDtors(Stmt *E, bool BindToTemporary = false); 361 CFGBlock *VisitChildrenForTemporaryDtors(Stmt *E); 362 CFGBlock *VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E); 363 CFGBlock *VisitCXXBindTemporaryExprForTemporaryDtors(CXXBindTemporaryExpr *E, 364 bool BindToTemporary); 365 CFGBlock * 366 VisitConditionalOperatorForTemporaryDtors(AbstractConditionalOperator *E, 367 bool BindToTemporary); 368 369 // NYS == Not Yet Supported 370 CFGBlock *NYS() { 371 badCFG = true; 372 return Block; 373 } 374 375 void autoCreateBlock() { if (!Block) Block = createBlock(); } 376 CFGBlock *createBlock(bool add_successor = true); 377 378 CFGBlock *addStmt(Stmt *S) { 379 return Visit(S, AddStmtChoice::AlwaysAdd); 380 } 381 CFGBlock *addInitializer(CXXCtorInitializer *I); 382 void addAutomaticObjDtors(LocalScope::const_iterator B, 383 LocalScope::const_iterator E, Stmt *S); 384 void addImplicitDtorsForDestructor(const CXXDestructorDecl *DD); 385 386 // Local scopes creation. 387 LocalScope* createOrReuseLocalScope(LocalScope* Scope); 388 389 void addLocalScopeForStmt(Stmt *S); 390 LocalScope* addLocalScopeForDeclStmt(DeclStmt *DS, LocalScope* Scope = NULL); 391 LocalScope* addLocalScopeForVarDecl(VarDecl *VD, LocalScope* Scope = NULL); 392 393 void addLocalScopeAndDtors(Stmt *S); 394 395 // Interface to CFGBlock - adding CFGElements. 396 void appendStmt(CFGBlock *B, const Stmt *S) { 397 if (alwaysAdd(S) && cachedEntry) 398 cachedEntry->second = B; 399 400 // All block-level expressions should have already been IgnoreParens()ed. 401 assert(!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S); 402 B->appendStmt(const_cast<Stmt*>(S), cfg->getBumpVectorContext()); 403 } 404 void appendInitializer(CFGBlock *B, CXXCtorInitializer *I) { 405 B->appendInitializer(I, cfg->getBumpVectorContext()); 406 } 407 void appendBaseDtor(CFGBlock *B, const CXXBaseSpecifier *BS) { 408 B->appendBaseDtor(BS, cfg->getBumpVectorContext()); 409 } 410 void appendMemberDtor(CFGBlock *B, FieldDecl *FD) { 411 B->appendMemberDtor(FD, cfg->getBumpVectorContext()); 412 } 413 void appendTemporaryDtor(CFGBlock *B, CXXBindTemporaryExpr *E) { 414 B->appendTemporaryDtor(E, cfg->getBumpVectorContext()); 415 } 416 417 void insertAutomaticObjDtors(CFGBlock *Blk, CFGBlock::iterator I, 418 LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt *S); 419 void appendAutomaticObjDtors(CFGBlock *Blk, LocalScope::const_iterator B, 420 LocalScope::const_iterator E, Stmt *S); 421 void prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 422 LocalScope::const_iterator B, LocalScope::const_iterator E); 423 424 void addSuccessor(CFGBlock *B, CFGBlock *S) { 425 B->addSuccessor(S, cfg->getBumpVectorContext()); 426 } 427 428 /// Try and evaluate an expression to an integer constant. 429 bool tryEvaluate(Expr *S, Expr::EvalResult &outResult) { 430 if (!BuildOpts.PruneTriviallyFalseEdges) 431 return false; 432 return !S->isTypeDependent() && 433 !S->isValueDependent() && 434 S->Evaluate(outResult, *Context); 435 } 436 437 /// tryEvaluateBool - Try and evaluate the Stmt and return 0 or 1 438 /// if we can evaluate to a known value, otherwise return -1. 439 TryResult tryEvaluateBool(Expr *S) { 440 Expr::EvalResult Result; 441 if (!tryEvaluate(S, Result)) 442 return TryResult(); 443 444 if (Result.Val.isInt()) 445 return Result.Val.getInt().getBoolValue(); 446 447 if (Result.Val.isLValue()) { 448 const Expr *e = Result.Val.getLValueBase(); 449 const CharUnits &c = Result.Val.getLValueOffset(); 450 if (!e && c.isZero()) 451 return false; 452 } 453 return TryResult(); 454 } 455 456}; 457 458inline bool AddStmtChoice::alwaysAdd(CFGBuilder &builder, 459 const Stmt *stmt) const { 460 return builder.alwaysAdd(stmt) || kind == AlwaysAdd; 461} 462 463bool CFGBuilder::alwaysAdd(const Stmt *stmt) { 464 bool shouldAdd = BuildOpts.alwaysAdd(stmt); 465 466 if (!BuildOpts.forcedBlkExprs) 467 return shouldAdd; 468 469 if (lastLookup == stmt) { 470 if (cachedEntry) { 471 assert(cachedEntry->first == stmt); 472 return true; 473 } 474 return shouldAdd; 475 } 476 477 lastLookup = stmt; 478 479 // Perform the lookup! 480 CFG::BuildOptions::ForcedBlkExprs *fb = *BuildOpts.forcedBlkExprs; 481 482 if (!fb) { 483 // No need to update 'cachedEntry', since it will always be null. 484 assert(cachedEntry == 0); 485 return shouldAdd; 486 } 487 488 CFG::BuildOptions::ForcedBlkExprs::iterator itr = fb->find(stmt); 489 if (itr == fb->end()) { 490 cachedEntry = 0; 491 return shouldAdd; 492 } 493 494 cachedEntry = &*itr; 495 return true; 496} 497 498// FIXME: Add support for dependent-sized array types in C++? 499// Does it even make sense to build a CFG for an uninstantiated template? 500static const VariableArrayType *FindVA(const Type *t) { 501 while (const ArrayType *vt = dyn_cast<ArrayType>(t)) { 502 if (const VariableArrayType *vat = dyn_cast<VariableArrayType>(vt)) 503 if (vat->getSizeExpr()) 504 return vat; 505 506 t = vt->getElementType().getTypePtr(); 507 } 508 509 return 0; 510} 511 512/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an 513/// arbitrary statement. Examples include a single expression or a function 514/// body (compound statement). The ownership of the returned CFG is 515/// transferred to the caller. If CFG construction fails, this method returns 516/// NULL. 517CFG* CFGBuilder::buildCFG(const Decl *D, Stmt *Statement) { 518 assert(cfg.get()); 519 if (!Statement) 520 return NULL; 521 522 // Create an empty block that will serve as the exit block for the CFG. Since 523 // this is the first block added to the CFG, it will be implicitly registered 524 // as the exit block. 525 Succ = createBlock(); 526 assert(Succ == &cfg->getExit()); 527 Block = NULL; // the EXIT block is empty. Create all other blocks lazily. 528 529 if (BuildOpts.AddImplicitDtors) 530 if (const CXXDestructorDecl *DD = dyn_cast_or_null<CXXDestructorDecl>(D)) 531 addImplicitDtorsForDestructor(DD); 532 533 // Visit the statements and create the CFG. 534 CFGBlock *B = addStmt(Statement); 535 536 if (badCFG) 537 return NULL; 538 539 // For C++ constructor add initializers to CFG. 540 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) { 541 for (CXXConstructorDecl::init_const_reverse_iterator I = CD->init_rbegin(), 542 E = CD->init_rend(); I != E; ++I) { 543 B = addInitializer(*I); 544 if (badCFG) 545 return NULL; 546 } 547 } 548 549 if (B) 550 Succ = B; 551 552 // Backpatch the gotos whose label -> block mappings we didn't know when we 553 // encountered them. 554 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(), 555 E = BackpatchBlocks.end(); I != E; ++I ) { 556 557 CFGBlock *B = I->block; 558 GotoStmt *G = cast<GotoStmt>(B->getTerminator()); 559 LabelMapTy::iterator LI = LabelMap.find(G->getLabel()); 560 561 // If there is no target for the goto, then we are looking at an 562 // incomplete AST. Handle this by not registering a successor. 563 if (LI == LabelMap.end()) continue; 564 565 JumpTarget JT = LI->second; 566 prependAutomaticObjDtorsWithTerminator(B, I->scopePosition, 567 JT.scopePosition); 568 addSuccessor(B, JT.block); 569 } 570 571 // Add successors to the Indirect Goto Dispatch block (if we have one). 572 if (CFGBlock *B = cfg->getIndirectGotoBlock()) 573 for (LabelSetTy::iterator I = AddressTakenLabels.begin(), 574 E = AddressTakenLabels.end(); I != E; ++I ) { 575 576 // Lookup the target block. 577 LabelMapTy::iterator LI = LabelMap.find(*I); 578 579 // If there is no target block that contains label, then we are looking 580 // at an incomplete AST. Handle this by not registering a successor. 581 if (LI == LabelMap.end()) continue; 582 583 addSuccessor(B, LI->second.block); 584 } 585 586 // Create an empty entry block that has no predecessors. 587 cfg->setEntry(createBlock()); 588 589 return cfg.take(); 590} 591 592/// createBlock - Used to lazily create blocks that are connected 593/// to the current (global) succcessor. 594CFGBlock *CFGBuilder::createBlock(bool add_successor) { 595 CFGBlock *B = cfg->createBlock(); 596 if (add_successor && Succ) 597 addSuccessor(B, Succ); 598 return B; 599} 600 601/// addInitializer - Add C++ base or member initializer element to CFG. 602CFGBlock *CFGBuilder::addInitializer(CXXCtorInitializer *I) { 603 if (!BuildOpts.AddInitializers) 604 return Block; 605 606 bool IsReference = false; 607 bool HasTemporaries = false; 608 609 // Destructors of temporaries in initialization expression should be called 610 // after initialization finishes. 611 Expr *Init = I->getInit(); 612 if (Init) { 613 if (FieldDecl *FD = I->getAnyMember()) 614 IsReference = FD->getType()->isReferenceType(); 615 HasTemporaries = isa<ExprWithCleanups>(Init); 616 617 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 618 // Generate destructors for temporaries in initialization expression. 619 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 620 IsReference); 621 } 622 } 623 624 autoCreateBlock(); 625 appendInitializer(Block, I); 626 627 if (Init) { 628 if (HasTemporaries) { 629 // For expression with temporaries go directly to subexpression to omit 630 // generating destructors for the second time. 631 return Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 632 } 633 return Visit(Init); 634 } 635 636 return Block; 637} 638 639/// addAutomaticObjDtors - Add to current block automatic objects destructors 640/// for objects in range of local scope positions. Use S as trigger statement 641/// for destructors. 642void CFGBuilder::addAutomaticObjDtors(LocalScope::const_iterator B, 643 LocalScope::const_iterator E, Stmt *S) { 644 if (!BuildOpts.AddImplicitDtors) 645 return; 646 647 if (B == E) 648 return; 649 650 autoCreateBlock(); 651 appendAutomaticObjDtors(Block, B, E, S); 652} 653 654/// addImplicitDtorsForDestructor - Add implicit destructors generated for 655/// base and member objects in destructor. 656void CFGBuilder::addImplicitDtorsForDestructor(const CXXDestructorDecl *DD) { 657 assert (BuildOpts.AddImplicitDtors 658 && "Can be called only when dtors should be added"); 659 const CXXRecordDecl *RD = DD->getParent(); 660 661 // At the end destroy virtual base objects. 662 for (CXXRecordDecl::base_class_const_iterator VI = RD->vbases_begin(), 663 VE = RD->vbases_end(); VI != VE; ++VI) { 664 const CXXRecordDecl *CD = VI->getType()->getAsCXXRecordDecl(); 665 if (!CD->hasTrivialDestructor()) { 666 autoCreateBlock(); 667 appendBaseDtor(Block, VI); 668 } 669 } 670 671 // Before virtual bases destroy direct base objects. 672 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(), 673 BE = RD->bases_end(); BI != BE; ++BI) { 674 if (!BI->isVirtual()) { 675 const CXXRecordDecl *CD = BI->getType()->getAsCXXRecordDecl(); 676 if (!CD->hasTrivialDestructor()) { 677 autoCreateBlock(); 678 appendBaseDtor(Block, BI); 679 } 680 } 681 } 682 683 // First destroy member objects. 684 for (CXXRecordDecl::field_iterator FI = RD->field_begin(), 685 FE = RD->field_end(); FI != FE; ++FI) { 686 // Check for constant size array. Set type to array element type. 687 QualType QT = FI->getType(); 688 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 689 if (AT->getSize() == 0) 690 continue; 691 QT = AT->getElementType(); 692 } 693 694 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 695 if (!CD->hasTrivialDestructor()) { 696 autoCreateBlock(); 697 appendMemberDtor(Block, *FI); 698 } 699 } 700} 701 702/// createOrReuseLocalScope - If Scope is NULL create new LocalScope. Either 703/// way return valid LocalScope object. 704LocalScope* CFGBuilder::createOrReuseLocalScope(LocalScope* Scope) { 705 if (!Scope) { 706 llvm::BumpPtrAllocator &alloc = cfg->getAllocator(); 707 Scope = alloc.Allocate<LocalScope>(); 708 BumpVectorContext ctx(alloc); 709 new (Scope) LocalScope(ctx, ScopePos); 710 } 711 return Scope; 712} 713 714/// addLocalScopeForStmt - Add LocalScope to local scopes tree for statement 715/// that should create implicit scope (e.g. if/else substatements). 716void CFGBuilder::addLocalScopeForStmt(Stmt *S) { 717 if (!BuildOpts.AddImplicitDtors) 718 return; 719 720 LocalScope *Scope = 0; 721 722 // For compound statement we will be creating explicit scope. 723 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(S)) { 724 for (CompoundStmt::body_iterator BI = CS->body_begin(), BE = CS->body_end() 725 ; BI != BE; ++BI) { 726 Stmt *SI = (*BI)->stripLabelLikeStatements(); 727 if (DeclStmt *DS = dyn_cast<DeclStmt>(SI)) 728 Scope = addLocalScopeForDeclStmt(DS, Scope); 729 } 730 return; 731 } 732 733 // For any other statement scope will be implicit and as such will be 734 // interesting only for DeclStmt. 735 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->stripLabelLikeStatements())) 736 addLocalScopeForDeclStmt(DS); 737} 738 739/// addLocalScopeForDeclStmt - Add LocalScope for declaration statement. Will 740/// reuse Scope if not NULL. 741LocalScope* CFGBuilder::addLocalScopeForDeclStmt(DeclStmt *DS, 742 LocalScope* Scope) { 743 if (!BuildOpts.AddImplicitDtors) 744 return Scope; 745 746 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end() 747 ; DI != DE; ++DI) { 748 if (VarDecl *VD = dyn_cast<VarDecl>(*DI)) 749 Scope = addLocalScopeForVarDecl(VD, Scope); 750 } 751 return Scope; 752} 753 754/// addLocalScopeForVarDecl - Add LocalScope for variable declaration. It will 755/// create add scope for automatic objects and temporary objects bound to 756/// const reference. Will reuse Scope if not NULL. 757LocalScope* CFGBuilder::addLocalScopeForVarDecl(VarDecl *VD, 758 LocalScope* Scope) { 759 if (!BuildOpts.AddImplicitDtors) 760 return Scope; 761 762 // Check if variable is local. 763 switch (VD->getStorageClass()) { 764 case SC_None: 765 case SC_Auto: 766 case SC_Register: 767 break; 768 default: return Scope; 769 } 770 771 // Check for const references bound to temporary. Set type to pointee. 772 QualType QT = VD->getType(); 773 if (const ReferenceType* RT = QT.getTypePtr()->getAs<ReferenceType>()) { 774 QT = RT->getPointeeType(); 775 if (!QT.isConstQualified()) 776 return Scope; 777 if (!VD->extendsLifetimeOfTemporary()) 778 return Scope; 779 } 780 781 // Check for constant size array. Set type to array element type. 782 if (const ConstantArrayType *AT = Context->getAsConstantArrayType(QT)) { 783 if (AT->getSize() == 0) 784 return Scope; 785 QT = AT->getElementType(); 786 } 787 788 // Check if type is a C++ class with non-trivial destructor. 789 if (const CXXRecordDecl *CD = QT->getAsCXXRecordDecl()) 790 if (!CD->hasTrivialDestructor()) { 791 // Add the variable to scope 792 Scope = createOrReuseLocalScope(Scope); 793 Scope->addVar(VD); 794 ScopePos = Scope->begin(); 795 } 796 return Scope; 797} 798 799/// addLocalScopeAndDtors - For given statement add local scope for it and 800/// add destructors that will cleanup the scope. Will reuse Scope if not NULL. 801void CFGBuilder::addLocalScopeAndDtors(Stmt *S) { 802 if (!BuildOpts.AddImplicitDtors) 803 return; 804 805 LocalScope::const_iterator scopeBeginPos = ScopePos; 806 addLocalScopeForStmt(S); 807 addAutomaticObjDtors(ScopePos, scopeBeginPos, S); 808} 809 810/// insertAutomaticObjDtors - Insert destructor CFGElements for variables with 811/// automatic storage duration to CFGBlock's elements vector. Insertion will be 812/// performed in place specified with iterator. 813void CFGBuilder::insertAutomaticObjDtors(CFGBlock *Blk, CFGBlock::iterator I, 814 LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt *S) { 815 BumpVectorContext &C = cfg->getBumpVectorContext(); 816 I = Blk->beginAutomaticObjDtorsInsert(I, B.distance(E), C); 817 while (B != E) 818 I = Blk->insertAutomaticObjDtor(I, *B++, S); 819} 820 821/// appendAutomaticObjDtors - Append destructor CFGElements for variables with 822/// automatic storage duration to CFGBlock's elements vector. Elements will be 823/// appended to physical end of the vector which happens to be logical 824/// beginning. 825void CFGBuilder::appendAutomaticObjDtors(CFGBlock *Blk, 826 LocalScope::const_iterator B, LocalScope::const_iterator E, Stmt *S) { 827 insertAutomaticObjDtors(Blk, Blk->begin(), B, E, S); 828} 829 830/// prependAutomaticObjDtorsWithTerminator - Prepend destructor CFGElements for 831/// variables with automatic storage duration to CFGBlock's elements vector. 832/// Elements will be prepended to physical beginning of the vector which 833/// happens to be logical end. Use blocks terminator as statement that specifies 834/// destructors call site. 835void CFGBuilder::prependAutomaticObjDtorsWithTerminator(CFGBlock *Blk, 836 LocalScope::const_iterator B, LocalScope::const_iterator E) { 837 insertAutomaticObjDtors(Blk, Blk->end(), B, E, Blk->getTerminator()); 838} 839 840/// Visit - Walk the subtree of a statement and add extra 841/// blocks for ternary operators, &&, and ||. We also process "," and 842/// DeclStmts (which may contain nested control-flow). 843CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) { 844 if (!S) { 845 badCFG = true; 846 return 0; 847 } 848 849 if (Expr *E = dyn_cast<Expr>(S)) 850 S = E->IgnoreParens(); 851 852 switch (S->getStmtClass()) { 853 default: 854 return VisitStmt(S, asc); 855 856 case Stmt::AddrLabelExprClass: 857 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc); 858 859 case Stmt::BinaryConditionalOperatorClass: 860 return VisitConditionalOperator(cast<BinaryConditionalOperator>(S), asc); 861 862 case Stmt::BinaryOperatorClass: 863 return VisitBinaryOperator(cast<BinaryOperator>(S), asc); 864 865 case Stmt::BlockExprClass: 866 return VisitBlockExpr(cast<BlockExpr>(S), asc); 867 868 case Stmt::BreakStmtClass: 869 return VisitBreakStmt(cast<BreakStmt>(S)); 870 871 case Stmt::CallExprClass: 872 case Stmt::CXXOperatorCallExprClass: 873 case Stmt::CXXMemberCallExprClass: 874 return VisitCallExpr(cast<CallExpr>(S), asc); 875 876 case Stmt::CaseStmtClass: 877 return VisitCaseStmt(cast<CaseStmt>(S)); 878 879 case Stmt::ChooseExprClass: 880 return VisitChooseExpr(cast<ChooseExpr>(S), asc); 881 882 case Stmt::CompoundStmtClass: 883 return VisitCompoundStmt(cast<CompoundStmt>(S)); 884 885 case Stmt::ConditionalOperatorClass: 886 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc); 887 888 case Stmt::ContinueStmtClass: 889 return VisitContinueStmt(cast<ContinueStmt>(S)); 890 891 case Stmt::CXXCatchStmtClass: 892 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S)); 893 894 case Stmt::ExprWithCleanupsClass: 895 return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc); 896 897 case Stmt::CXXBindTemporaryExprClass: 898 return VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), asc); 899 900 case Stmt::CXXConstructExprClass: 901 return VisitCXXConstructExpr(cast<CXXConstructExpr>(S), asc); 902 903 case Stmt::CXXFunctionalCastExprClass: 904 return VisitCXXFunctionalCastExpr(cast<CXXFunctionalCastExpr>(S), asc); 905 906 case Stmt::CXXTemporaryObjectExprClass: 907 return VisitCXXTemporaryObjectExpr(cast<CXXTemporaryObjectExpr>(S), asc); 908 909 case Stmt::CXXThrowExprClass: 910 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S)); 911 912 case Stmt::CXXTryStmtClass: 913 return VisitCXXTryStmt(cast<CXXTryStmt>(S)); 914 915 case Stmt::CXXForRangeStmtClass: 916 return VisitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 917 918 case Stmt::DeclStmtClass: 919 return VisitDeclStmt(cast<DeclStmt>(S)); 920 921 case Stmt::DefaultStmtClass: 922 return VisitDefaultStmt(cast<DefaultStmt>(S)); 923 924 case Stmt::DoStmtClass: 925 return VisitDoStmt(cast<DoStmt>(S)); 926 927 case Stmt::ForStmtClass: 928 return VisitForStmt(cast<ForStmt>(S)); 929 930 case Stmt::GotoStmtClass: 931 return VisitGotoStmt(cast<GotoStmt>(S)); 932 933 case Stmt::IfStmtClass: 934 return VisitIfStmt(cast<IfStmt>(S)); 935 936 case Stmt::ImplicitCastExprClass: 937 return VisitImplicitCastExpr(cast<ImplicitCastExpr>(S), asc); 938 939 case Stmt::IndirectGotoStmtClass: 940 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S)); 941 942 case Stmt::LabelStmtClass: 943 return VisitLabelStmt(cast<LabelStmt>(S)); 944 945 case Stmt::MemberExprClass: 946 return VisitMemberExpr(cast<MemberExpr>(S), asc); 947 948 case Stmt::ObjCAtCatchStmtClass: 949 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S)); 950 951 case Stmt::ObjCAtSynchronizedStmtClass: 952 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S)); 953 954 case Stmt::ObjCAtThrowStmtClass: 955 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S)); 956 957 case Stmt::ObjCAtTryStmtClass: 958 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S)); 959 960 case Stmt::ObjCForCollectionStmtClass: 961 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S)); 962 963 case Stmt::NullStmtClass: 964 return Block; 965 966 case Stmt::ReturnStmtClass: 967 return VisitReturnStmt(cast<ReturnStmt>(S)); 968 969 case Stmt::UnaryExprOrTypeTraitExprClass: 970 return VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S), 971 asc); 972 973 case Stmt::StmtExprClass: 974 return VisitStmtExpr(cast<StmtExpr>(S), asc); 975 976 case Stmt::SwitchStmtClass: 977 return VisitSwitchStmt(cast<SwitchStmt>(S)); 978 979 case Stmt::UnaryOperatorClass: 980 return VisitUnaryOperator(cast<UnaryOperator>(S), asc); 981 982 case Stmt::WhileStmtClass: 983 return VisitWhileStmt(cast<WhileStmt>(S)); 984 } 985} 986 987CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) { 988 if (asc.alwaysAdd(*this, S)) { 989 autoCreateBlock(); 990 appendStmt(Block, S); 991 } 992 993 return VisitChildren(S); 994} 995 996/// VisitChildren - Visit the children of a Stmt. 997CFGBlock *CFGBuilder::VisitChildren(Stmt *Terminator) { 998 CFGBlock *lastBlock = Block; 999 for (Stmt::child_range I = Terminator->children(); I; ++I) 1000 if (Stmt *child = *I) 1001 if (CFGBlock *b = Visit(child)) 1002 lastBlock = b; 1003 1004 return lastBlock; 1005} 1006 1007CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, 1008 AddStmtChoice asc) { 1009 AddressTakenLabels.insert(A->getLabel()); 1010 1011 if (asc.alwaysAdd(*this, A)) { 1012 autoCreateBlock(); 1013 appendStmt(Block, A); 1014 } 1015 1016 return Block; 1017} 1018 1019CFGBlock *CFGBuilder::VisitUnaryOperator(UnaryOperator *U, 1020 AddStmtChoice asc) { 1021 if (asc.alwaysAdd(*this, U)) { 1022 autoCreateBlock(); 1023 appendStmt(Block, U); 1024 } 1025 1026 return Visit(U->getSubExpr(), AddStmtChoice()); 1027} 1028 1029CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, 1030 AddStmtChoice asc) { 1031 if (B->isLogicalOp()) { // && or || 1032 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1033 appendStmt(ConfluenceBlock, B); 1034 1035 if (badCFG) 1036 return 0; 1037 1038 // create the block evaluating the LHS 1039 CFGBlock *LHSBlock = createBlock(false); 1040 LHSBlock->setTerminator(B); 1041 1042 // create the block evaluating the RHS 1043 Succ = ConfluenceBlock; 1044 Block = NULL; 1045 CFGBlock *RHSBlock = addStmt(B->getRHS()); 1046 1047 if (RHSBlock) { 1048 if (badCFG) 1049 return 0; 1050 } else { 1051 // Create an empty block for cases where the RHS doesn't require 1052 // any explicit statements in the CFG. 1053 RHSBlock = createBlock(); 1054 } 1055 1056 // See if this is a known constant. 1057 TryResult KnownVal = tryEvaluateBool(B->getLHS()); 1058 if (KnownVal.isKnown() && (B->getOpcode() == BO_LOr)) 1059 KnownVal.negate(); 1060 1061 // Now link the LHSBlock with RHSBlock. 1062 if (B->getOpcode() == BO_LOr) { 1063 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 1064 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 1065 } else { 1066 assert(B->getOpcode() == BO_LAnd); 1067 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 1068 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 1069 } 1070 1071 // Generate the blocks for evaluating the LHS. 1072 Block = LHSBlock; 1073 return addStmt(B->getLHS()); 1074 } 1075 1076 if (B->getOpcode() == BO_Comma) { // , 1077 autoCreateBlock(); 1078 appendStmt(Block, B); 1079 addStmt(B->getRHS()); 1080 return addStmt(B->getLHS()); 1081 } 1082 1083 if (B->isAssignmentOp()) { 1084 if (asc.alwaysAdd(*this, B)) { 1085 autoCreateBlock(); 1086 appendStmt(Block, B); 1087 } 1088 Visit(B->getLHS()); 1089 return Visit(B->getRHS()); 1090 } 1091 1092 if (asc.alwaysAdd(*this, B)) { 1093 autoCreateBlock(); 1094 appendStmt(Block, B); 1095 } 1096 1097 CFGBlock *RBlock = Visit(B->getRHS()); 1098 CFGBlock *LBlock = Visit(B->getLHS()); 1099 // If visiting RHS causes us to finish 'Block', e.g. the RHS is a StmtExpr 1100 // containing a DoStmt, and the LHS doesn't create a new block, then we should 1101 // return RBlock. Otherwise we'll incorrectly return NULL. 1102 return (LBlock ? LBlock : RBlock); 1103} 1104 1105CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) { 1106 if (asc.alwaysAdd(*this, E)) { 1107 autoCreateBlock(); 1108 appendStmt(Block, E); 1109 } 1110 return Block; 1111} 1112 1113CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) { 1114 // "break" is a control-flow statement. Thus we stop processing the current 1115 // block. 1116 if (badCFG) 1117 return 0; 1118 1119 // Now create a new block that ends with the break statement. 1120 Block = createBlock(false); 1121 Block->setTerminator(B); 1122 1123 // If there is no target for the break, then we are looking at an incomplete 1124 // AST. This means that the CFG cannot be constructed. 1125 if (BreakJumpTarget.block) { 1126 addAutomaticObjDtors(ScopePos, BreakJumpTarget.scopePosition, B); 1127 addSuccessor(Block, BreakJumpTarget.block); 1128 } else 1129 badCFG = true; 1130 1131 1132 return Block; 1133} 1134 1135static bool CanThrow(Expr *E, ASTContext &Ctx) { 1136 QualType Ty = E->getType(); 1137 if (Ty->isFunctionPointerType()) 1138 Ty = Ty->getAs<PointerType>()->getPointeeType(); 1139 else if (Ty->isBlockPointerType()) 1140 Ty = Ty->getAs<BlockPointerType>()->getPointeeType(); 1141 1142 const FunctionType *FT = Ty->getAs<FunctionType>(); 1143 if (FT) { 1144 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) 1145 if (Proto->isNothrow(Ctx)) 1146 return false; 1147 } 1148 return true; 1149} 1150 1151CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { 1152 // Compute the callee type. 1153 QualType calleeType = C->getCallee()->getType(); 1154 if (calleeType == Context->BoundMemberTy) { 1155 QualType boundType = Expr::findBoundMemberType(C->getCallee()); 1156 1157 // We should only get a null bound type if processing a dependent 1158 // CFG. Recover by assuming nothing. 1159 if (!boundType.isNull()) calleeType = boundType; 1160 } 1161 1162 // If this is a call to a no-return function, this stops the block here. 1163 bool NoReturn = getFunctionExtInfo(*calleeType).getNoReturn(); 1164 1165 bool AddEHEdge = false; 1166 1167 // Languages without exceptions are assumed to not throw. 1168 if (Context->getLangOptions().Exceptions) { 1169 if (BuildOpts.AddEHEdges) 1170 AddEHEdge = true; 1171 } 1172 1173 if (FunctionDecl *FD = C->getDirectCallee()) { 1174 if (FD->hasAttr<NoReturnAttr>()) 1175 NoReturn = true; 1176 if (FD->hasAttr<NoThrowAttr>()) 1177 AddEHEdge = false; 1178 } 1179 1180 if (!CanThrow(C->getCallee(), *Context)) 1181 AddEHEdge = false; 1182 1183 if (!NoReturn && !AddEHEdge) 1184 return VisitStmt(C, asc.withAlwaysAdd(true)); 1185 1186 if (Block) { 1187 Succ = Block; 1188 if (badCFG) 1189 return 0; 1190 } 1191 1192 Block = createBlock(!NoReturn); 1193 appendStmt(Block, C); 1194 1195 if (NoReturn) { 1196 // Wire this to the exit block directly. 1197 addSuccessor(Block, &cfg->getExit()); 1198 } 1199 if (AddEHEdge) { 1200 // Add exceptional edges. 1201 if (TryTerminatedBlock) 1202 addSuccessor(Block, TryTerminatedBlock); 1203 else 1204 addSuccessor(Block, &cfg->getExit()); 1205 } 1206 1207 return VisitChildren(C); 1208} 1209 1210CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C, 1211 AddStmtChoice asc) { 1212 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1213 appendStmt(ConfluenceBlock, C); 1214 if (badCFG) 1215 return 0; 1216 1217 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 1218 Succ = ConfluenceBlock; 1219 Block = NULL; 1220 CFGBlock *LHSBlock = Visit(C->getLHS(), alwaysAdd); 1221 if (badCFG) 1222 return 0; 1223 1224 Succ = ConfluenceBlock; 1225 Block = NULL; 1226 CFGBlock *RHSBlock = Visit(C->getRHS(), alwaysAdd); 1227 if (badCFG) 1228 return 0; 1229 1230 Block = createBlock(false); 1231 // See if this is a known constant. 1232 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 1233 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 1234 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 1235 Block->setTerminator(C); 1236 return addStmt(C->getCond()); 1237} 1238 1239 1240CFGBlock *CFGBuilder::VisitCompoundStmt(CompoundStmt *C) { 1241 addLocalScopeAndDtors(C); 1242 CFGBlock *LastBlock = Block; 1243 1244 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend(); 1245 I != E; ++I ) { 1246 // If we hit a segment of code just containing ';' (NullStmts), we can 1247 // get a null block back. In such cases, just use the LastBlock 1248 if (CFGBlock *newBlock = addStmt(*I)) 1249 LastBlock = newBlock; 1250 1251 if (badCFG) 1252 return NULL; 1253 } 1254 1255 return LastBlock; 1256} 1257 1258CFGBlock *CFGBuilder::VisitConditionalOperator(AbstractConditionalOperator *C, 1259 AddStmtChoice asc) { 1260 const BinaryConditionalOperator *BCO = dyn_cast<BinaryConditionalOperator>(C); 1261 const OpaqueValueExpr *opaqueValue = (BCO ? BCO->getOpaqueValue() : NULL); 1262 1263 // Create the confluence block that will "merge" the results of the ternary 1264 // expression. 1265 CFGBlock *ConfluenceBlock = Block ? Block : createBlock(); 1266 appendStmt(ConfluenceBlock, C); 1267 if (badCFG) 1268 return 0; 1269 1270 AddStmtChoice alwaysAdd = asc.withAlwaysAdd(true); 1271 1272 // Create a block for the LHS expression if there is an LHS expression. A 1273 // GCC extension allows LHS to be NULL, causing the condition to be the 1274 // value that is returned instead. 1275 // e.g: x ?: y is shorthand for: x ? x : y; 1276 Succ = ConfluenceBlock; 1277 Block = NULL; 1278 CFGBlock *LHSBlock = 0; 1279 const Expr *trueExpr = C->getTrueExpr(); 1280 if (trueExpr != opaqueValue) { 1281 LHSBlock = Visit(C->getTrueExpr(), alwaysAdd); 1282 if (badCFG) 1283 return 0; 1284 Block = NULL; 1285 } 1286 else 1287 LHSBlock = ConfluenceBlock; 1288 1289 // Create the block for the RHS expression. 1290 Succ = ConfluenceBlock; 1291 CFGBlock *RHSBlock = Visit(C->getFalseExpr(), alwaysAdd); 1292 if (badCFG) 1293 return 0; 1294 1295 // Create the block that will contain the condition. 1296 Block = createBlock(false); 1297 1298 // See if this is a known constant. 1299 const TryResult& KnownVal = tryEvaluateBool(C->getCond()); 1300 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 1301 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 1302 Block->setTerminator(C); 1303 Expr *condExpr = C->getCond(); 1304 1305 if (opaqueValue) { 1306 // Run the condition expression if it's not trivially expressed in 1307 // terms of the opaque value (or if there is no opaque value). 1308 if (condExpr != opaqueValue) 1309 addStmt(condExpr); 1310 1311 // Before that, run the common subexpression if there was one. 1312 // At least one of this or the above will be run. 1313 return addStmt(BCO->getCommon()); 1314 } 1315 1316 return addStmt(condExpr); 1317} 1318 1319CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) { 1320 // Check if the Decl is for an __label__. If so, elide it from the 1321 // CFG entirely. 1322 if (isa<LabelDecl>(*DS->decl_begin())) 1323 return Block; 1324 1325 // This case also handles static_asserts. 1326 if (DS->isSingleDecl()) 1327 return VisitDeclSubExpr(DS); 1328 1329 CFGBlock *B = 0; 1330 1331 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy. 1332 typedef SmallVector<Decl*,10> BufTy; 1333 BufTy Buf(DS->decl_begin(), DS->decl_end()); 1334 1335 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) { 1336 // Get the alignment of the new DeclStmt, padding out to >=8 bytes. 1337 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8 1338 ? 8 : llvm::AlignOf<DeclStmt>::Alignment; 1339 1340 // Allocate the DeclStmt using the BumpPtrAllocator. It will get 1341 // automatically freed with the CFG. 1342 DeclGroupRef DG(*I); 1343 Decl *D = *I; 1344 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A); 1345 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D)); 1346 1347 // Append the fake DeclStmt to block. 1348 B = VisitDeclSubExpr(DSNew); 1349 } 1350 1351 return B; 1352} 1353 1354/// VisitDeclSubExpr - Utility method to add block-level expressions for 1355/// DeclStmts and initializers in them. 1356CFGBlock *CFGBuilder::VisitDeclSubExpr(DeclStmt *DS) { 1357 assert(DS->isSingleDecl() && "Can handle single declarations only."); 1358 Decl *D = DS->getSingleDecl(); 1359 1360 if (isa<StaticAssertDecl>(D)) { 1361 // static_asserts aren't added to the CFG because they do not impact 1362 // runtime semantics. 1363 return Block; 1364 } 1365 1366 VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()); 1367 1368 if (!VD) { 1369 autoCreateBlock(); 1370 appendStmt(Block, DS); 1371 return Block; 1372 } 1373 1374 bool IsReference = false; 1375 bool HasTemporaries = false; 1376 1377 // Destructors of temporaries in initialization expression should be called 1378 // after initialization finishes. 1379 Expr *Init = VD->getInit(); 1380 if (Init) { 1381 IsReference = VD->getType()->isReferenceType(); 1382 HasTemporaries = isa<ExprWithCleanups>(Init); 1383 1384 if (BuildOpts.AddImplicitDtors && HasTemporaries) { 1385 // Generate destructors for temporaries in initialization expression. 1386 VisitForTemporaryDtors(cast<ExprWithCleanups>(Init)->getSubExpr(), 1387 IsReference); 1388 } 1389 } 1390 1391 autoCreateBlock(); 1392 appendStmt(Block, DS); 1393 1394 if (Init) { 1395 if (HasTemporaries) 1396 // For expression with temporaries go directly to subexpression to omit 1397 // generating destructors for the second time. 1398 Visit(cast<ExprWithCleanups>(Init)->getSubExpr()); 1399 else 1400 Visit(Init); 1401 } 1402 1403 // If the type of VD is a VLA, then we must process its size expressions. 1404 for (const VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); 1405 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 1406 Block = addStmt(VA->getSizeExpr()); 1407 1408 // Remove variable from local scope. 1409 if (ScopePos && VD == *ScopePos) 1410 ++ScopePos; 1411 1412 return Block; 1413} 1414 1415CFGBlock *CFGBuilder::VisitIfStmt(IfStmt *I) { 1416 // We may see an if statement in the middle of a basic block, or it may be the 1417 // first statement we are processing. In either case, we create a new basic 1418 // block. First, we create the blocks for the then...else statements, and 1419 // then we create the block containing the if statement. If we were in the 1420 // middle of a block, we stop processing that block. That block is then the 1421 // implicit successor for the "then" and "else" clauses. 1422 1423 // Save local scope position because in case of condition variable ScopePos 1424 // won't be restored when traversing AST. 1425 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1426 1427 // Create local scope for possible condition variable. 1428 // Store scope position. Add implicit destructor. 1429 if (VarDecl *VD = I->getConditionVariable()) { 1430 LocalScope::const_iterator BeginScopePos = ScopePos; 1431 addLocalScopeForVarDecl(VD); 1432 addAutomaticObjDtors(ScopePos, BeginScopePos, I); 1433 } 1434 1435 // The block we were processing is now finished. Make it the successor 1436 // block. 1437 if (Block) { 1438 Succ = Block; 1439 if (badCFG) 1440 return 0; 1441 } 1442 1443 // Process the false branch. 1444 CFGBlock *ElseBlock = Succ; 1445 1446 if (Stmt *Else = I->getElse()) { 1447 SaveAndRestore<CFGBlock*> sv(Succ); 1448 1449 // NULL out Block so that the recursive call to Visit will 1450 // create a new basic block. 1451 Block = NULL; 1452 1453 // If branch is not a compound statement create implicit scope 1454 // and add destructors. 1455 if (!isa<CompoundStmt>(Else)) 1456 addLocalScopeAndDtors(Else); 1457 1458 ElseBlock = addStmt(Else); 1459 1460 if (!ElseBlock) // Can occur when the Else body has all NullStmts. 1461 ElseBlock = sv.get(); 1462 else if (Block) { 1463 if (badCFG) 1464 return 0; 1465 } 1466 } 1467 1468 // Process the true branch. 1469 CFGBlock *ThenBlock; 1470 { 1471 Stmt *Then = I->getThen(); 1472 assert(Then); 1473 SaveAndRestore<CFGBlock*> sv(Succ); 1474 Block = NULL; 1475 1476 // If branch is not a compound statement create implicit scope 1477 // and add destructors. 1478 if (!isa<CompoundStmt>(Then)) 1479 addLocalScopeAndDtors(Then); 1480 1481 ThenBlock = addStmt(Then); 1482 1483 if (!ThenBlock) { 1484 // We can reach here if the "then" body has all NullStmts. 1485 // Create an empty block so we can distinguish between true and false 1486 // branches in path-sensitive analyses. 1487 ThenBlock = createBlock(false); 1488 addSuccessor(ThenBlock, sv.get()); 1489 } else if (Block) { 1490 if (badCFG) 1491 return 0; 1492 } 1493 } 1494 1495 // Now create a new block containing the if statement. 1496 Block = createBlock(false); 1497 1498 // Set the terminator of the new block to the If statement. 1499 Block->setTerminator(I); 1500 1501 // See if this is a known constant. 1502 const TryResult &KnownVal = tryEvaluateBool(I->getCond()); 1503 1504 // Now add the successors. 1505 addSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock); 1506 addSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock); 1507 1508 // Add the condition as the last statement in the new block. This may create 1509 // new blocks as the condition may contain control-flow. Any newly created 1510 // blocks will be pointed to be "Block". 1511 Block = addStmt(I->getCond()); 1512 1513 // Finally, if the IfStmt contains a condition variable, add both the IfStmt 1514 // and the condition variable initialization to the CFG. 1515 if (VarDecl *VD = I->getConditionVariable()) { 1516 if (Expr *Init = VD->getInit()) { 1517 autoCreateBlock(); 1518 appendStmt(Block, I->getConditionVariableDeclStmt()); 1519 addStmt(Init); 1520 } 1521 } 1522 1523 return Block; 1524} 1525 1526 1527CFGBlock *CFGBuilder::VisitReturnStmt(ReturnStmt *R) { 1528 // If we were in the middle of a block we stop processing that block. 1529 // 1530 // NOTE: If a "return" appears in the middle of a block, this means that the 1531 // code afterwards is DEAD (unreachable). We still keep a basic block 1532 // for that code; a simple "mark-and-sweep" from the entry block will be 1533 // able to report such dead blocks. 1534 1535 // Create the new block. 1536 Block = createBlock(false); 1537 1538 // The Exit block is the only successor. 1539 addAutomaticObjDtors(ScopePos, LocalScope::const_iterator(), R); 1540 addSuccessor(Block, &cfg->getExit()); 1541 1542 // Add the return statement to the block. This may create new blocks if R 1543 // contains control-flow (short-circuit operations). 1544 return VisitStmt(R, AddStmtChoice::AlwaysAdd); 1545} 1546 1547CFGBlock *CFGBuilder::VisitLabelStmt(LabelStmt *L) { 1548 // Get the block of the labeled statement. Add it to our map. 1549 addStmt(L->getSubStmt()); 1550 CFGBlock *LabelBlock = Block; 1551 1552 if (!LabelBlock) // This can happen when the body is empty, i.e. 1553 LabelBlock = createBlock(); // scopes that only contains NullStmts. 1554 1555 assert(LabelMap.find(L->getDecl()) == LabelMap.end() && 1556 "label already in map"); 1557 LabelMap[L->getDecl()] = JumpTarget(LabelBlock, ScopePos); 1558 1559 // Labels partition blocks, so this is the end of the basic block we were 1560 // processing (L is the block's label). Because this is label (and we have 1561 // already processed the substatement) there is no extra control-flow to worry 1562 // about. 1563 LabelBlock->setLabel(L); 1564 if (badCFG) 1565 return 0; 1566 1567 // We set Block to NULL to allow lazy creation of a new block (if necessary); 1568 Block = NULL; 1569 1570 // This block is now the implicit successor of other blocks. 1571 Succ = LabelBlock; 1572 1573 return LabelBlock; 1574} 1575 1576CFGBlock *CFGBuilder::VisitGotoStmt(GotoStmt *G) { 1577 // Goto is a control-flow statement. Thus we stop processing the current 1578 // block and create a new one. 1579 1580 Block = createBlock(false); 1581 Block->setTerminator(G); 1582 1583 // If we already know the mapping to the label block add the successor now. 1584 LabelMapTy::iterator I = LabelMap.find(G->getLabel()); 1585 1586 if (I == LabelMap.end()) 1587 // We will need to backpatch this block later. 1588 BackpatchBlocks.push_back(JumpSource(Block, ScopePos)); 1589 else { 1590 JumpTarget JT = I->second; 1591 addAutomaticObjDtors(ScopePos, JT.scopePosition, G); 1592 addSuccessor(Block, JT.block); 1593 } 1594 1595 return Block; 1596} 1597 1598CFGBlock *CFGBuilder::VisitForStmt(ForStmt *F) { 1599 CFGBlock *LoopSuccessor = NULL; 1600 1601 // Save local scope position because in case of condition variable ScopePos 1602 // won't be restored when traversing AST. 1603 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1604 1605 // Create local scope for init statement and possible condition variable. 1606 // Add destructor for init statement and condition variable. 1607 // Store scope position for continue statement. 1608 if (Stmt *Init = F->getInit()) 1609 addLocalScopeForStmt(Init); 1610 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1611 1612 if (VarDecl *VD = F->getConditionVariable()) 1613 addLocalScopeForVarDecl(VD); 1614 LocalScope::const_iterator ContinueScopePos = ScopePos; 1615 1616 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), F); 1617 1618 // "for" is a control-flow statement. Thus we stop processing the current 1619 // block. 1620 if (Block) { 1621 if (badCFG) 1622 return 0; 1623 LoopSuccessor = Block; 1624 } else 1625 LoopSuccessor = Succ; 1626 1627 // Save the current value for the break targets. 1628 // All breaks should go to the code following the loop. 1629 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 1630 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1631 1632 // Because of short-circuit evaluation, the condition of the loop can span 1633 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1634 // evaluate the condition. 1635 CFGBlock *ExitConditionBlock = createBlock(false); 1636 CFGBlock *EntryConditionBlock = ExitConditionBlock; 1637 1638 // Set the terminator for the "exit" condition block. 1639 ExitConditionBlock->setTerminator(F); 1640 1641 // Now add the actual condition to the condition block. Because the condition 1642 // itself may contain control-flow, new blocks may be created. 1643 if (Stmt *C = F->getCond()) { 1644 Block = ExitConditionBlock; 1645 EntryConditionBlock = addStmt(C); 1646 if (badCFG) 1647 return 0; 1648 assert(Block == EntryConditionBlock || 1649 (Block == 0 && EntryConditionBlock == Succ)); 1650 1651 // If this block contains a condition variable, add both the condition 1652 // variable and initializer to the CFG. 1653 if (VarDecl *VD = F->getConditionVariable()) { 1654 if (Expr *Init = VD->getInit()) { 1655 autoCreateBlock(); 1656 appendStmt(Block, F->getConditionVariableDeclStmt()); 1657 EntryConditionBlock = addStmt(Init); 1658 assert(Block == EntryConditionBlock); 1659 } 1660 } 1661 1662 if (Block) { 1663 if (badCFG) 1664 return 0; 1665 } 1666 } 1667 1668 // The condition block is the implicit successor for the loop body as well as 1669 // any code above the loop. 1670 Succ = EntryConditionBlock; 1671 1672 // See if this is a known constant. 1673 TryResult KnownVal(true); 1674 1675 if (F->getCond()) 1676 KnownVal = tryEvaluateBool(F->getCond()); 1677 1678 // Now create the loop body. 1679 { 1680 assert(F->getBody()); 1681 1682 // Save the current values for Block, Succ, and continue targets. 1683 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1684 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 1685 1686 // Create a new block to contain the (bottom) of the loop body. 1687 Block = NULL; 1688 1689 // Loop body should end with destructor of Condition variable (if any). 1690 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, F); 1691 1692 if (Stmt *I = F->getInc()) { 1693 // Generate increment code in its own basic block. This is the target of 1694 // continue statements. 1695 Succ = addStmt(I); 1696 } else { 1697 // No increment code. Create a special, empty, block that is used as the 1698 // target block for "looping back" to the start of the loop. 1699 assert(Succ == EntryConditionBlock); 1700 Succ = Block ? Block : createBlock(); 1701 } 1702 1703 // Finish up the increment (or empty) block if it hasn't been already. 1704 if (Block) { 1705 assert(Block == Succ); 1706 if (badCFG) 1707 return 0; 1708 Block = 0; 1709 } 1710 1711 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 1712 1713 // The starting block for the loop increment is the block that should 1714 // represent the 'loop target' for looping back to the start of the loop. 1715 ContinueJumpTarget.block->setLoopTarget(F); 1716 1717 // If body is not a compound statement create implicit scope 1718 // and add destructors. 1719 if (!isa<CompoundStmt>(F->getBody())) 1720 addLocalScopeAndDtors(F->getBody()); 1721 1722 // Now populate the body block, and in the process create new blocks as we 1723 // walk the body of the loop. 1724 CFGBlock *BodyBlock = addStmt(F->getBody()); 1725 1726 if (!BodyBlock) 1727 BodyBlock = ContinueJumpTarget.block;//can happen for "for (...;...;...);" 1728 else if (badCFG) 1729 return 0; 1730 1731 // This new body block is a successor to our "exit" condition block. 1732 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 1733 } 1734 1735 // Link up the condition block with the code that follows the loop. (the 1736 // false branch). 1737 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 1738 1739 // If the loop contains initialization, create a new block for those 1740 // statements. This block can also contain statements that precede the loop. 1741 if (Stmt *I = F->getInit()) { 1742 Block = createBlock(); 1743 return addStmt(I); 1744 } 1745 1746 // There is no loop initialization. We are thus basically a while loop. 1747 // NULL out Block to force lazy block construction. 1748 Block = NULL; 1749 Succ = EntryConditionBlock; 1750 return EntryConditionBlock; 1751} 1752 1753CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) { 1754 if (asc.alwaysAdd(*this, M)) { 1755 autoCreateBlock(); 1756 appendStmt(Block, M); 1757 } 1758 return Visit(M->getBase()); 1759} 1760 1761CFGBlock *CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 1762 // Objective-C fast enumeration 'for' statements: 1763 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC 1764 // 1765 // for ( Type newVariable in collection_expression ) { statements } 1766 // 1767 // becomes: 1768 // 1769 // prologue: 1770 // 1. collection_expression 1771 // T. jump to loop_entry 1772 // loop_entry: 1773 // 1. side-effects of element expression 1774 // 1. ObjCForCollectionStmt [performs binding to newVariable] 1775 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil] 1776 // TB: 1777 // statements 1778 // T. jump to loop_entry 1779 // FB: 1780 // what comes after 1781 // 1782 // and 1783 // 1784 // Type existingItem; 1785 // for ( existingItem in expression ) { statements } 1786 // 1787 // becomes: 1788 // 1789 // the same with newVariable replaced with existingItem; the binding works 1790 // the same except that for one ObjCForCollectionStmt::getElement() returns 1791 // a DeclStmt and the other returns a DeclRefExpr. 1792 // 1793 1794 CFGBlock *LoopSuccessor = 0; 1795 1796 if (Block) { 1797 if (badCFG) 1798 return 0; 1799 LoopSuccessor = Block; 1800 Block = 0; 1801 } else 1802 LoopSuccessor = Succ; 1803 1804 // Build the condition blocks. 1805 CFGBlock *ExitConditionBlock = createBlock(false); 1806 1807 // Set the terminator for the "exit" condition block. 1808 ExitConditionBlock->setTerminator(S); 1809 1810 // The last statement in the block should be the ObjCForCollectionStmt, which 1811 // performs the actual binding to 'element' and determines if there are any 1812 // more items in the collection. 1813 appendStmt(ExitConditionBlock, S); 1814 Block = ExitConditionBlock; 1815 1816 // Walk the 'element' expression to see if there are any side-effects. We 1817 // generate new blocks as necessary. We DON'T add the statement by default to 1818 // the CFG unless it contains control-flow. 1819 CFGBlock *EntryConditionBlock = Visit(S->getElement(), 1820 AddStmtChoice::NotAlwaysAdd); 1821 if (Block) { 1822 if (badCFG) 1823 return 0; 1824 Block = 0; 1825 } 1826 1827 // The condition block is the implicit successor for the loop body as well as 1828 // any code above the loop. 1829 Succ = EntryConditionBlock; 1830 1831 // Now create the true branch. 1832 { 1833 // Save the current values for Succ, continue and break targets. 1834 SaveAndRestore<CFGBlock*> save_Succ(Succ); 1835 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1836 save_break(BreakJumpTarget); 1837 1838 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1839 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 1840 1841 CFGBlock *BodyBlock = addStmt(S->getBody()); 1842 1843 if (!BodyBlock) 1844 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;" 1845 else if (Block) { 1846 if (badCFG) 1847 return 0; 1848 } 1849 1850 // This new body block is a successor to our "exit" condition block. 1851 addSuccessor(ExitConditionBlock, BodyBlock); 1852 } 1853 1854 // Link up the condition block with the code that follows the loop. 1855 // (the false branch). 1856 addSuccessor(ExitConditionBlock, LoopSuccessor); 1857 1858 // Now create a prologue block to contain the collection expression. 1859 Block = createBlock(); 1860 return addStmt(S->getCollection()); 1861} 1862 1863CFGBlock *CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) { 1864 // FIXME: Add locking 'primitives' to CFG for @synchronized. 1865 1866 // Inline the body. 1867 CFGBlock *SyncBlock = addStmt(S->getSynchBody()); 1868 1869 // The sync body starts its own basic block. This makes it a little easier 1870 // for diagnostic clients. 1871 if (SyncBlock) { 1872 if (badCFG) 1873 return 0; 1874 1875 Block = 0; 1876 Succ = SyncBlock; 1877 } 1878 1879 // Add the @synchronized to the CFG. 1880 autoCreateBlock(); 1881 appendStmt(Block, S); 1882 1883 // Inline the sync expression. 1884 return addStmt(S->getSynchExpr()); 1885} 1886 1887CFGBlock *CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 1888 // FIXME 1889 return NYS(); 1890} 1891 1892CFGBlock *CFGBuilder::VisitWhileStmt(WhileStmt *W) { 1893 CFGBlock *LoopSuccessor = NULL; 1894 1895 // Save local scope position because in case of condition variable ScopePos 1896 // won't be restored when traversing AST. 1897 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 1898 1899 // Create local scope for possible condition variable. 1900 // Store scope position for continue statement. 1901 LocalScope::const_iterator LoopBeginScopePos = ScopePos; 1902 if (VarDecl *VD = W->getConditionVariable()) { 1903 addLocalScopeForVarDecl(VD); 1904 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 1905 } 1906 1907 // "while" is a control-flow statement. Thus we stop processing the current 1908 // block. 1909 if (Block) { 1910 if (badCFG) 1911 return 0; 1912 LoopSuccessor = Block; 1913 Block = 0; 1914 } else 1915 LoopSuccessor = Succ; 1916 1917 // Because of short-circuit evaluation, the condition of the loop can span 1918 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 1919 // evaluate the condition. 1920 CFGBlock *ExitConditionBlock = createBlock(false); 1921 CFGBlock *EntryConditionBlock = ExitConditionBlock; 1922 1923 // Set the terminator for the "exit" condition block. 1924 ExitConditionBlock->setTerminator(W); 1925 1926 // Now add the actual condition to the condition block. Because the condition 1927 // itself may contain control-flow, new blocks may be created. Thus we update 1928 // "Succ" after adding the condition. 1929 if (Stmt *C = W->getCond()) { 1930 Block = ExitConditionBlock; 1931 EntryConditionBlock = addStmt(C); 1932 // The condition might finish the current 'Block'. 1933 Block = EntryConditionBlock; 1934 1935 // If this block contains a condition variable, add both the condition 1936 // variable and initializer to the CFG. 1937 if (VarDecl *VD = W->getConditionVariable()) { 1938 if (Expr *Init = VD->getInit()) { 1939 autoCreateBlock(); 1940 appendStmt(Block, W->getConditionVariableDeclStmt()); 1941 EntryConditionBlock = addStmt(Init); 1942 assert(Block == EntryConditionBlock); 1943 } 1944 } 1945 1946 if (Block) { 1947 if (badCFG) 1948 return 0; 1949 } 1950 } 1951 1952 // The condition block is the implicit successor for the loop body as well as 1953 // any code above the loop. 1954 Succ = EntryConditionBlock; 1955 1956 // See if this is a known constant. 1957 const TryResult& KnownVal = tryEvaluateBool(W->getCond()); 1958 1959 // Process the loop body. 1960 { 1961 assert(W->getBody()); 1962 1963 // Save the current values for Block, Succ, and continue and break targets 1964 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 1965 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 1966 save_break(BreakJumpTarget); 1967 1968 // Create an empty block to represent the transition block for looping back 1969 // to the head of the loop. 1970 Block = 0; 1971 assert(Succ == EntryConditionBlock); 1972 Succ = createBlock(); 1973 Succ->setLoopTarget(W); 1974 ContinueJumpTarget = JumpTarget(Succ, LoopBeginScopePos); 1975 1976 // All breaks should go to the code following the loop. 1977 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 1978 1979 // NULL out Block to force lazy instantiation of blocks for the body. 1980 Block = NULL; 1981 1982 // Loop body should end with destructor of Condition variable (if any). 1983 addAutomaticObjDtors(ScopePos, LoopBeginScopePos, W); 1984 1985 // If body is not a compound statement create implicit scope 1986 // and add destructors. 1987 if (!isa<CompoundStmt>(W->getBody())) 1988 addLocalScopeAndDtors(W->getBody()); 1989 1990 // Create the body. The returned block is the entry to the loop body. 1991 CFGBlock *BodyBlock = addStmt(W->getBody()); 1992 1993 if (!BodyBlock) 1994 BodyBlock = ContinueJumpTarget.block; // can happen for "while(...) ;" 1995 else if (Block) { 1996 if (badCFG) 1997 return 0; 1998 } 1999 2000 // Add the loop body entry as a successor to the condition. 2001 addSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock); 2002 } 2003 2004 // Link up the condition block with the code that follows the loop. (the 2005 // false branch). 2006 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2007 2008 // There can be no more statements in the condition block since we loop back 2009 // to this block. NULL out Block to force lazy creation of another block. 2010 Block = NULL; 2011 2012 // Return the condition block, which is the dominating block for the loop. 2013 Succ = EntryConditionBlock; 2014 return EntryConditionBlock; 2015} 2016 2017 2018CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 2019 // FIXME: For now we pretend that @catch and the code it contains does not 2020 // exit. 2021 return Block; 2022} 2023 2024CFGBlock *CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 2025 // FIXME: This isn't complete. We basically treat @throw like a return 2026 // statement. 2027 2028 // If we were in the middle of a block we stop processing that block. 2029 if (badCFG) 2030 return 0; 2031 2032 // Create the new block. 2033 Block = createBlock(false); 2034 2035 // The Exit block is the only successor. 2036 addSuccessor(Block, &cfg->getExit()); 2037 2038 // Add the statement to the block. This may create new blocks if S contains 2039 // control-flow (short-circuit operations). 2040 return VisitStmt(S, AddStmtChoice::AlwaysAdd); 2041} 2042 2043CFGBlock *CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr *T) { 2044 // If we were in the middle of a block we stop processing that block. 2045 if (badCFG) 2046 return 0; 2047 2048 // Create the new block. 2049 Block = createBlock(false); 2050 2051 if (TryTerminatedBlock) 2052 // The current try statement is the only successor. 2053 addSuccessor(Block, TryTerminatedBlock); 2054 else 2055 // otherwise the Exit block is the only successor. 2056 addSuccessor(Block, &cfg->getExit()); 2057 2058 // Add the statement to the block. This may create new blocks if S contains 2059 // control-flow (short-circuit operations). 2060 return VisitStmt(T, AddStmtChoice::AlwaysAdd); 2061} 2062 2063CFGBlock *CFGBuilder::VisitDoStmt(DoStmt *D) { 2064 CFGBlock *LoopSuccessor = NULL; 2065 2066 // "do...while" is a control-flow statement. Thus we stop processing the 2067 // current block. 2068 if (Block) { 2069 if (badCFG) 2070 return 0; 2071 LoopSuccessor = Block; 2072 } else 2073 LoopSuccessor = Succ; 2074 2075 // Because of short-circuit evaluation, the condition of the loop can span 2076 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that 2077 // evaluate the condition. 2078 CFGBlock *ExitConditionBlock = createBlock(false); 2079 CFGBlock *EntryConditionBlock = ExitConditionBlock; 2080 2081 // Set the terminator for the "exit" condition block. 2082 ExitConditionBlock->setTerminator(D); 2083 2084 // Now add the actual condition to the condition block. Because the condition 2085 // itself may contain control-flow, new blocks may be created. 2086 if (Stmt *C = D->getCond()) { 2087 Block = ExitConditionBlock; 2088 EntryConditionBlock = addStmt(C); 2089 if (Block) { 2090 if (badCFG) 2091 return 0; 2092 } 2093 } 2094 2095 // The condition block is the implicit successor for the loop body. 2096 Succ = EntryConditionBlock; 2097 2098 // See if this is a known constant. 2099 const TryResult &KnownVal = tryEvaluateBool(D->getCond()); 2100 2101 // Process the loop body. 2102 CFGBlock *BodyBlock = NULL; 2103 { 2104 assert(D->getBody()); 2105 2106 // Save the current values for Block, Succ, and continue and break targets 2107 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2108 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget), 2109 save_break(BreakJumpTarget); 2110 2111 // All continues within this loop should go to the condition block 2112 ContinueJumpTarget = JumpTarget(EntryConditionBlock, ScopePos); 2113 2114 // All breaks should go to the code following the loop. 2115 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2116 2117 // NULL out Block to force lazy instantiation of blocks for the body. 2118 Block = NULL; 2119 2120 // If body is not a compound statement create implicit scope 2121 // and add destructors. 2122 if (!isa<CompoundStmt>(D->getBody())) 2123 addLocalScopeAndDtors(D->getBody()); 2124 2125 // Create the body. The returned block is the entry to the loop body. 2126 BodyBlock = addStmt(D->getBody()); 2127 2128 if (!BodyBlock) 2129 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)" 2130 else if (Block) { 2131 if (badCFG) 2132 return 0; 2133 } 2134 2135 if (!KnownVal.isFalse()) { 2136 // Add an intermediate block between the BodyBlock and the 2137 // ExitConditionBlock to represent the "loop back" transition. Create an 2138 // empty block to represent the transition block for looping back to the 2139 // head of the loop. 2140 // FIXME: Can we do this more efficiently without adding another block? 2141 Block = NULL; 2142 Succ = BodyBlock; 2143 CFGBlock *LoopBackBlock = createBlock(); 2144 LoopBackBlock->setLoopTarget(D); 2145 2146 // Add the loop body entry as a successor to the condition. 2147 addSuccessor(ExitConditionBlock, LoopBackBlock); 2148 } 2149 else 2150 addSuccessor(ExitConditionBlock, NULL); 2151 } 2152 2153 // Link up the condition block with the code that follows the loop. 2154 // (the false branch). 2155 addSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor); 2156 2157 // There can be no more statements in the body block(s) since we loop back to 2158 // the body. NULL out Block to force lazy creation of another block. 2159 Block = NULL; 2160 2161 // Return the loop body, which is the dominating block for the loop. 2162 Succ = BodyBlock; 2163 return BodyBlock; 2164} 2165 2166CFGBlock *CFGBuilder::VisitContinueStmt(ContinueStmt *C) { 2167 // "continue" is a control-flow statement. Thus we stop processing the 2168 // current block. 2169 if (badCFG) 2170 return 0; 2171 2172 // Now create a new block that ends with the continue statement. 2173 Block = createBlock(false); 2174 Block->setTerminator(C); 2175 2176 // If there is no target for the continue, then we are looking at an 2177 // incomplete AST. This means the CFG cannot be constructed. 2178 if (ContinueJumpTarget.block) { 2179 addAutomaticObjDtors(ScopePos, ContinueJumpTarget.scopePosition, C); 2180 addSuccessor(Block, ContinueJumpTarget.block); 2181 } else 2182 badCFG = true; 2183 2184 return Block; 2185} 2186 2187CFGBlock *CFGBuilder::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E, 2188 AddStmtChoice asc) { 2189 2190 if (asc.alwaysAdd(*this, E)) { 2191 autoCreateBlock(); 2192 appendStmt(Block, E); 2193 } 2194 2195 // VLA types have expressions that must be evaluated. 2196 CFGBlock *lastBlock = Block; 2197 2198 if (E->isArgumentType()) { 2199 for (const VariableArrayType *VA =FindVA(E->getArgumentType().getTypePtr()); 2200 VA != 0; VA = FindVA(VA->getElementType().getTypePtr())) 2201 lastBlock = addStmt(VA->getSizeExpr()); 2202 } 2203 return lastBlock; 2204} 2205 2206/// VisitStmtExpr - Utility method to handle (nested) statement 2207/// expressions (a GCC extension). 2208CFGBlock *CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) { 2209 if (asc.alwaysAdd(*this, SE)) { 2210 autoCreateBlock(); 2211 appendStmt(Block, SE); 2212 } 2213 return VisitCompoundStmt(SE->getSubStmt()); 2214} 2215 2216CFGBlock *CFGBuilder::VisitSwitchStmt(SwitchStmt *Terminator) { 2217 // "switch" is a control-flow statement. Thus we stop processing the current 2218 // block. 2219 CFGBlock *SwitchSuccessor = NULL; 2220 2221 // Save local scope position because in case of condition variable ScopePos 2222 // won't be restored when traversing AST. 2223 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2224 2225 // Create local scope for possible condition variable. 2226 // Store scope position. Add implicit destructor. 2227 if (VarDecl *VD = Terminator->getConditionVariable()) { 2228 LocalScope::const_iterator SwitchBeginScopePos = ScopePos; 2229 addLocalScopeForVarDecl(VD); 2230 addAutomaticObjDtors(ScopePos, SwitchBeginScopePos, Terminator); 2231 } 2232 2233 if (Block) { 2234 if (badCFG) 2235 return 0; 2236 SwitchSuccessor = Block; 2237 } else SwitchSuccessor = Succ; 2238 2239 // Save the current "switch" context. 2240 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock), 2241 save_default(DefaultCaseBlock); 2242 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2243 2244 // Set the "default" case to be the block after the switch statement. If the 2245 // switch statement contains a "default:", this value will be overwritten with 2246 // the block for that code. 2247 DefaultCaseBlock = SwitchSuccessor; 2248 2249 // Create a new block that will contain the switch statement. 2250 SwitchTerminatedBlock = createBlock(false); 2251 2252 // Now process the switch body. The code after the switch is the implicit 2253 // successor. 2254 Succ = SwitchSuccessor; 2255 BreakJumpTarget = JumpTarget(SwitchSuccessor, ScopePos); 2256 2257 // When visiting the body, the case statements should automatically get linked 2258 // up to the switch. We also don't keep a pointer to the body, since all 2259 // control-flow from the switch goes to case/default statements. 2260 assert(Terminator->getBody() && "switch must contain a non-NULL body"); 2261 Block = NULL; 2262 2263 // For pruning unreachable case statements, save the current state 2264 // for tracking the condition value. 2265 SaveAndRestore<bool> save_switchExclusivelyCovered(switchExclusivelyCovered, 2266 false); 2267 2268 // Determine if the switch condition can be explicitly evaluated. 2269 assert(Terminator->getCond() && "switch condition must be non-NULL"); 2270 Expr::EvalResult result; 2271 bool b = tryEvaluate(Terminator->getCond(), result); 2272 SaveAndRestore<Expr::EvalResult*> save_switchCond(switchCond, 2273 b ? &result : 0); 2274 2275 // If body is not a compound statement create implicit scope 2276 // and add destructors. 2277 if (!isa<CompoundStmt>(Terminator->getBody())) 2278 addLocalScopeAndDtors(Terminator->getBody()); 2279 2280 addStmt(Terminator->getBody()); 2281 if (Block) { 2282 if (badCFG) 2283 return 0; 2284 } 2285 2286 // If we have no "default:" case, the default transition is to the code 2287 // following the switch body. Moreover, take into account if all the 2288 // cases of a switch are covered (e.g., switching on an enum value). 2289 addSuccessor(SwitchTerminatedBlock, 2290 switchExclusivelyCovered || Terminator->isAllEnumCasesCovered() 2291 ? 0 : DefaultCaseBlock); 2292 2293 // Add the terminator and condition in the switch block. 2294 SwitchTerminatedBlock->setTerminator(Terminator); 2295 Block = SwitchTerminatedBlock; 2296 Block = addStmt(Terminator->getCond()); 2297 2298 // Finally, if the SwitchStmt contains a condition variable, add both the 2299 // SwitchStmt and the condition variable initialization to the CFG. 2300 if (VarDecl *VD = Terminator->getConditionVariable()) { 2301 if (Expr *Init = VD->getInit()) { 2302 autoCreateBlock(); 2303 appendStmt(Block, Terminator->getConditionVariableDeclStmt()); 2304 addStmt(Init); 2305 } 2306 } 2307 2308 return Block; 2309} 2310 2311static bool shouldAddCase(bool &switchExclusivelyCovered, 2312 const Expr::EvalResult *switchCond, 2313 const CaseStmt *CS, 2314 ASTContext &Ctx) { 2315 if (!switchCond) 2316 return true; 2317 2318 bool addCase = false; 2319 2320 if (!switchExclusivelyCovered) { 2321 if (switchCond->Val.isInt()) { 2322 // Evaluate the LHS of the case value. 2323 Expr::EvalResult V1; 2324 CS->getLHS()->Evaluate(V1, Ctx); 2325 assert(V1.Val.isInt()); 2326 const llvm::APSInt &condInt = switchCond->Val.getInt(); 2327 const llvm::APSInt &lhsInt = V1.Val.getInt(); 2328 2329 if (condInt == lhsInt) { 2330 addCase = true; 2331 switchExclusivelyCovered = true; 2332 } 2333 else if (condInt < lhsInt) { 2334 if (const Expr *RHS = CS->getRHS()) { 2335 // Evaluate the RHS of the case value. 2336 Expr::EvalResult V2; 2337 RHS->Evaluate(V2, Ctx); 2338 assert(V2.Val.isInt()); 2339 if (V2.Val.getInt() <= condInt) { 2340 addCase = true; 2341 switchExclusivelyCovered = true; 2342 } 2343 } 2344 } 2345 } 2346 else 2347 addCase = true; 2348 } 2349 return addCase; 2350} 2351 2352CFGBlock *CFGBuilder::VisitCaseStmt(CaseStmt *CS) { 2353 // CaseStmts are essentially labels, so they are the first statement in a 2354 // block. 2355 CFGBlock *TopBlock = 0, *LastBlock = 0; 2356 2357 if (Stmt *Sub = CS->getSubStmt()) { 2358 // For deeply nested chains of CaseStmts, instead of doing a recursion 2359 // (which can blow out the stack), manually unroll and create blocks 2360 // along the way. 2361 while (isa<CaseStmt>(Sub)) { 2362 CFGBlock *currentBlock = createBlock(false); 2363 currentBlock->setLabel(CS); 2364 2365 if (TopBlock) 2366 addSuccessor(LastBlock, currentBlock); 2367 else 2368 TopBlock = currentBlock; 2369 2370 addSuccessor(SwitchTerminatedBlock, 2371 shouldAddCase(switchExclusivelyCovered, switchCond, 2372 CS, *Context) 2373 ? currentBlock : 0); 2374 2375 LastBlock = currentBlock; 2376 CS = cast<CaseStmt>(Sub); 2377 Sub = CS->getSubStmt(); 2378 } 2379 2380 addStmt(Sub); 2381 } 2382 2383 CFGBlock *CaseBlock = Block; 2384 if (!CaseBlock) 2385 CaseBlock = createBlock(); 2386 2387 // Cases statements partition blocks, so this is the top of the basic block we 2388 // were processing (the "case XXX:" is the label). 2389 CaseBlock->setLabel(CS); 2390 2391 if (badCFG) 2392 return 0; 2393 2394 // Add this block to the list of successors for the block with the switch 2395 // statement. 2396 assert(SwitchTerminatedBlock); 2397 addSuccessor(SwitchTerminatedBlock, 2398 shouldAddCase(switchExclusivelyCovered, switchCond, 2399 CS, *Context) 2400 ? CaseBlock : 0); 2401 2402 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2403 Block = NULL; 2404 2405 if (TopBlock) { 2406 addSuccessor(LastBlock, CaseBlock); 2407 Succ = TopBlock; 2408 } else { 2409 // This block is now the implicit successor of other blocks. 2410 Succ = CaseBlock; 2411 } 2412 2413 return Succ; 2414} 2415 2416CFGBlock *CFGBuilder::VisitDefaultStmt(DefaultStmt *Terminator) { 2417 if (Terminator->getSubStmt()) 2418 addStmt(Terminator->getSubStmt()); 2419 2420 DefaultCaseBlock = Block; 2421 2422 if (!DefaultCaseBlock) 2423 DefaultCaseBlock = createBlock(); 2424 2425 // Default statements partition blocks, so this is the top of the basic block 2426 // we were processing (the "default:" is the label). 2427 DefaultCaseBlock->setLabel(Terminator); 2428 2429 if (badCFG) 2430 return 0; 2431 2432 // Unlike case statements, we don't add the default block to the successors 2433 // for the switch statement immediately. This is done when we finish 2434 // processing the switch statement. This allows for the default case 2435 // (including a fall-through to the code after the switch statement) to always 2436 // be the last successor of a switch-terminated block. 2437 2438 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2439 Block = NULL; 2440 2441 // This block is now the implicit successor of other blocks. 2442 Succ = DefaultCaseBlock; 2443 2444 return DefaultCaseBlock; 2445} 2446 2447CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) { 2448 // "try"/"catch" is a control-flow statement. Thus we stop processing the 2449 // current block. 2450 CFGBlock *TrySuccessor = NULL; 2451 2452 if (Block) { 2453 if (badCFG) 2454 return 0; 2455 TrySuccessor = Block; 2456 } else TrySuccessor = Succ; 2457 2458 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock; 2459 2460 // Create a new block that will contain the try statement. 2461 CFGBlock *NewTryTerminatedBlock = createBlock(false); 2462 // Add the terminator in the try block. 2463 NewTryTerminatedBlock->setTerminator(Terminator); 2464 2465 bool HasCatchAll = false; 2466 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) { 2467 // The code after the try is the implicit successor. 2468 Succ = TrySuccessor; 2469 CXXCatchStmt *CS = Terminator->getHandler(h); 2470 if (CS->getExceptionDecl() == 0) { 2471 HasCatchAll = true; 2472 } 2473 Block = NULL; 2474 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS); 2475 if (CatchBlock == 0) 2476 return 0; 2477 // Add this block to the list of successors for the block with the try 2478 // statement. 2479 addSuccessor(NewTryTerminatedBlock, CatchBlock); 2480 } 2481 if (!HasCatchAll) { 2482 if (PrevTryTerminatedBlock) 2483 addSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock); 2484 else 2485 addSuccessor(NewTryTerminatedBlock, &cfg->getExit()); 2486 } 2487 2488 // The code after the try is the implicit successor. 2489 Succ = TrySuccessor; 2490 2491 // Save the current "try" context. 2492 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock, NewTryTerminatedBlock); 2493 cfg->addTryDispatchBlock(TryTerminatedBlock); 2494 2495 assert(Terminator->getTryBlock() && "try must contain a non-NULL body"); 2496 Block = NULL; 2497 Block = addStmt(Terminator->getTryBlock()); 2498 return Block; 2499} 2500 2501CFGBlock *CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt *CS) { 2502 // CXXCatchStmt are treated like labels, so they are the first statement in a 2503 // block. 2504 2505 // Save local scope position because in case of exception variable ScopePos 2506 // won't be restored when traversing AST. 2507 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2508 2509 // Create local scope for possible exception variable. 2510 // Store scope position. Add implicit destructor. 2511 if (VarDecl *VD = CS->getExceptionDecl()) { 2512 LocalScope::const_iterator BeginScopePos = ScopePos; 2513 addLocalScopeForVarDecl(VD); 2514 addAutomaticObjDtors(ScopePos, BeginScopePos, CS); 2515 } 2516 2517 if (CS->getHandlerBlock()) 2518 addStmt(CS->getHandlerBlock()); 2519 2520 CFGBlock *CatchBlock = Block; 2521 if (!CatchBlock) 2522 CatchBlock = createBlock(); 2523 2524 CatchBlock->setLabel(CS); 2525 2526 if (badCFG) 2527 return 0; 2528 2529 // We set Block to NULL to allow lazy creation of a new block (if necessary) 2530 Block = NULL; 2531 2532 return CatchBlock; 2533} 2534 2535CFGBlock *CFGBuilder::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 2536 // C++0x for-range statements are specified as [stmt.ranged]: 2537 // 2538 // { 2539 // auto && __range = range-init; 2540 // for ( auto __begin = begin-expr, 2541 // __end = end-expr; 2542 // __begin != __end; 2543 // ++__begin ) { 2544 // for-range-declaration = *__begin; 2545 // statement 2546 // } 2547 // } 2548 2549 // Save local scope position before the addition of the implicit variables. 2550 SaveAndRestore<LocalScope::const_iterator> save_scope_pos(ScopePos); 2551 2552 // Create local scopes and destructors for range, begin and end variables. 2553 if (Stmt *Range = S->getRangeStmt()) 2554 addLocalScopeForStmt(Range); 2555 if (Stmt *BeginEnd = S->getBeginEndStmt()) 2556 addLocalScopeForStmt(BeginEnd); 2557 addAutomaticObjDtors(ScopePos, save_scope_pos.get(), S); 2558 2559 LocalScope::const_iterator ContinueScopePos = ScopePos; 2560 2561 // "for" is a control-flow statement. Thus we stop processing the current 2562 // block. 2563 CFGBlock *LoopSuccessor = NULL; 2564 if (Block) { 2565 if (badCFG) 2566 return 0; 2567 LoopSuccessor = Block; 2568 } else 2569 LoopSuccessor = Succ; 2570 2571 // Save the current value for the break targets. 2572 // All breaks should go to the code following the loop. 2573 SaveAndRestore<JumpTarget> save_break(BreakJumpTarget); 2574 BreakJumpTarget = JumpTarget(LoopSuccessor, ScopePos); 2575 2576 // The block for the __begin != __end expression. 2577 CFGBlock *ConditionBlock = createBlock(false); 2578 ConditionBlock->setTerminator(S); 2579 2580 // Now add the actual condition to the condition block. 2581 if (Expr *C = S->getCond()) { 2582 Block = ConditionBlock; 2583 CFGBlock *BeginConditionBlock = addStmt(C); 2584 if (badCFG) 2585 return 0; 2586 assert(BeginConditionBlock == ConditionBlock && 2587 "condition block in for-range was unexpectedly complex"); 2588 (void)BeginConditionBlock; 2589 } 2590 2591 // The condition block is the implicit successor for the loop body as well as 2592 // any code above the loop. 2593 Succ = ConditionBlock; 2594 2595 // See if this is a known constant. 2596 TryResult KnownVal(true); 2597 2598 if (S->getCond()) 2599 KnownVal = tryEvaluateBool(S->getCond()); 2600 2601 // Now create the loop body. 2602 { 2603 assert(S->getBody()); 2604 2605 // Save the current values for Block, Succ, and continue targets. 2606 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ); 2607 SaveAndRestore<JumpTarget> save_continue(ContinueJumpTarget); 2608 2609 // Generate increment code in its own basic block. This is the target of 2610 // continue statements. 2611 Block = 0; 2612 Succ = addStmt(S->getInc()); 2613 ContinueJumpTarget = JumpTarget(Succ, ContinueScopePos); 2614 2615 // The starting block for the loop increment is the block that should 2616 // represent the 'loop target' for looping back to the start of the loop. 2617 ContinueJumpTarget.block->setLoopTarget(S); 2618 2619 // Finish up the increment block and prepare to start the loop body. 2620 assert(Block); 2621 if (badCFG) 2622 return 0; 2623 Block = 0; 2624 2625 2626 // Add implicit scope and dtors for loop variable. 2627 addLocalScopeAndDtors(S->getLoopVarStmt()); 2628 2629 // Populate a new block to contain the loop body and loop variable. 2630 Block = addStmt(S->getBody()); 2631 if (badCFG) 2632 return 0; 2633 Block = addStmt(S->getLoopVarStmt()); 2634 if (badCFG) 2635 return 0; 2636 2637 // This new body block is a successor to our condition block. 2638 addSuccessor(ConditionBlock, KnownVal.isFalse() ? 0 : Block); 2639 } 2640 2641 // Link up the condition block with the code that follows the loop (the 2642 // false branch). 2643 addSuccessor(ConditionBlock, KnownVal.isTrue() ? 0 : LoopSuccessor); 2644 2645 // Add the initialization statements. 2646 Block = createBlock(); 2647 addStmt(S->getBeginEndStmt()); 2648 return addStmt(S->getRangeStmt()); 2649} 2650 2651CFGBlock *CFGBuilder::VisitExprWithCleanups(ExprWithCleanups *E, 2652 AddStmtChoice asc) { 2653 if (BuildOpts.AddImplicitDtors) { 2654 // If adding implicit destructors visit the full expression for adding 2655 // destructors of temporaries. 2656 VisitForTemporaryDtors(E->getSubExpr()); 2657 2658 // Full expression has to be added as CFGStmt so it will be sequenced 2659 // before destructors of it's temporaries. 2660 asc = asc.withAlwaysAdd(true); 2661 } 2662 return Visit(E->getSubExpr(), asc); 2663} 2664 2665CFGBlock *CFGBuilder::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E, 2666 AddStmtChoice asc) { 2667 if (asc.alwaysAdd(*this, E)) { 2668 autoCreateBlock(); 2669 appendStmt(Block, E); 2670 2671 // We do not want to propagate the AlwaysAdd property. 2672 asc = asc.withAlwaysAdd(false); 2673 } 2674 return Visit(E->getSubExpr(), asc); 2675} 2676 2677CFGBlock *CFGBuilder::VisitCXXConstructExpr(CXXConstructExpr *C, 2678 AddStmtChoice asc) { 2679 autoCreateBlock(); 2680 if (!C->isElidable()) 2681 appendStmt(Block, C); 2682 2683 return VisitChildren(C); 2684} 2685 2686CFGBlock *CFGBuilder::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *E, 2687 AddStmtChoice asc) { 2688 if (asc.alwaysAdd(*this, E)) { 2689 autoCreateBlock(); 2690 appendStmt(Block, E); 2691 // We do not want to propagate the AlwaysAdd property. 2692 asc = asc.withAlwaysAdd(false); 2693 } 2694 return Visit(E->getSubExpr(), asc); 2695} 2696 2697CFGBlock *CFGBuilder::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *C, 2698 AddStmtChoice asc) { 2699 autoCreateBlock(); 2700 appendStmt(Block, C); 2701 return VisitChildren(C); 2702} 2703 2704CFGBlock *CFGBuilder::VisitImplicitCastExpr(ImplicitCastExpr *E, 2705 AddStmtChoice asc) { 2706 if (asc.alwaysAdd(*this, E)) { 2707 autoCreateBlock(); 2708 appendStmt(Block, E); 2709 } 2710 return Visit(E->getSubExpr(), AddStmtChoice()); 2711} 2712 2713CFGBlock *CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt *I) { 2714 // Lazily create the indirect-goto dispatch block if there isn't one already. 2715 CFGBlock *IBlock = cfg->getIndirectGotoBlock(); 2716 2717 if (!IBlock) { 2718 IBlock = createBlock(false); 2719 cfg->setIndirectGotoBlock(IBlock); 2720 } 2721 2722 // IndirectGoto is a control-flow statement. Thus we stop processing the 2723 // current block and create a new one. 2724 if (badCFG) 2725 return 0; 2726 2727 Block = createBlock(false); 2728 Block->setTerminator(I); 2729 addSuccessor(Block, IBlock); 2730 return addStmt(I->getTarget()); 2731} 2732 2733CFGBlock *CFGBuilder::VisitForTemporaryDtors(Stmt *E, bool BindToTemporary) { 2734tryAgain: 2735 if (!E) { 2736 badCFG = true; 2737 return NULL; 2738 } 2739 switch (E->getStmtClass()) { 2740 default: 2741 return VisitChildrenForTemporaryDtors(E); 2742 2743 case Stmt::BinaryOperatorClass: 2744 return VisitBinaryOperatorForTemporaryDtors(cast<BinaryOperator>(E)); 2745 2746 case Stmt::CXXBindTemporaryExprClass: 2747 return VisitCXXBindTemporaryExprForTemporaryDtors( 2748 cast<CXXBindTemporaryExpr>(E), BindToTemporary); 2749 2750 case Stmt::BinaryConditionalOperatorClass: 2751 case Stmt::ConditionalOperatorClass: 2752 return VisitConditionalOperatorForTemporaryDtors( 2753 cast<AbstractConditionalOperator>(E), BindToTemporary); 2754 2755 case Stmt::ImplicitCastExprClass: 2756 // For implicit cast we want BindToTemporary to be passed further. 2757 E = cast<CastExpr>(E)->getSubExpr(); 2758 goto tryAgain; 2759 2760 case Stmt::ParenExprClass: 2761 E = cast<ParenExpr>(E)->getSubExpr(); 2762 goto tryAgain; 2763 2764 case Stmt::MaterializeTemporaryExprClass: 2765 E = cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(); 2766 goto tryAgain; 2767 } 2768} 2769 2770CFGBlock *CFGBuilder::VisitChildrenForTemporaryDtors(Stmt *E) { 2771 // When visiting children for destructors we want to visit them in reverse 2772 // order. Because there's no reverse iterator for children must to reverse 2773 // them in helper vector. 2774 typedef SmallVector<Stmt *, 4> ChildrenVect; 2775 ChildrenVect ChildrenRev; 2776 for (Stmt::child_range I = E->children(); I; ++I) { 2777 if (*I) ChildrenRev.push_back(*I); 2778 } 2779 2780 CFGBlock *B = Block; 2781 for (ChildrenVect::reverse_iterator I = ChildrenRev.rbegin(), 2782 L = ChildrenRev.rend(); I != L; ++I) { 2783 if (CFGBlock *R = VisitForTemporaryDtors(*I)) 2784 B = R; 2785 } 2786 return B; 2787} 2788 2789CFGBlock *CFGBuilder::VisitBinaryOperatorForTemporaryDtors(BinaryOperator *E) { 2790 if (E->isLogicalOp()) { 2791 // Destructors for temporaries in LHS expression should be called after 2792 // those for RHS expression. Even if this will unnecessarily create a block, 2793 // this block will be used at least by the full expression. 2794 autoCreateBlock(); 2795 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getLHS()); 2796 if (badCFG) 2797 return NULL; 2798 2799 Succ = ConfluenceBlock; 2800 Block = NULL; 2801 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2802 2803 if (RHSBlock) { 2804 if (badCFG) 2805 return NULL; 2806 2807 // If RHS expression did produce destructors we need to connect created 2808 // blocks to CFG in same manner as for binary operator itself. 2809 CFGBlock *LHSBlock = createBlock(false); 2810 LHSBlock->setTerminator(CFGTerminator(E, true)); 2811 2812 // For binary operator LHS block is before RHS in list of predecessors 2813 // of ConfluenceBlock. 2814 std::reverse(ConfluenceBlock->pred_begin(), 2815 ConfluenceBlock->pred_end()); 2816 2817 // See if this is a known constant. 2818 TryResult KnownVal = tryEvaluateBool(E->getLHS()); 2819 if (KnownVal.isKnown() && (E->getOpcode() == BO_LOr)) 2820 KnownVal.negate(); 2821 2822 // Link LHSBlock with RHSBlock exactly the same way as for binary operator 2823 // itself. 2824 if (E->getOpcode() == BO_LOr) { 2825 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2826 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2827 } else { 2828 assert (E->getOpcode() == BO_LAnd); 2829 addSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock); 2830 addSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock); 2831 } 2832 2833 Block = LHSBlock; 2834 return LHSBlock; 2835 } 2836 2837 Block = ConfluenceBlock; 2838 return ConfluenceBlock; 2839 } 2840 2841 if (E->isAssignmentOp()) { 2842 // For assignment operator (=) LHS expression is visited 2843 // before RHS expression. For destructors visit them in reverse order. 2844 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2845 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2846 return LHSBlock ? LHSBlock : RHSBlock; 2847 } 2848 2849 // For any other binary operator RHS expression is visited before 2850 // LHS expression (order of children). For destructors visit them in reverse 2851 // order. 2852 CFGBlock *LHSBlock = VisitForTemporaryDtors(E->getLHS()); 2853 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getRHS()); 2854 return RHSBlock ? RHSBlock : LHSBlock; 2855} 2856 2857CFGBlock *CFGBuilder::VisitCXXBindTemporaryExprForTemporaryDtors( 2858 CXXBindTemporaryExpr *E, bool BindToTemporary) { 2859 // First add destructors for temporaries in subexpression. 2860 CFGBlock *B = VisitForTemporaryDtors(E->getSubExpr()); 2861 if (!BindToTemporary) { 2862 // If lifetime of temporary is not prolonged (by assigning to constant 2863 // reference) add destructor for it. 2864 autoCreateBlock(); 2865 appendTemporaryDtor(Block, E); 2866 B = Block; 2867 } 2868 return B; 2869} 2870 2871CFGBlock *CFGBuilder::VisitConditionalOperatorForTemporaryDtors( 2872 AbstractConditionalOperator *E, bool BindToTemporary) { 2873 // First add destructors for condition expression. Even if this will 2874 // unnecessarily create a block, this block will be used at least by the full 2875 // expression. 2876 autoCreateBlock(); 2877 CFGBlock *ConfluenceBlock = VisitForTemporaryDtors(E->getCond()); 2878 if (badCFG) 2879 return NULL; 2880 if (BinaryConditionalOperator *BCO 2881 = dyn_cast<BinaryConditionalOperator>(E)) { 2882 ConfluenceBlock = VisitForTemporaryDtors(BCO->getCommon()); 2883 if (badCFG) 2884 return NULL; 2885 } 2886 2887 // Try to add block with destructors for LHS expression. 2888 CFGBlock *LHSBlock = NULL; 2889 Succ = ConfluenceBlock; 2890 Block = NULL; 2891 LHSBlock = VisitForTemporaryDtors(E->getTrueExpr(), BindToTemporary); 2892 if (badCFG) 2893 return NULL; 2894 2895 // Try to add block with destructors for RHS expression; 2896 Succ = ConfluenceBlock; 2897 Block = NULL; 2898 CFGBlock *RHSBlock = VisitForTemporaryDtors(E->getFalseExpr(), 2899 BindToTemporary); 2900 if (badCFG) 2901 return NULL; 2902 2903 if (!RHSBlock && !LHSBlock) { 2904 // If neither LHS nor RHS expression had temporaries to destroy don't create 2905 // more blocks. 2906 Block = ConfluenceBlock; 2907 return Block; 2908 } 2909 2910 Block = createBlock(false); 2911 Block->setTerminator(CFGTerminator(E, true)); 2912 2913 // See if this is a known constant. 2914 const TryResult &KnownVal = tryEvaluateBool(E->getCond()); 2915 2916 if (LHSBlock) { 2917 addSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock); 2918 } else if (KnownVal.isFalse()) { 2919 addSuccessor(Block, NULL); 2920 } else { 2921 addSuccessor(Block, ConfluenceBlock); 2922 std::reverse(ConfluenceBlock->pred_begin(), ConfluenceBlock->pred_end()); 2923 } 2924 2925 if (!RHSBlock) 2926 RHSBlock = ConfluenceBlock; 2927 addSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock); 2928 2929 return Block; 2930} 2931 2932} // end anonymous namespace 2933 2934/// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has 2935/// no successors or predecessors. If this is the first block created in the 2936/// CFG, it is automatically set to be the Entry and Exit of the CFG. 2937CFGBlock *CFG::createBlock() { 2938 bool first_block = begin() == end(); 2939 2940 // Create the block. 2941 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>(); 2942 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC); 2943 Blocks.push_back(Mem, BlkBVC); 2944 2945 // If this is the first block, set it as the Entry and Exit. 2946 if (first_block) 2947 Entry = Exit = &back(); 2948 2949 // Return the block. 2950 return &back(); 2951} 2952 2953/// buildCFG - Constructs a CFG from an AST. Ownership of the returned 2954/// CFG is returned to the caller. 2955CFG* CFG::buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, 2956 const BuildOptions &BO) { 2957 CFGBuilder Builder(C, BO); 2958 return Builder.buildCFG(D, Statement); 2959} 2960 2961const CXXDestructorDecl * 2962CFGImplicitDtor::getDestructorDecl(ASTContext &astContext) const { 2963 switch (getKind()) { 2964 case CFGElement::Invalid: 2965 case CFGElement::Statement: 2966 case CFGElement::Initializer: 2967 llvm_unreachable("getDestructorDecl should only be used with " 2968 "ImplicitDtors"); 2969 case CFGElement::AutomaticObjectDtor: { 2970 const VarDecl *var = cast<CFGAutomaticObjDtor>(this)->getVarDecl(); 2971 QualType ty = var->getType(); 2972 ty = ty.getNonReferenceType(); 2973 if (const ArrayType *arrayType = astContext.getAsArrayType(ty)) { 2974 ty = arrayType->getElementType(); 2975 } 2976 const RecordType *recordType = ty->getAs<RecordType>(); 2977 const CXXRecordDecl *classDecl = 2978 cast<CXXRecordDecl>(recordType->getDecl()); 2979 return classDecl->getDestructor(); 2980 } 2981 case CFGElement::TemporaryDtor: { 2982 const CXXBindTemporaryExpr *bindExpr = 2983 cast<CFGTemporaryDtor>(this)->getBindTemporaryExpr(); 2984 const CXXTemporary *temp = bindExpr->getTemporary(); 2985 return temp->getDestructor(); 2986 } 2987 case CFGElement::BaseDtor: 2988 case CFGElement::MemberDtor: 2989 2990 // Not yet supported. 2991 return 0; 2992 } 2993 llvm_unreachable("getKind() returned bogus value"); 2994 return 0; 2995} 2996 2997bool CFGImplicitDtor::isNoReturn(ASTContext &astContext) const { 2998 if (const CXXDestructorDecl *cdecl = getDestructorDecl(astContext)) { 2999 QualType ty = cdecl->getType(); 3000 return cast<FunctionType>(ty)->getNoReturnAttr(); 3001 } 3002 return false; 3003} 3004 3005//===----------------------------------------------------------------------===// 3006// CFG: Queries for BlkExprs. 3007//===----------------------------------------------------------------------===// 3008 3009namespace { 3010 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy; 3011} 3012 3013static void FindSubExprAssignments(const Stmt *S, 3014 llvm::SmallPtrSet<const Expr*,50>& Set) { 3015 if (!S) 3016 return; 3017 3018 for (Stmt::const_child_range I = S->children(); I; ++I) { 3019 const Stmt *child = *I; 3020 if (!child) 3021 continue; 3022 3023 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(child)) 3024 if (B->isAssignmentOp()) Set.insert(B); 3025 3026 FindSubExprAssignments(child, Set); 3027 } 3028} 3029 3030static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) { 3031 BlkExprMapTy* M = new BlkExprMapTy(); 3032 3033 // Look for assignments that are used as subexpressions. These are the only 3034 // assignments that we want to *possibly* register as a block-level 3035 // expression. Basically, if an assignment occurs both in a subexpression and 3036 // at the block-level, it is a block-level expression. 3037 llvm::SmallPtrSet<const Expr*,50> SubExprAssignments; 3038 3039 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) 3040 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) 3041 if (const CFGStmt *S = BI->getAs<CFGStmt>()) 3042 FindSubExprAssignments(S->getStmt(), SubExprAssignments); 3043 3044 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) { 3045 3046 // Iterate over the statements again on identify the Expr* and Stmt* at the 3047 // block-level that are block-level expressions. 3048 3049 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI) { 3050 const CFGStmt *CS = BI->getAs<CFGStmt>(); 3051 if (!CS) 3052 continue; 3053 if (const Expr *Exp = dyn_cast<Expr>(CS->getStmt())) { 3054 assert((Exp->IgnoreParens() == Exp) && "No parens on block-level exps"); 3055 3056 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) { 3057 // Assignment expressions that are not nested within another 3058 // expression are really "statements" whose value is never used by 3059 // another expression. 3060 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp)) 3061 continue; 3062 } else if (const StmtExpr *SE = dyn_cast<StmtExpr>(Exp)) { 3063 // Special handling for statement expressions. The last statement in 3064 // the statement expression is also a block-level expr. 3065 const CompoundStmt *C = SE->getSubStmt(); 3066 if (!C->body_empty()) { 3067 const Stmt *Last = C->body_back(); 3068 if (const Expr *LastEx = dyn_cast<Expr>(Last)) 3069 Last = LastEx->IgnoreParens(); 3070 unsigned x = M->size(); 3071 (*M)[Last] = x; 3072 } 3073 } 3074 3075 unsigned x = M->size(); 3076 (*M)[Exp] = x; 3077 } 3078 } 3079 3080 // Look at terminators. The condition is a block-level expression. 3081 3082 Stmt *S = (*I)->getTerminatorCondition(); 3083 3084 if (S && M->find(S) == M->end()) { 3085 unsigned x = M->size(); 3086 (*M)[S] = x; 3087 } 3088 } 3089 3090 return M; 3091} 3092 3093CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt *S) { 3094 assert(S != NULL); 3095 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); } 3096 3097 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap); 3098 BlkExprMapTy::iterator I = M->find(S); 3099 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second); 3100} 3101 3102unsigned CFG::getNumBlkExprs() { 3103 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap)) 3104 return M->size(); 3105 3106 // We assume callers interested in the number of BlkExprs will want 3107 // the map constructed if it doesn't already exist. 3108 BlkExprMap = (void*) PopulateBlkExprMap(*this); 3109 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size(); 3110} 3111 3112//===----------------------------------------------------------------------===// 3113// Filtered walking of the CFG. 3114//===----------------------------------------------------------------------===// 3115 3116bool CFGBlock::FilterEdge(const CFGBlock::FilterOptions &F, 3117 const CFGBlock *From, const CFGBlock *To) { 3118 3119 if (To && F.IgnoreDefaultsWithCoveredEnums) { 3120 // If the 'To' has no label or is labeled but the label isn't a 3121 // CaseStmt then filter this edge. 3122 if (const SwitchStmt *S = 3123 dyn_cast_or_null<SwitchStmt>(From->getTerminator().getStmt())) { 3124 if (S->isAllEnumCasesCovered()) { 3125 const Stmt *L = To->getLabel(); 3126 if (!L || !isa<CaseStmt>(L)) 3127 return true; 3128 } 3129 } 3130 } 3131 3132 return false; 3133} 3134 3135//===----------------------------------------------------------------------===// 3136// Cleanup: CFG dstor. 3137//===----------------------------------------------------------------------===// 3138 3139CFG::~CFG() { 3140 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap); 3141} 3142 3143//===----------------------------------------------------------------------===// 3144// CFG pretty printing 3145//===----------------------------------------------------------------------===// 3146 3147namespace { 3148 3149class StmtPrinterHelper : public PrinterHelper { 3150 typedef llvm::DenseMap<const Stmt*,std::pair<unsigned,unsigned> > StmtMapTy; 3151 typedef llvm::DenseMap<const Decl*,std::pair<unsigned,unsigned> > DeclMapTy; 3152 StmtMapTy StmtMap; 3153 DeclMapTy DeclMap; 3154 signed currentBlock; 3155 unsigned currentStmt; 3156 const LangOptions &LangOpts; 3157public: 3158 3159 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO) 3160 : currentBlock(0), currentStmt(0), LangOpts(LO) 3161 { 3162 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) { 3163 unsigned j = 1; 3164 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ; 3165 BI != BEnd; ++BI, ++j ) { 3166 if (const CFGStmt *SE = BI->getAs<CFGStmt>()) { 3167 const Stmt *stmt= SE->getStmt(); 3168 std::pair<unsigned, unsigned> P((*I)->getBlockID(), j); 3169 StmtMap[stmt] = P; 3170 3171 switch (stmt->getStmtClass()) { 3172 case Stmt::DeclStmtClass: 3173 DeclMap[cast<DeclStmt>(stmt)->getSingleDecl()] = P; 3174 break; 3175 case Stmt::IfStmtClass: { 3176 const VarDecl *var = cast<IfStmt>(stmt)->getConditionVariable(); 3177 if (var) 3178 DeclMap[var] = P; 3179 break; 3180 } 3181 case Stmt::ForStmtClass: { 3182 const VarDecl *var = cast<ForStmt>(stmt)->getConditionVariable(); 3183 if (var) 3184 DeclMap[var] = P; 3185 break; 3186 } 3187 case Stmt::WhileStmtClass: { 3188 const VarDecl *var = 3189 cast<WhileStmt>(stmt)->getConditionVariable(); 3190 if (var) 3191 DeclMap[var] = P; 3192 break; 3193 } 3194 case Stmt::SwitchStmtClass: { 3195 const VarDecl *var = 3196 cast<SwitchStmt>(stmt)->getConditionVariable(); 3197 if (var) 3198 DeclMap[var] = P; 3199 break; 3200 } 3201 case Stmt::CXXCatchStmtClass: { 3202 const VarDecl *var = 3203 cast<CXXCatchStmt>(stmt)->getExceptionDecl(); 3204 if (var) 3205 DeclMap[var] = P; 3206 break; 3207 } 3208 default: 3209 break; 3210 } 3211 } 3212 } 3213 } 3214 } 3215 3216 3217 virtual ~StmtPrinterHelper() {} 3218 3219 const LangOptions &getLangOpts() const { return LangOpts; } 3220 void setBlockID(signed i) { currentBlock = i; } 3221 void setStmtID(unsigned i) { currentStmt = i; } 3222 3223 virtual bool handledStmt(Stmt *S, raw_ostream &OS) { 3224 StmtMapTy::iterator I = StmtMap.find(S); 3225 3226 if (I == StmtMap.end()) 3227 return false; 3228 3229 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3230 && I->second.second == currentStmt) { 3231 return false; 3232 } 3233 3234 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3235 return true; 3236 } 3237 3238 bool handleDecl(const Decl *D, raw_ostream &OS) { 3239 DeclMapTy::iterator I = DeclMap.find(D); 3240 3241 if (I == DeclMap.end()) 3242 return false; 3243 3244 if (currentBlock >= 0 && I->second.first == (unsigned) currentBlock 3245 && I->second.second == currentStmt) { 3246 return false; 3247 } 3248 3249 OS << "[B" << I->second.first << "." << I->second.second << "]"; 3250 return true; 3251 } 3252}; 3253} // end anonymous namespace 3254 3255 3256namespace { 3257class CFGBlockTerminatorPrint 3258 : public StmtVisitor<CFGBlockTerminatorPrint,void> { 3259 3260 raw_ostream &OS; 3261 StmtPrinterHelper* Helper; 3262 PrintingPolicy Policy; 3263public: 3264 CFGBlockTerminatorPrint(raw_ostream &os, StmtPrinterHelper* helper, 3265 const PrintingPolicy &Policy) 3266 : OS(os), Helper(helper), Policy(Policy) {} 3267 3268 void VisitIfStmt(IfStmt *I) { 3269 OS << "if "; 3270 I->getCond()->printPretty(OS,Helper,Policy); 3271 } 3272 3273 // Default case. 3274 void VisitStmt(Stmt *Terminator) { 3275 Terminator->printPretty(OS, Helper, Policy); 3276 } 3277 3278 void VisitForStmt(ForStmt *F) { 3279 OS << "for (" ; 3280 if (F->getInit()) 3281 OS << "..."; 3282 OS << "; "; 3283 if (Stmt *C = F->getCond()) 3284 C->printPretty(OS, Helper, Policy); 3285 OS << "; "; 3286 if (F->getInc()) 3287 OS << "..."; 3288 OS << ")"; 3289 } 3290 3291 void VisitWhileStmt(WhileStmt *W) { 3292 OS << "while " ; 3293 if (Stmt *C = W->getCond()) 3294 C->printPretty(OS, Helper, Policy); 3295 } 3296 3297 void VisitDoStmt(DoStmt *D) { 3298 OS << "do ... while "; 3299 if (Stmt *C = D->getCond()) 3300 C->printPretty(OS, Helper, Policy); 3301 } 3302 3303 void VisitSwitchStmt(SwitchStmt *Terminator) { 3304 OS << "switch "; 3305 Terminator->getCond()->printPretty(OS, Helper, Policy); 3306 } 3307 3308 void VisitCXXTryStmt(CXXTryStmt *CS) { 3309 OS << "try ..."; 3310 } 3311 3312 void VisitAbstractConditionalOperator(AbstractConditionalOperator* C) { 3313 C->getCond()->printPretty(OS, Helper, Policy); 3314 OS << " ? ... : ..."; 3315 } 3316 3317 void VisitChooseExpr(ChooseExpr *C) { 3318 OS << "__builtin_choose_expr( "; 3319 C->getCond()->printPretty(OS, Helper, Policy); 3320 OS << " )"; 3321 } 3322 3323 void VisitIndirectGotoStmt(IndirectGotoStmt *I) { 3324 OS << "goto *"; 3325 I->getTarget()->printPretty(OS, Helper, Policy); 3326 } 3327 3328 void VisitBinaryOperator(BinaryOperator* B) { 3329 if (!B->isLogicalOp()) { 3330 VisitExpr(B); 3331 return; 3332 } 3333 3334 B->getLHS()->printPretty(OS, Helper, Policy); 3335 3336 switch (B->getOpcode()) { 3337 case BO_LOr: 3338 OS << " || ..."; 3339 return; 3340 case BO_LAnd: 3341 OS << " && ..."; 3342 return; 3343 default: 3344 assert(false && "Invalid logical operator."); 3345 } 3346 } 3347 3348 void VisitExpr(Expr *E) { 3349 E->printPretty(OS, Helper, Policy); 3350 } 3351}; 3352} // end anonymous namespace 3353 3354static void print_elem(raw_ostream &OS, StmtPrinterHelper* Helper, 3355 const CFGElement &E) { 3356 if (const CFGStmt *CS = E.getAs<CFGStmt>()) { 3357 const Stmt *S = CS->getStmt(); 3358 3359 if (Helper) { 3360 3361 // special printing for statement-expressions. 3362 if (const StmtExpr *SE = dyn_cast<StmtExpr>(S)) { 3363 const CompoundStmt *Sub = SE->getSubStmt(); 3364 3365 if (Sub->children()) { 3366 OS << "({ ... ; "; 3367 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS); 3368 OS << " })\n"; 3369 return; 3370 } 3371 } 3372 // special printing for comma expressions. 3373 if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) { 3374 if (B->getOpcode() == BO_Comma) { 3375 OS << "... , "; 3376 Helper->handledStmt(B->getRHS(),OS); 3377 OS << '\n'; 3378 return; 3379 } 3380 } 3381 } 3382 S->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3383 3384 if (isa<CXXOperatorCallExpr>(S)) { 3385 OS << " (OperatorCall)"; 3386 } else if (isa<CXXBindTemporaryExpr>(S)) { 3387 OS << " (BindTemporary)"; 3388 } 3389 3390 // Expressions need a newline. 3391 if (isa<Expr>(S)) 3392 OS << '\n'; 3393 3394 } else if (const CFGInitializer *IE = E.getAs<CFGInitializer>()) { 3395 const CXXCtorInitializer *I = IE->getInitializer(); 3396 if (I->isBaseInitializer()) 3397 OS << I->getBaseClass()->getAsCXXRecordDecl()->getName(); 3398 else OS << I->getAnyMember()->getName(); 3399 3400 OS << "("; 3401 if (Expr *IE = I->getInit()) 3402 IE->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts())); 3403 OS << ")"; 3404 3405 if (I->isBaseInitializer()) 3406 OS << " (Base initializer)\n"; 3407 else OS << " (Member initializer)\n"; 3408 3409 } else if (const CFGAutomaticObjDtor *DE = E.getAs<CFGAutomaticObjDtor>()){ 3410 const VarDecl *VD = DE->getVarDecl(); 3411 Helper->handleDecl(VD, OS); 3412 3413 const Type* T = VD->getType().getTypePtr(); 3414 if (const ReferenceType* RT = T->getAs<ReferenceType>()) 3415 T = RT->getPointeeType().getTypePtr(); 3416 else if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3417 T = ET; 3418 3419 OS << ".~" << T->getAsCXXRecordDecl()->getName().str() << "()"; 3420 OS << " (Implicit destructor)\n"; 3421 3422 } else if (const CFGBaseDtor *BE = E.getAs<CFGBaseDtor>()) { 3423 const CXXBaseSpecifier *BS = BE->getBaseSpecifier(); 3424 OS << "~" << BS->getType()->getAsCXXRecordDecl()->getName() << "()"; 3425 OS << " (Base object destructor)\n"; 3426 3427 } else if (const CFGMemberDtor *ME = E.getAs<CFGMemberDtor>()) { 3428 const FieldDecl *FD = ME->getFieldDecl(); 3429 3430 const Type *T = FD->getType().getTypePtr(); 3431 if (const Type *ET = T->getArrayElementTypeNoTypeQual()) 3432 T = ET; 3433 3434 OS << "this->" << FD->getName(); 3435 OS << ".~" << T->getAsCXXRecordDecl()->getName() << "()"; 3436 OS << " (Member object destructor)\n"; 3437 3438 } else if (const CFGTemporaryDtor *TE = E.getAs<CFGTemporaryDtor>()) { 3439 const CXXBindTemporaryExpr *BT = TE->getBindTemporaryExpr(); 3440 OS << "~" << BT->getType()->getAsCXXRecordDecl()->getName() << "()"; 3441 OS << " (Temporary object destructor)\n"; 3442 } 3443} 3444 3445static void print_block(raw_ostream &OS, const CFG* cfg, 3446 const CFGBlock &B, 3447 StmtPrinterHelper* Helper, bool print_edges) { 3448 3449 if (Helper) Helper->setBlockID(B.getBlockID()); 3450 3451 // Print the header. 3452 OS << "\n [ B" << B.getBlockID(); 3453 3454 if (&B == &cfg->getEntry()) 3455 OS << " (ENTRY) ]\n"; 3456 else if (&B == &cfg->getExit()) 3457 OS << " (EXIT) ]\n"; 3458 else if (&B == cfg->getIndirectGotoBlock()) 3459 OS << " (INDIRECT GOTO DISPATCH) ]\n"; 3460 else 3461 OS << " ]\n"; 3462 3463 // Print the label of this block. 3464 if (Stmt *Label = const_cast<Stmt*>(B.getLabel())) { 3465 3466 if (print_edges) 3467 OS << " "; 3468 3469 if (LabelStmt *L = dyn_cast<LabelStmt>(Label)) 3470 OS << L->getName(); 3471 else if (CaseStmt *C = dyn_cast<CaseStmt>(Label)) { 3472 OS << "case "; 3473 C->getLHS()->printPretty(OS, Helper, 3474 PrintingPolicy(Helper->getLangOpts())); 3475 if (C->getRHS()) { 3476 OS << " ... "; 3477 C->getRHS()->printPretty(OS, Helper, 3478 PrintingPolicy(Helper->getLangOpts())); 3479 } 3480 } else if (isa<DefaultStmt>(Label)) 3481 OS << "default"; 3482 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) { 3483 OS << "catch ("; 3484 if (CS->getExceptionDecl()) 3485 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()), 3486 0); 3487 else 3488 OS << "..."; 3489 OS << ")"; 3490 3491 } else 3492 assert(false && "Invalid label statement in CFGBlock."); 3493 3494 OS << ":\n"; 3495 } 3496 3497 // Iterate through the statements in the block and print them. 3498 unsigned j = 1; 3499 3500 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ; 3501 I != E ; ++I, ++j ) { 3502 3503 // Print the statement # in the basic block and the statement itself. 3504 if (print_edges) 3505 OS << " "; 3506 3507 OS << llvm::format("%3d", j) << ": "; 3508 3509 if (Helper) 3510 Helper->setStmtID(j); 3511 3512 print_elem(OS,Helper,*I); 3513 } 3514 3515 // Print the terminator of this block. 3516 if (B.getTerminator()) { 3517 if (print_edges) 3518 OS << " "; 3519 3520 OS << " T: "; 3521 3522 if (Helper) Helper->setBlockID(-1); 3523 3524 CFGBlockTerminatorPrint TPrinter(OS, Helper, 3525 PrintingPolicy(Helper->getLangOpts())); 3526 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator().getStmt())); 3527 OS << '\n'; 3528 } 3529 3530 if (print_edges) { 3531 // Print the predecessors of this block. 3532 OS << " Predecessors (" << B.pred_size() << "):"; 3533 unsigned i = 0; 3534 3535 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end(); 3536 I != E; ++I, ++i) { 3537 3538 if (i == 8 || (i-8) == 0) 3539 OS << "\n "; 3540 3541 OS << " B" << (*I)->getBlockID(); 3542 } 3543 3544 OS << '\n'; 3545 3546 // Print the successors of this block. 3547 OS << " Successors (" << B.succ_size() << "):"; 3548 i = 0; 3549 3550 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end(); 3551 I != E; ++I, ++i) { 3552 3553 if (i == 8 || (i-8) % 10 == 0) 3554 OS << "\n "; 3555 3556 if (*I) 3557 OS << " B" << (*I)->getBlockID(); 3558 else 3559 OS << " NULL"; 3560 } 3561 3562 OS << '\n'; 3563 } 3564} 3565 3566 3567/// dump - A simple pretty printer of a CFG that outputs to stderr. 3568void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); } 3569 3570/// print - A simple pretty printer of a CFG that outputs to an ostream. 3571void CFG::print(raw_ostream &OS, const LangOptions &LO) const { 3572 StmtPrinterHelper Helper(this, LO); 3573 3574 // Print the entry block. 3575 print_block(OS, this, getEntry(), &Helper, true); 3576 3577 // Iterate through the CFGBlocks and print them one by one. 3578 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) { 3579 // Skip the entry block, because we already printed it. 3580 if (&(**I) == &getEntry() || &(**I) == &getExit()) 3581 continue; 3582 3583 print_block(OS, this, **I, &Helper, true); 3584 } 3585 3586 // Print the exit block. 3587 print_block(OS, this, getExit(), &Helper, true); 3588 OS.flush(); 3589} 3590 3591/// dump - A simply pretty printer of a CFGBlock that outputs to stderr. 3592void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const { 3593 print(llvm::errs(), cfg, LO); 3594} 3595 3596/// print - A simple pretty printer of a CFGBlock that outputs to an ostream. 3597/// Generally this will only be called from CFG::print. 3598void CFGBlock::print(raw_ostream &OS, const CFG* cfg, 3599 const LangOptions &LO) const { 3600 StmtPrinterHelper Helper(cfg, LO); 3601 print_block(OS, cfg, *this, &Helper, true); 3602} 3603 3604/// printTerminator - A simple pretty printer of the terminator of a CFGBlock. 3605void CFGBlock::printTerminator(raw_ostream &OS, 3606 const LangOptions &LO) const { 3607 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO)); 3608 TPrinter.Visit(const_cast<Stmt*>(getTerminator().getStmt())); 3609} 3610 3611Stmt *CFGBlock::getTerminatorCondition() { 3612 Stmt *Terminator = this->Terminator; 3613 if (!Terminator) 3614 return NULL; 3615 3616 Expr *E = NULL; 3617 3618 switch (Terminator->getStmtClass()) { 3619 default: 3620 break; 3621 3622 case Stmt::ForStmtClass: 3623 E = cast<ForStmt>(Terminator)->getCond(); 3624 break; 3625 3626 case Stmt::WhileStmtClass: 3627 E = cast<WhileStmt>(Terminator)->getCond(); 3628 break; 3629 3630 case Stmt::DoStmtClass: 3631 E = cast<DoStmt>(Terminator)->getCond(); 3632 break; 3633 3634 case Stmt::IfStmtClass: 3635 E = cast<IfStmt>(Terminator)->getCond(); 3636 break; 3637 3638 case Stmt::ChooseExprClass: 3639 E = cast<ChooseExpr>(Terminator)->getCond(); 3640 break; 3641 3642 case Stmt::IndirectGotoStmtClass: 3643 E = cast<IndirectGotoStmt>(Terminator)->getTarget(); 3644 break; 3645 3646 case Stmt::SwitchStmtClass: 3647 E = cast<SwitchStmt>(Terminator)->getCond(); 3648 break; 3649 3650 case Stmt::BinaryConditionalOperatorClass: 3651 E = cast<BinaryConditionalOperator>(Terminator)->getCond(); 3652 break; 3653 3654 case Stmt::ConditionalOperatorClass: 3655 E = cast<ConditionalOperator>(Terminator)->getCond(); 3656 break; 3657 3658 case Stmt::BinaryOperatorClass: // '&&' and '||' 3659 E = cast<BinaryOperator>(Terminator)->getLHS(); 3660 break; 3661 3662 case Stmt::ObjCForCollectionStmtClass: 3663 return Terminator; 3664 } 3665 3666 return E ? E->IgnoreParens() : NULL; 3667} 3668 3669//===----------------------------------------------------------------------===// 3670// CFG Graphviz Visualization 3671//===----------------------------------------------------------------------===// 3672 3673 3674#ifndef NDEBUG 3675static StmtPrinterHelper* GraphHelper; 3676#endif 3677 3678void CFG::viewCFG(const LangOptions &LO) const { 3679#ifndef NDEBUG 3680 StmtPrinterHelper H(this, LO); 3681 GraphHelper = &H; 3682 llvm::ViewGraph(this,"CFG"); 3683 GraphHelper = NULL; 3684#endif 3685} 3686 3687namespace llvm { 3688template<> 3689struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits { 3690 3691 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 3692 3693 static std::string getNodeLabel(const CFGBlock *Node, const CFG* Graph) { 3694 3695#ifndef NDEBUG 3696 std::string OutSStr; 3697 llvm::raw_string_ostream Out(OutSStr); 3698 print_block(Out,Graph, *Node, GraphHelper, false); 3699 std::string& OutStr = Out.str(); 3700 3701 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 3702 3703 // Process string output to make it nicer... 3704 for (unsigned i = 0; i != OutStr.length(); ++i) 3705 if (OutStr[i] == '\n') { // Left justify 3706 OutStr[i] = '\\'; 3707 OutStr.insert(OutStr.begin()+i+1, 'l'); 3708 } 3709 3710 return OutStr; 3711#else 3712 return ""; 3713#endif 3714 } 3715}; 3716} // end namespace llvm 3717