1 //===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
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 "llvm/Support/GraphWriter.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/OwningPtr.h"
27 using namespace clang;
31 static SourceLocation GetEndLoc(Decl* D) {
32 if (VarDecl* VD = dyn_cast<VarDecl>(D))
33 if (Expr* Ex = VD->getInit())
34 return Ex->getSourceRange().getEnd();
36 return D->getLocation();
41 enum Kind { NotAlwaysAdd = 0,
43 AsLValueNotAlwaysAdd = 2,
44 AlwaysAddAsLValue = 3 };
46 AddStmtChoice(Kind kind) : k(kind) {}
48 bool alwaysAdd() const { return (unsigned)k & 0x1; }
49 bool asLValue() const { return k >= AsLValueNotAlwaysAdd; }
55 /// CFGBuilder - This class implements CFG construction from an AST.
56 /// The builder is stateful: an instance of the builder should be used to only
57 /// construct a single CFG.
61 /// CFGBuilder builder;
62 /// CFG* cfg = builder.BuildAST(stmt1);
64 /// CFG construction is done via a recursive walk of an AST. We actually parse
65 /// the AST in reverse order so that the successor of a basic block is
66 /// constructed prior to its predecessor. This allows us to nicely capture
67 /// implicit fall-throughs without extra basic blocks.
71 llvm::OwningPtr<CFG> cfg;
75 CFGBlock* ContinueTargetBlock;
76 CFGBlock* BreakTargetBlock;
77 CFGBlock* SwitchTerminatedBlock;
78 CFGBlock* DefaultCaseBlock;
79 CFGBlock* TryTerminatedBlock;
81 // LabelMap records the mapping from Label expressions to their blocks.
82 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
85 // A list of blocks that end with a "goto" that must be backpatched to their
86 // resolved targets upon completion of CFG construction.
87 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
88 BackpatchBlocksTy BackpatchBlocks;
90 // A list of labels whose address has been taken (for indirect gotos).
91 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
92 LabelSetTy AddressTakenLabels;
95 explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
96 Block(NULL), Succ(NULL),
97 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
98 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL),
99 TryTerminatedBlock(NULL) {}
101 // buildCFG - Used by external clients to construct the CFG.
102 CFG* buildCFG(const Decl *D, Stmt *Statement, ASTContext *C, bool AddEHEdges,
106 // Visitors to walk an AST and construct the CFG.
107 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, AddStmtChoice asc);
108 CFGBlock *VisitBinaryOperator(BinaryOperator *B, AddStmtChoice asc);
109 CFGBlock *VisitBlockExpr(BlockExpr* E, AddStmtChoice asc);
110 CFGBlock *VisitBreakStmt(BreakStmt *B);
111 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S);
112 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
113 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S);
114 CFGBlock *VisitCXXMemberCallExpr(CXXMemberCallExpr *C, AddStmtChoice asc);
115 CFGBlock *VisitCallExpr(CallExpr *C, AddStmtChoice asc);
116 CFGBlock *VisitCaseStmt(CaseStmt *C);
117 CFGBlock *VisitChooseExpr(ChooseExpr *C, AddStmtChoice asc);
118 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
119 CFGBlock *VisitConditionalOperator(ConditionalOperator *C, AddStmtChoice asc);
120 CFGBlock *VisitContinueStmt(ContinueStmt *C);
121 CFGBlock *VisitDeclStmt(DeclStmt *DS);
122 CFGBlock *VisitDeclSubExpr(Decl* D);
123 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
124 CFGBlock *VisitDoStmt(DoStmt *D);
125 CFGBlock *VisitForStmt(ForStmt *F);
126 CFGBlock *VisitGotoStmt(GotoStmt* G);
127 CFGBlock *VisitIfStmt(IfStmt *I);
128 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
129 CFGBlock *VisitLabelStmt(LabelStmt *L);
130 CFGBlock *VisitMemberExpr(MemberExpr *M, AddStmtChoice asc);
131 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
132 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
133 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
134 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
135 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
136 CFGBlock *VisitReturnStmt(ReturnStmt* R);
137 CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, AddStmtChoice asc);
138 CFGBlock *VisitStmtExpr(StmtExpr *S, AddStmtChoice asc);
139 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
140 CFGBlock *VisitWhileStmt(WhileStmt *W);
142 CFGBlock *Visit(Stmt *S, AddStmtChoice asc = AddStmtChoice::NotAlwaysAdd);
143 CFGBlock *VisitStmt(Stmt *S, AddStmtChoice asc);
144 CFGBlock *VisitChildren(Stmt* S);
146 // NYS == Not Yet Supported
152 CFGBlock *StartScope(Stmt *S, CFGBlock *B) {
158 B->StartScope(S, cfg->getBumpVectorContext());
162 void EndScope(Stmt *S) {
167 Block = createBlock();
168 Block->EndScope(S, cfg->getBumpVectorContext());
171 void autoCreateBlock() { if (!Block) Block = createBlock(); }
172 CFGBlock *createBlock(bool add_successor = true);
173 bool FinishBlock(CFGBlock* B);
174 CFGBlock *addStmt(Stmt *S, AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
175 return Visit(S, asc);
178 void AppendStmt(CFGBlock *B, Stmt *S,
179 AddStmtChoice asc = AddStmtChoice::AlwaysAdd) {
180 B->appendStmt(S, cfg->getBumpVectorContext(), asc.asLValue());
183 void AddSuccessor(CFGBlock *B, CFGBlock *S) {
184 B->addSuccessor(S, cfg->getBumpVectorContext());
187 /// TryResult - a class representing a variant over the values
188 /// 'true', 'false', or 'unknown'. This is returned by TryEvaluateBool,
189 /// and is used by the CFGBuilder to decide if a branch condition
190 /// can be decided up front during CFG construction.
194 TryResult(bool b) : X(b ? 1 : 0) {}
195 TryResult() : X(-1) {}
197 bool isTrue() const { return X == 1; }
198 bool isFalse() const { return X == 0; }
199 bool isKnown() const { return X >= 0; }
206 /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
207 /// if we can evaluate to a known value, otherwise return -1.
208 TryResult TryEvaluateBool(Expr *S) {
209 Expr::EvalResult Result;
210 if (!S->isTypeDependent() && !S->isValueDependent() &&
211 S->Evaluate(Result, *Context) && Result.Val.isInt())
212 return Result.Val.getInt().getBoolValue();
219 // True iff EH edges on CallExprs should be added to the CFG.
222 // True iff scope start and scope end notes should be added to the CFG.
226 // FIXME: Add support for dependent-sized array types in C++?
227 // Does it even make sense to build a CFG for an uninstantiated template?
228 static VariableArrayType* FindVA(Type* t) {
229 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
230 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
231 if (vat->getSizeExpr())
234 t = vt->getElementType().getTypePtr();
240 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
241 /// arbitrary statement. Examples include a single expression or a function
242 /// body (compound statement). The ownership of the returned CFG is
243 /// transferred to the caller. If CFG construction fails, this method returns
245 CFG* CFGBuilder::buildCFG(const Decl *D, Stmt* Statement, ASTContext* C,
246 bool addehedges, bool AddScopes) {
247 AddEHEdges = addehedges;
253 this->AddScopes = AddScopes;
256 // Create an empty block that will serve as the exit block for the CFG. Since
257 // this is the first block added to the CFG, it will be implicitly registered
258 // as the exit block.
259 Succ = createBlock();
260 assert(Succ == &cfg->getExit());
261 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
263 // Visit the statements and create the CFG.
264 CFGBlock* B = addStmt(Statement);
266 if (const CXXConstructorDecl *CD = dyn_cast_or_null<CXXConstructorDecl>(D)) {
267 // FIXME: Add code for base initializers and member initializers.
274 // Finalize the last constructed block. This usually involves reversing the
275 // order of the statements in the block.
276 if (Block) FinishBlock(B);
278 // Backpatch the gotos whose label -> block mappings we didn't know when we
280 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
281 E = BackpatchBlocks.end(); I != E; ++I ) {
284 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
285 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
287 // If there is no target for the goto, then we are looking at an
288 // incomplete AST. Handle this by not registering a successor.
289 if (LI == LabelMap.end()) continue;
291 AddSuccessor(B, LI->second);
294 // Add successors to the Indirect Goto Dispatch block (if we have one).
295 if (CFGBlock* B = cfg->getIndirectGotoBlock())
296 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
297 E = AddressTakenLabels.end(); I != E; ++I ) {
299 // Lookup the target block.
300 LabelMapTy::iterator LI = LabelMap.find(*I);
302 // If there is no target block that contains label, then we are looking
303 // at an incomplete AST. Handle this by not registering a successor.
304 if (LI == LabelMap.end()) continue;
306 AddSuccessor(B, LI->second);
312 // Create an empty entry block that has no predecessors.
313 cfg->setEntry(createBlock());
315 return badCFG ? NULL : cfg.take();
318 /// createBlock - Used to lazily create blocks that are connected
319 /// to the current (global) succcessor.
320 CFGBlock* CFGBuilder::createBlock(bool add_successor) {
321 CFGBlock* B = cfg->createBlock();
322 if (add_successor && Succ)
323 AddSuccessor(B, Succ);
327 /// FinishBlock - "Finalize" the block by checking if we have a bad CFG.
328 bool CFGBuilder::FinishBlock(CFGBlock* B) {
336 /// Visit - Walk the subtree of a statement and add extra
337 /// blocks for ternary operators, &&, and ||. We also process "," and
338 /// DeclStmts (which may contain nested control-flow).
339 CFGBlock* CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
345 switch (S->getStmtClass()) {
347 return VisitStmt(S, asc);
349 case Stmt::AddrLabelExprClass:
350 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), asc);
352 case Stmt::BinaryOperatorClass:
353 return VisitBinaryOperator(cast<BinaryOperator>(S), asc);
355 case Stmt::BlockExprClass:
356 return VisitBlockExpr(cast<BlockExpr>(S), asc);
358 case Stmt::BreakStmtClass:
359 return VisitBreakStmt(cast<BreakStmt>(S));
361 case Stmt::CallExprClass:
362 return VisitCallExpr(cast<CallExpr>(S), asc);
364 case Stmt::CaseStmtClass:
365 return VisitCaseStmt(cast<CaseStmt>(S));
367 case Stmt::ChooseExprClass:
368 return VisitChooseExpr(cast<ChooseExpr>(S), asc);
370 case Stmt::CompoundStmtClass:
371 return VisitCompoundStmt(cast<CompoundStmt>(S));
373 case Stmt::ConditionalOperatorClass:
374 return VisitConditionalOperator(cast<ConditionalOperator>(S), asc);
376 case Stmt::ContinueStmtClass:
377 return VisitContinueStmt(cast<ContinueStmt>(S));
379 case Stmt::CXXCatchStmtClass:
380 return VisitCXXCatchStmt(cast<CXXCatchStmt>(S));
382 case Stmt::CXXMemberCallExprClass:
383 return VisitCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), asc);
385 case Stmt::CXXThrowExprClass:
386 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
388 case Stmt::CXXTryStmtClass:
389 return VisitCXXTryStmt(cast<CXXTryStmt>(S));
391 case Stmt::DeclStmtClass:
392 return VisitDeclStmt(cast<DeclStmt>(S));
394 case Stmt::DefaultStmtClass:
395 return VisitDefaultStmt(cast<DefaultStmt>(S));
397 case Stmt::DoStmtClass:
398 return VisitDoStmt(cast<DoStmt>(S));
400 case Stmt::ForStmtClass:
401 return VisitForStmt(cast<ForStmt>(S));
403 case Stmt::GotoStmtClass:
404 return VisitGotoStmt(cast<GotoStmt>(S));
406 case Stmt::IfStmtClass:
407 return VisitIfStmt(cast<IfStmt>(S));
409 case Stmt::IndirectGotoStmtClass:
410 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
412 case Stmt::LabelStmtClass:
413 return VisitLabelStmt(cast<LabelStmt>(S));
415 case Stmt::MemberExprClass:
416 return VisitMemberExpr(cast<MemberExpr>(S), asc);
418 case Stmt::ObjCAtCatchStmtClass:
419 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
421 case Stmt::ObjCAtSynchronizedStmtClass:
422 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
424 case Stmt::ObjCAtThrowStmtClass:
425 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
427 case Stmt::ObjCAtTryStmtClass:
428 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
430 case Stmt::ObjCForCollectionStmtClass:
431 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
433 case Stmt::ParenExprClass:
434 S = cast<ParenExpr>(S)->getSubExpr();
437 case Stmt::NullStmtClass:
440 case Stmt::ReturnStmtClass:
441 return VisitReturnStmt(cast<ReturnStmt>(S));
443 case Stmt::SizeOfAlignOfExprClass:
444 return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), asc);
446 case Stmt::StmtExprClass:
447 return VisitStmtExpr(cast<StmtExpr>(S), asc);
449 case Stmt::SwitchStmtClass:
450 return VisitSwitchStmt(cast<SwitchStmt>(S));
452 case Stmt::WhileStmtClass:
453 return VisitWhileStmt(cast<WhileStmt>(S));
457 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, AddStmtChoice asc) {
458 if (asc.alwaysAdd()) {
460 AppendStmt(Block, S, asc);
463 return VisitChildren(S);
466 /// VisitChildren - Visit the children of a Stmt.
467 CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
469 for (Stmt::child_iterator I = Terminator->child_begin(),
470 E = Terminator->child_end(); I != E; ++I) {
471 if (*I) B = Visit(*I);
476 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A,
478 AddressTakenLabels.insert(A->getLabel());
480 if (asc.alwaysAdd()) {
482 AppendStmt(Block, A, asc);
488 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B,
490 if (B->isLogicalOp()) { // && or ||
491 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
492 AppendStmt(ConfluenceBlock, B, asc);
494 if (!FinishBlock(ConfluenceBlock))
497 // create the block evaluating the LHS
498 CFGBlock* LHSBlock = createBlock(false);
499 LHSBlock->setTerminator(B);
501 // create the block evaluating the RHS
502 Succ = ConfluenceBlock;
504 CFGBlock* RHSBlock = addStmt(B->getRHS());
507 if (!FinishBlock(RHSBlock))
511 // Create an empty block for cases where the RHS doesn't require
512 // any explicit statements in the CFG.
513 RHSBlock = createBlock();
516 // See if this is a known constant.
517 TryResult KnownVal = TryEvaluateBool(B->getLHS());
518 if (KnownVal.isKnown() && (B->getOpcode() == BinaryOperator::LOr))
521 // Now link the LHSBlock with RHSBlock.
522 if (B->getOpcode() == BinaryOperator::LOr) {
523 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
524 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
526 assert(B->getOpcode() == BinaryOperator::LAnd);
527 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
528 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
531 // Generate the blocks for evaluating the LHS.
533 return addStmt(B->getLHS());
535 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
537 AppendStmt(Block, B, asc);
538 addStmt(B->getRHS());
539 return addStmt(B->getLHS());
542 return VisitStmt(B, asc);
545 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, AddStmtChoice asc) {
546 if (asc.alwaysAdd()) {
548 AppendStmt(Block, E, asc);
553 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
554 // "break" is a control-flow statement. Thus we stop processing the current
556 if (Block && !FinishBlock(Block))
559 // Now create a new block that ends with the break statement.
560 Block = createBlock(false);
561 Block->setTerminator(B);
563 // If there is no target for the break, then we are looking at an incomplete
564 // AST. This means that the CFG cannot be constructed.
565 if (BreakTargetBlock)
566 AddSuccessor(Block, BreakTargetBlock);
574 static bool CanThrow(Expr *E) {
575 QualType Ty = E->getType();
576 if (Ty->isFunctionPointerType())
577 Ty = Ty->getAs<PointerType>()->getPointeeType();
578 else if (Ty->isBlockPointerType())
579 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
581 const FunctionType *FT = Ty->getAs<FunctionType>();
583 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
584 if (Proto->hasEmptyExceptionSpec())
590 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) {
591 // If this is a call to a no-return function, this stops the block here.
592 bool NoReturn = false;
593 if (getFunctionExtInfo(*C->getCallee()->getType()).getNoReturn()) {
597 bool AddEHEdge = false;
599 // Languages without exceptions are assumed to not throw.
600 if (Context->getLangOptions().Exceptions) {
605 if (FunctionDecl *FD = C->getDirectCallee()) {
606 if (FD->hasAttr<NoReturnAttr>())
608 if (FD->hasAttr<NoThrowAttr>())
612 if (!CanThrow(C->getCallee()))
615 if (!NoReturn && !AddEHEdge)
616 return VisitStmt(C, AddStmtChoice::AlwaysAdd);
620 if (!FinishBlock(Block))
624 Block = createBlock(!NoReturn);
625 AppendStmt(Block, C, asc);
628 // Wire this to the exit block directly.
629 AddSuccessor(Block, &cfg->getExit());
632 // Add exceptional edges.
633 if (TryTerminatedBlock)
634 AddSuccessor(Block, TryTerminatedBlock);
636 AddSuccessor(Block, &cfg->getExit());
639 return VisitChildren(C);
642 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C,
644 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
645 AppendStmt(ConfluenceBlock, C, asc);
646 if (!FinishBlock(ConfluenceBlock))
649 asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
650 : AddStmtChoice::AlwaysAdd;
652 Succ = ConfluenceBlock;
654 CFGBlock* LHSBlock = addStmt(C->getLHS(), asc);
655 if (!FinishBlock(LHSBlock))
658 Succ = ConfluenceBlock;
660 CFGBlock* RHSBlock = addStmt(C->getRHS(), asc);
661 if (!FinishBlock(RHSBlock))
664 Block = createBlock(false);
665 // See if this is a known constant.
666 const TryResult& KnownVal = TryEvaluateBool(C->getCond());
667 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
668 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
669 Block->setTerminator(C);
670 return addStmt(C->getCond());
674 CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
677 CFGBlock* LastBlock = Block;
679 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
681 LastBlock = addStmt(*I);
687 LastBlock = StartScope(C, LastBlock);
692 CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C,
694 // Create the confluence block that will "merge" the results of the ternary
696 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
697 AppendStmt(ConfluenceBlock, C, asc);
698 if (!FinishBlock(ConfluenceBlock))
701 asc = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
702 : AddStmtChoice::AlwaysAdd;
704 // Create a block for the LHS expression if there is an LHS expression. A
705 // GCC extension allows LHS to be NULL, causing the condition to be the
706 // value that is returned instead.
707 // e.g: x ?: y is shorthand for: x ? x : y;
708 Succ = ConfluenceBlock;
710 CFGBlock* LHSBlock = NULL;
712 LHSBlock = addStmt(C->getLHS(), asc);
713 if (!FinishBlock(LHSBlock))
718 // Create the block for the RHS expression.
719 Succ = ConfluenceBlock;
720 CFGBlock* RHSBlock = addStmt(C->getRHS(), asc);
721 if (!FinishBlock(RHSBlock))
724 // Create the block that will contain the condition.
725 Block = createBlock(false);
727 // See if this is a known constant.
728 const TryResult& KnownVal = TryEvaluateBool(C->getCond());
730 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
732 if (KnownVal.isFalse()) {
733 // If we know the condition is false, add NULL as the successor for
734 // the block containing the condition. In this case, the confluence
735 // block will have just one predecessor.
736 AddSuccessor(Block, 0);
737 assert(ConfluenceBlock->pred_size() == 1);
739 // If we have no LHS expression, add the ConfluenceBlock as a direct
740 // successor for the block containing the condition. Moreover, we need to
741 // reverse the order of the predecessors in the ConfluenceBlock because
742 // the RHSBlock will have been added to the succcessors already, and we
743 // want the first predecessor to the the block containing the expression
744 // for the case when the ternary expression evaluates to true.
745 AddSuccessor(Block, ConfluenceBlock);
746 assert(ConfluenceBlock->pred_size() == 2);
747 std::reverse(ConfluenceBlock->pred_begin(),
748 ConfluenceBlock->pred_end());
752 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
753 Block->setTerminator(C);
754 return addStmt(C->getCond());
757 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
760 if (DS->isSingleDecl()) {
761 AppendStmt(Block, DS);
762 return VisitDeclSubExpr(DS->getSingleDecl());
767 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
768 typedef llvm::SmallVector<Decl*,10> BufTy;
769 BufTy Buf(DS->decl_begin(), DS->decl_end());
771 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
772 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
773 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
774 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
776 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
777 // automatically freed with the CFG.
780 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
781 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
783 // Append the fake DeclStmt to block.
784 AppendStmt(Block, DSNew);
785 B = VisitDeclSubExpr(D);
791 /// VisitDeclSubExpr - Utility method to add block-level expressions for
792 /// initializers in Decls.
793 CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
796 VarDecl *VD = dyn_cast<VarDecl>(D);
801 Expr *Init = VD->getInit();
804 AddStmtChoice::Kind k =
805 VD->getType()->isReferenceType() ? AddStmtChoice::AsLValueNotAlwaysAdd
806 : AddStmtChoice::NotAlwaysAdd;
807 Visit(Init, AddStmtChoice(k));
810 // If the type of VD is a VLA, then we must process its size expressions.
811 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
812 VA = FindVA(VA->getElementType().getTypePtr()))
813 Block = addStmt(VA->getSizeExpr());
818 CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
819 // We may see an if statement in the middle of a basic block, or it may be the
820 // first statement we are processing. In either case, we create a new basic
821 // block. First, we create the blocks for the then...else statements, and
822 // then we create the block containing the if statement. If we were in the
823 // middle of a block, we stop processing that block. That block is then the
824 // implicit successor for the "then" and "else" clauses.
826 // The block we were proccessing is now finished. Make it the successor
830 if (!FinishBlock(Block))
834 // Process the false branch.
835 CFGBlock* ElseBlock = Succ;
837 if (Stmt* Else = I->getElse()) {
838 SaveAndRestore<CFGBlock*> sv(Succ);
840 // NULL out Block so that the recursive call to Visit will
841 // create a new basic block.
843 ElseBlock = addStmt(Else);
845 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
846 ElseBlock = sv.get();
848 if (!FinishBlock(ElseBlock))
853 // Process the true branch.
856 Stmt* Then = I->getThen();
858 SaveAndRestore<CFGBlock*> sv(Succ);
860 ThenBlock = addStmt(Then);
863 // We can reach here if the "then" body has all NullStmts.
864 // Create an empty block so we can distinguish between true and false
865 // branches in path-sensitive analyses.
866 ThenBlock = createBlock(false);
867 AddSuccessor(ThenBlock, sv.get());
869 if (!FinishBlock(ThenBlock))
874 // Now create a new block containing the if statement.
875 Block = createBlock(false);
877 // Set the terminator of the new block to the If statement.
878 Block->setTerminator(I);
880 // See if this is a known constant.
881 const TryResult &KnownVal = TryEvaluateBool(I->getCond());
883 // Now add the successors.
884 AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
885 AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
887 // Add the condition as the last statement in the new block. This may create
888 // new blocks as the condition may contain control-flow. Any newly created
889 // blocks will be pointed to be "Block".
890 Block = addStmt(I->getCond());
892 // Finally, if the IfStmt contains a condition variable, add both the IfStmt
893 // and the condition variable initialization to the CFG.
894 if (VarDecl *VD = I->getConditionVariable()) {
895 if (Expr *Init = VD->getInit()) {
897 AppendStmt(Block, I, AddStmtChoice::AlwaysAdd);
906 CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
907 // If we were in the middle of a block we stop processing that block.
909 // NOTE: If a "return" appears in the middle of a block, this means that the
910 // code afterwards is DEAD (unreachable). We still keep a basic block
911 // for that code; a simple "mark-and-sweep" from the entry block will be
912 // able to report such dead blocks.
916 // Create the new block.
917 Block = createBlock(false);
919 // The Exit block is the only successor.
920 AddSuccessor(Block, &cfg->getExit());
922 // Add the return statement to the block. This may create new blocks if R
923 // contains control-flow (short-circuit operations).
924 return VisitStmt(R, AddStmtChoice::AlwaysAdd);
927 CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
928 // Get the block of the labeled statement. Add it to our map.
929 addStmt(L->getSubStmt());
930 CFGBlock* LabelBlock = Block;
932 if (!LabelBlock) // This can happen when the body is empty, i.e.
933 LabelBlock = createBlock(); // scopes that only contains NullStmts.
935 assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
936 LabelMap[ L ] = LabelBlock;
938 // Labels partition blocks, so this is the end of the basic block we were
939 // processing (L is the block's label). Because this is label (and we have
940 // already processed the substatement) there is no extra control-flow to worry
942 LabelBlock->setLabel(L);
943 if (!FinishBlock(LabelBlock))
946 // We set Block to NULL to allow lazy creation of a new block (if necessary);
949 // This block is now the implicit successor of other blocks.
955 CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
956 // Goto is a control-flow statement. Thus we stop processing the current
957 // block and create a new one.
961 Block = createBlock(false);
962 Block->setTerminator(G);
964 // If we already know the mapping to the label block add the successor now.
965 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
967 if (I == LabelMap.end())
968 // We will need to backpatch this block later.
969 BackpatchBlocks.push_back(Block);
971 AddSuccessor(Block, I->second);
976 CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
977 CFGBlock* LoopSuccessor = NULL;
979 // "for" is a control-flow statement. Thus we stop processing the current
982 if (!FinishBlock(Block))
984 LoopSuccessor = Block;
986 LoopSuccessor = Succ;
988 // Save the current value for the break targets.
989 // All breaks should go to the code following the loop.
990 SaveAndRestore<CFGBlock*> save_break(BreakTargetBlock);
991 BreakTargetBlock = LoopSuccessor;
993 // Because of short-circuit evaluation, the condition of the loop can span
994 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
995 // evaluate the condition.
996 CFGBlock* ExitConditionBlock = createBlock(false);
997 CFGBlock* EntryConditionBlock = ExitConditionBlock;
999 // Set the terminator for the "exit" condition block.
1000 ExitConditionBlock->setTerminator(F);
1002 // Now add the actual condition to the condition block. Because the condition
1003 // itself may contain control-flow, new blocks may be created.
1004 if (Stmt* C = F->getCond()) {
1005 Block = ExitConditionBlock;
1006 EntryConditionBlock = addStmt(C);
1007 assert(Block == EntryConditionBlock);
1009 // If this block contains a condition variable, add both the condition
1010 // variable and initializer to the CFG.
1011 if (VarDecl *VD = F->getConditionVariable()) {
1012 if (Expr *Init = VD->getInit()) {
1014 AppendStmt(Block, F, AddStmtChoice::AlwaysAdd);
1015 EntryConditionBlock = addStmt(Init);
1016 assert(Block == EntryConditionBlock);
1021 if (!FinishBlock(EntryConditionBlock))
1026 // The condition block is the implicit successor for the loop body as well as
1027 // any code above the loop.
1028 Succ = EntryConditionBlock;
1030 // See if this is a known constant.
1031 TryResult KnownVal(true);
1034 KnownVal = TryEvaluateBool(F->getCond());
1036 // Now create the loop body.
1038 assert(F->getBody());
1040 // Save the current values for Block, Succ, and continue targets.
1041 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1042 save_continue(ContinueTargetBlock);
1044 // Create a new block to contain the (bottom) of the loop body.
1047 if (Stmt* I = F->getInc()) {
1048 // Generate increment code in its own basic block. This is the target of
1049 // continue statements.
1052 // No increment code. Create a special, empty, block that is used as the
1053 // target block for "looping back" to the start of the loop.
1054 assert(Succ == EntryConditionBlock);
1055 Succ = createBlock();
1058 // Finish up the increment (or empty) block if it hasn't been already.
1060 assert(Block == Succ);
1061 if (!FinishBlock(Block))
1066 ContinueTargetBlock = Succ;
1068 // The starting block for the loop increment is the block that should
1069 // represent the 'loop target' for looping back to the start of the loop.
1070 ContinueTargetBlock->setLoopTarget(F);
1072 // Now populate the body block, and in the process create new blocks as we
1073 // walk the body of the loop.
1074 CFGBlock* BodyBlock = addStmt(F->getBody());
1077 BodyBlock = ContinueTargetBlock; // can happen for "for (...;...;...) ;"
1078 else if (Block && !FinishBlock(BodyBlock))
1081 // This new body block is a successor to our "exit" condition block.
1082 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1085 // Link up the condition block with the code that follows the loop. (the
1087 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1089 // If the loop contains initialization, create a new block for those
1090 // statements. This block can also contain statements that precede the loop.
1091 if (Stmt* I = F->getInit()) {
1092 Block = createBlock();
1095 // There is no loop initialization. We are thus basically a while loop.
1096 // NULL out Block to force lazy block construction.
1098 Succ = EntryConditionBlock;
1099 return EntryConditionBlock;
1103 CFGBlock *CFGBuilder::VisitMemberExpr(MemberExpr *M, AddStmtChoice asc) {
1104 if (asc.alwaysAdd()) {
1106 AppendStmt(Block, M, asc);
1108 return Visit(M->getBase(),
1109 M->isArrow() ? AddStmtChoice::NotAlwaysAdd
1110 : AddStmtChoice::AsLValueNotAlwaysAdd);
1113 CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
1114 // Objective-C fast enumeration 'for' statements:
1115 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
1117 // for ( Type newVariable in collection_expression ) { statements }
1122 // 1. collection_expression
1123 // T. jump to loop_entry
1125 // 1. side-effects of element expression
1126 // 1. ObjCForCollectionStmt [performs binding to newVariable]
1127 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
1130 // T. jump to loop_entry
1136 // Type existingItem;
1137 // for ( existingItem in expression ) { statements }
1141 // the same with newVariable replaced with existingItem; the binding works
1142 // the same except that for one ObjCForCollectionStmt::getElement() returns
1143 // a DeclStmt and the other returns a DeclRefExpr.
1146 CFGBlock* LoopSuccessor = 0;
1149 if (!FinishBlock(Block))
1151 LoopSuccessor = Block;
1154 LoopSuccessor = Succ;
1156 // Build the condition blocks.
1157 CFGBlock* ExitConditionBlock = createBlock(false);
1158 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1160 // Set the terminator for the "exit" condition block.
1161 ExitConditionBlock->setTerminator(S);
1163 // The last statement in the block should be the ObjCForCollectionStmt, which
1164 // performs the actual binding to 'element' and determines if there are any
1165 // more items in the collection.
1166 AppendStmt(ExitConditionBlock, S);
1167 Block = ExitConditionBlock;
1169 // Walk the 'element' expression to see if there are any side-effects. We
1170 // generate new blocks as necesary. We DON'T add the statement by default to
1171 // the CFG unless it contains control-flow.
1172 EntryConditionBlock = Visit(S->getElement(), AddStmtChoice::NotAlwaysAdd);
1174 if (!FinishBlock(EntryConditionBlock))
1179 // The condition block is the implicit successor for the loop body as well as
1180 // any code above the loop.
1181 Succ = EntryConditionBlock;
1183 // Now create the true branch.
1185 // Save the current values for Succ, continue and break targets.
1186 SaveAndRestore<CFGBlock*> save_Succ(Succ),
1187 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
1189 BreakTargetBlock = LoopSuccessor;
1190 ContinueTargetBlock = EntryConditionBlock;
1192 CFGBlock* BodyBlock = addStmt(S->getBody());
1195 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1197 if (!FinishBlock(BodyBlock))
1201 // This new body block is a successor to our "exit" condition block.
1202 AddSuccessor(ExitConditionBlock, BodyBlock);
1205 // Link up the condition block with the code that follows the loop.
1206 // (the false branch).
1207 AddSuccessor(ExitConditionBlock, LoopSuccessor);
1209 // Now create a prologue block to contain the collection expression.
1210 Block = createBlock();
1211 return addStmt(S->getCollection());
1214 CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1215 // FIXME: Add locking 'primitives' to CFG for @synchronized.
1218 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1220 // The sync body starts its own basic block. This makes it a little easier
1221 // for diagnostic clients.
1223 if (!FinishBlock(SyncBlock))
1230 // Inline the sync expression.
1231 return addStmt(S->getSynchExpr());
1234 CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1239 CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1240 CFGBlock* LoopSuccessor = NULL;
1242 // "while" is a control-flow statement. Thus we stop processing the current
1245 if (!FinishBlock(Block))
1247 LoopSuccessor = Block;
1249 LoopSuccessor = Succ;
1251 // Because of short-circuit evaluation, the condition of the loop can span
1252 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1253 // evaluate the condition.
1254 CFGBlock* ExitConditionBlock = createBlock(false);
1255 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1257 // Set the terminator for the "exit" condition block.
1258 ExitConditionBlock->setTerminator(W);
1260 // Now add the actual condition to the condition block. Because the condition
1261 // itself may contain control-flow, new blocks may be created. Thus we update
1262 // "Succ" after adding the condition.
1263 if (Stmt* C = W->getCond()) {
1264 Block = ExitConditionBlock;
1265 EntryConditionBlock = addStmt(C);
1266 assert(Block == EntryConditionBlock);
1268 // If this block contains a condition variable, add both the condition
1269 // variable and initializer to the CFG.
1270 if (VarDecl *VD = W->getConditionVariable()) {
1271 if (Expr *Init = VD->getInit()) {
1273 AppendStmt(Block, W, AddStmtChoice::AlwaysAdd);
1274 EntryConditionBlock = addStmt(Init);
1275 assert(Block == EntryConditionBlock);
1280 if (!FinishBlock(EntryConditionBlock))
1285 // The condition block is the implicit successor for the loop body as well as
1286 // any code above the loop.
1287 Succ = EntryConditionBlock;
1289 // See if this is a known constant.
1290 const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1292 // Process the loop body.
1294 assert(W->getBody());
1296 // Save the current values for Block, Succ, and continue and break targets
1297 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1298 save_continue(ContinueTargetBlock),
1299 save_break(BreakTargetBlock);
1301 // Create an empty block to represent the transition block for looping back
1302 // to the head of the loop.
1304 assert(Succ == EntryConditionBlock);
1305 Succ = createBlock();
1306 Succ->setLoopTarget(W);
1307 ContinueTargetBlock = Succ;
1309 // All breaks should go to the code following the loop.
1310 BreakTargetBlock = LoopSuccessor;
1312 // NULL out Block to force lazy instantiation of blocks for the body.
1315 // Create the body. The returned block is the entry to the loop body.
1316 CFGBlock* BodyBlock = addStmt(W->getBody());
1319 BodyBlock = ContinueTargetBlock; // can happen for "while(...) ;"
1321 if (!FinishBlock(BodyBlock))
1325 // Add the loop body entry as a successor to the condition.
1326 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1329 // Link up the condition block with the code that follows the loop. (the
1331 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1333 // There can be no more statements in the condition block since we loop back
1334 // to this block. NULL out Block to force lazy creation of another block.
1337 // Return the condition block, which is the dominating block for the loop.
1338 Succ = EntryConditionBlock;
1339 return EntryConditionBlock;
1343 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1344 // FIXME: For now we pretend that @catch and the code it contains does not
1349 CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1350 // FIXME: This isn't complete. We basically treat @throw like a return
1353 // If we were in the middle of a block we stop processing that block.
1354 if (Block && !FinishBlock(Block))
1357 // Create the new block.
1358 Block = createBlock(false);
1360 // The Exit block is the only successor.
1361 AddSuccessor(Block, &cfg->getExit());
1363 // Add the statement to the block. This may create new blocks if S contains
1364 // control-flow (short-circuit operations).
1365 return VisitStmt(S, AddStmtChoice::AlwaysAdd);
1368 CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1369 // If we were in the middle of a block we stop processing that block.
1370 if (Block && !FinishBlock(Block))
1373 // Create the new block.
1374 Block = createBlock(false);
1376 if (TryTerminatedBlock)
1377 // The current try statement is the only successor.
1378 AddSuccessor(Block, TryTerminatedBlock);
1380 // otherwise the Exit block is the only successor.
1381 AddSuccessor(Block, &cfg->getExit());
1383 // Add the statement to the block. This may create new blocks if S contains
1384 // control-flow (short-circuit operations).
1385 return VisitStmt(T, AddStmtChoice::AlwaysAdd);
1388 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1389 CFGBlock* LoopSuccessor = NULL;
1391 // "do...while" is a control-flow statement. Thus we stop processing the
1394 if (!FinishBlock(Block))
1396 LoopSuccessor = Block;
1398 LoopSuccessor = Succ;
1400 // Because of short-circuit evaluation, the condition of the loop can span
1401 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1402 // evaluate the condition.
1403 CFGBlock* ExitConditionBlock = createBlock(false);
1404 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1406 // Set the terminator for the "exit" condition block.
1407 ExitConditionBlock->setTerminator(D);
1409 // Now add the actual condition to the condition block. Because the condition
1410 // itself may contain control-flow, new blocks may be created.
1411 if (Stmt* C = D->getCond()) {
1412 Block = ExitConditionBlock;
1413 EntryConditionBlock = addStmt(C);
1415 if (!FinishBlock(EntryConditionBlock))
1420 // The condition block is the implicit successor for the loop body.
1421 Succ = EntryConditionBlock;
1423 // See if this is a known constant.
1424 const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1426 // Process the loop body.
1427 CFGBlock* BodyBlock = NULL;
1429 assert(D->getBody());
1431 // Save the current values for Block, Succ, and continue and break targets
1432 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1433 save_continue(ContinueTargetBlock),
1434 save_break(BreakTargetBlock);
1436 // All continues within this loop should go to the condition block
1437 ContinueTargetBlock = EntryConditionBlock;
1439 // All breaks should go to the code following the loop.
1440 BreakTargetBlock = LoopSuccessor;
1442 // NULL out Block to force lazy instantiation of blocks for the body.
1445 // Create the body. The returned block is the entry to the loop body.
1446 BodyBlock = addStmt(D->getBody());
1449 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1451 if (!FinishBlock(BodyBlock))
1455 // Add an intermediate block between the BodyBlock and the
1456 // ExitConditionBlock to represent the "loop back" transition. Create an
1457 // empty block to represent the transition block for looping back to the
1458 // head of the loop.
1459 // FIXME: Can we do this more efficiently without adding another block?
1462 CFGBlock *LoopBackBlock = createBlock();
1463 LoopBackBlock->setLoopTarget(D);
1465 // Add the loop body entry as a successor to the condition.
1466 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : LoopBackBlock);
1469 // Link up the condition block with the code that follows the loop.
1470 // (the false branch).
1471 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1473 // There can be no more statements in the body block(s) since we loop back to
1474 // the body. NULL out Block to force lazy creation of another block.
1477 // Return the loop body, which is the dominating block for the loop.
1482 CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1483 // "continue" is a control-flow statement. Thus we stop processing the
1485 if (Block && !FinishBlock(Block))
1488 // Now create a new block that ends with the continue statement.
1489 Block = createBlock(false);
1490 Block->setTerminator(C);
1492 // If there is no target for the continue, then we are looking at an
1493 // incomplete AST. This means the CFG cannot be constructed.
1494 if (ContinueTargetBlock)
1495 AddSuccessor(Block, ContinueTargetBlock);
1502 CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1503 AddStmtChoice asc) {
1505 if (asc.alwaysAdd()) {
1507 AppendStmt(Block, E);
1510 // VLA types have expressions that must be evaluated.
1511 if (E->isArgumentType()) {
1512 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1513 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1514 addStmt(VA->getSizeExpr());
1520 /// VisitStmtExpr - Utility method to handle (nested) statement
1521 /// expressions (a GCC extension).
1522 CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, AddStmtChoice asc) {
1523 if (asc.alwaysAdd()) {
1525 AppendStmt(Block, SE);
1527 return VisitCompoundStmt(SE->getSubStmt());
1530 CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
1531 // "switch" is a control-flow statement. Thus we stop processing the current
1533 CFGBlock* SwitchSuccessor = NULL;
1536 if (!FinishBlock(Block))
1538 SwitchSuccessor = Block;
1539 } else SwitchSuccessor = Succ;
1541 // Save the current "switch" context.
1542 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
1543 save_break(BreakTargetBlock),
1544 save_default(DefaultCaseBlock);
1546 // Set the "default" case to be the block after the switch statement. If the
1547 // switch statement contains a "default:", this value will be overwritten with
1548 // the block for that code.
1549 DefaultCaseBlock = SwitchSuccessor;
1551 // Create a new block that will contain the switch statement.
1552 SwitchTerminatedBlock = createBlock(false);
1554 // Now process the switch body. The code after the switch is the implicit
1556 Succ = SwitchSuccessor;
1557 BreakTargetBlock = SwitchSuccessor;
1559 // When visiting the body, the case statements should automatically get linked
1560 // up to the switch. We also don't keep a pointer to the body, since all
1561 // control-flow from the switch goes to case/default statements.
1562 assert(Terminator->getBody() && "switch must contain a non-NULL body");
1564 CFGBlock *BodyBlock = addStmt(Terminator->getBody());
1566 if (!FinishBlock(BodyBlock))
1570 // If we have no "default:" case, the default transition is to the code
1571 // following the switch body.
1572 AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
1574 // Add the terminator and condition in the switch block.
1575 SwitchTerminatedBlock->setTerminator(Terminator);
1576 assert(Terminator->getCond() && "switch condition must be non-NULL");
1577 Block = SwitchTerminatedBlock;
1578 Block = addStmt(Terminator->getCond());
1580 // Finally, if the SwitchStmt contains a condition variable, add both the
1581 // SwitchStmt and the condition variable initialization to the CFG.
1582 if (VarDecl *VD = Terminator->getConditionVariable()) {
1583 if (Expr *Init = VD->getInit()) {
1585 AppendStmt(Block, Terminator, AddStmtChoice::AlwaysAdd);
1593 CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
1594 // CaseStmts are essentially labels, so they are the first statement in a
1597 if (CS->getSubStmt())
1598 addStmt(CS->getSubStmt());
1600 CFGBlock* CaseBlock = Block;
1602 CaseBlock = createBlock();
1604 // Cases statements partition blocks, so this is the top of the basic block we
1605 // were processing (the "case XXX:" is the label).
1606 CaseBlock->setLabel(CS);
1608 if (!FinishBlock(CaseBlock))
1611 // Add this block to the list of successors for the block with the switch
1613 assert(SwitchTerminatedBlock);
1614 AddSuccessor(SwitchTerminatedBlock, CaseBlock);
1616 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1619 // This block is now the implicit successor of other blocks.
1625 CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1626 if (Terminator->getSubStmt())
1627 addStmt(Terminator->getSubStmt());
1629 DefaultCaseBlock = Block;
1631 if (!DefaultCaseBlock)
1632 DefaultCaseBlock = createBlock();
1634 // Default statements partition blocks, so this is the top of the basic block
1635 // we were processing (the "default:" is the label).
1636 DefaultCaseBlock->setLabel(Terminator);
1638 if (!FinishBlock(DefaultCaseBlock))
1641 // Unlike case statements, we don't add the default block to the successors
1642 // for the switch statement immediately. This is done when we finish
1643 // processing the switch statement. This allows for the default case
1644 // (including a fall-through to the code after the switch statement) to always
1645 // be the last successor of a switch-terminated block.
1647 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1650 // This block is now the implicit successor of other blocks.
1651 Succ = DefaultCaseBlock;
1653 return DefaultCaseBlock;
1656 CFGBlock *CFGBuilder::VisitCXXTryStmt(CXXTryStmt *Terminator) {
1657 // "try"/"catch" is a control-flow statement. Thus we stop processing the
1659 CFGBlock* TrySuccessor = NULL;
1662 if (!FinishBlock(Block))
1664 TrySuccessor = Block;
1665 } else TrySuccessor = Succ;
1667 CFGBlock *PrevTryTerminatedBlock = TryTerminatedBlock;
1669 // Create a new block that will contain the try statement.
1670 CFGBlock *NewTryTerminatedBlock = createBlock(false);
1671 // Add the terminator in the try block.
1672 NewTryTerminatedBlock->setTerminator(Terminator);
1674 bool HasCatchAll = false;
1675 for (unsigned h = 0; h <Terminator->getNumHandlers(); ++h) {
1676 // The code after the try is the implicit successor.
1677 Succ = TrySuccessor;
1678 CXXCatchStmt *CS = Terminator->getHandler(h);
1679 if (CS->getExceptionDecl() == 0) {
1683 CFGBlock *CatchBlock = VisitCXXCatchStmt(CS);
1684 if (CatchBlock == 0)
1686 // Add this block to the list of successors for the block with the try
1688 AddSuccessor(NewTryTerminatedBlock, CatchBlock);
1691 if (PrevTryTerminatedBlock)
1692 AddSuccessor(NewTryTerminatedBlock, PrevTryTerminatedBlock);
1694 AddSuccessor(NewTryTerminatedBlock, &cfg->getExit());
1697 // The code after the try is the implicit successor.
1698 Succ = TrySuccessor;
1700 // Save the current "try" context.
1701 SaveAndRestore<CFGBlock*> save_try(TryTerminatedBlock);
1702 TryTerminatedBlock = NewTryTerminatedBlock;
1704 assert(Terminator->getTryBlock() && "try must contain a non-NULL body");
1706 Block = addStmt(Terminator->getTryBlock());
1710 CFGBlock* CFGBuilder::VisitCXXCatchStmt(CXXCatchStmt* CS) {
1711 // CXXCatchStmt are treated like labels, so they are the first statement in a
1714 if (CS->getHandlerBlock())
1715 addStmt(CS->getHandlerBlock());
1717 CFGBlock* CatchBlock = Block;
1719 CatchBlock = createBlock();
1721 CatchBlock->setLabel(CS);
1723 if (!FinishBlock(CatchBlock))
1726 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1732 CFGBlock *CFGBuilder::VisitCXXMemberCallExpr(CXXMemberCallExpr *C,
1733 AddStmtChoice asc) {
1734 AddStmtChoice::Kind K = asc.asLValue() ? AddStmtChoice::AlwaysAddAsLValue
1735 : AddStmtChoice::AlwaysAdd;
1737 AppendStmt(Block, C, AddStmtChoice(K));
1738 return VisitChildren(C);
1741 CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1742 // Lazily create the indirect-goto dispatch block if there isn't one already.
1743 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1746 IBlock = createBlock(false);
1747 cfg->setIndirectGotoBlock(IBlock);
1750 // IndirectGoto is a control-flow statement. Thus we stop processing the
1751 // current block and create a new one.
1752 if (Block && !FinishBlock(Block))
1755 Block = createBlock(false);
1756 Block->setTerminator(I);
1757 AddSuccessor(Block, IBlock);
1758 return addStmt(I->getTarget());
1761 } // end anonymous namespace
1763 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
1764 /// no successors or predecessors. If this is the first block created in the
1765 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
1766 CFGBlock* CFG::createBlock() {
1767 bool first_block = begin() == end();
1769 // Create the block.
1770 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
1771 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
1772 Blocks.push_back(Mem, BlkBVC);
1774 // If this is the first block, set it as the Entry and Exit.
1776 Entry = Exit = &back();
1778 // Return the block.
1782 /// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1783 /// CFG is returned to the caller.
1784 CFG* CFG::buildCFG(const Decl *D, Stmt* Statement, ASTContext *C,
1785 bool AddEHEdges, bool AddScopes) {
1787 return Builder.buildCFG(D, Statement, C, AddEHEdges, AddScopes);
1790 //===----------------------------------------------------------------------===//
1791 // CFG: Queries for BlkExprs.
1792 //===----------------------------------------------------------------------===//
1795 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
1798 static void FindSubExprAssignments(Stmt *S,
1799 llvm::SmallPtrSet<Expr*,50>& Set) {
1803 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1808 if (BinaryOperator* B = dyn_cast<BinaryOperator>(child))
1809 if (B->isAssignmentOp()) Set.insert(B);
1811 FindSubExprAssignments(child, Set);
1815 static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1816 BlkExprMapTy* M = new BlkExprMapTy();
1818 // Look for assignments that are used as subexpressions. These are the only
1819 // assignments that we want to *possibly* register as a block-level
1820 // expression. Basically, if an assignment occurs both in a subexpression and
1821 // at the block-level, it is a block-level expression.
1822 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1824 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1825 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1826 FindSubExprAssignments(*BI, SubExprAssignments);
1828 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1830 // Iterate over the statements again on identify the Expr* and Stmt* at the
1831 // block-level that are block-level expressions.
1833 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1834 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
1836 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
1837 // Assignment expressions that are not nested within another
1838 // expression are really "statements" whose value is never used by
1839 // another expression.
1840 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
1842 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
1843 // Special handling for statement expressions. The last statement in
1844 // the statement expression is also a block-level expr.
1845 const CompoundStmt* C = Terminator->getSubStmt();
1846 if (!C->body_empty()) {
1847 unsigned x = M->size();
1848 (*M)[C->body_back()] = x;
1852 unsigned x = M->size();
1856 // Look at terminators. The condition is a block-level expression.
1858 Stmt* S = (*I)->getTerminatorCondition();
1860 if (S && M->find(S) == M->end()) {
1861 unsigned x = M->size();
1869 CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1871 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1873 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1874 BlkExprMapTy::iterator I = M->find(S);
1875 return (I == M->end()) ? CFG::BlkExprNumTy() : CFG::BlkExprNumTy(I->second);
1878 unsigned CFG::getNumBlkExprs() {
1879 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1882 // We assume callers interested in the number of BlkExprs will want
1883 // the map constructed if it doesn't already exist.
1884 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1885 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1889 //===----------------------------------------------------------------------===//
1890 // Cleanup: CFG dstor.
1891 //===----------------------------------------------------------------------===//
1894 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1897 //===----------------------------------------------------------------------===//
1898 // CFG pretty printing
1899 //===----------------------------------------------------------------------===//
1903 class StmtPrinterHelper : public PrinterHelper {
1904 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1906 signed CurrentBlock;
1907 unsigned CurrentStmt;
1908 const LangOptions &LangOpts;
1911 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1912 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
1913 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1915 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
1916 BI != BEnd; ++BI, ++j )
1917 StmtMap[*BI] = std::make_pair((*I)->getBlockID(),j);
1921 virtual ~StmtPrinterHelper() {}
1923 const LangOptions &getLangOpts() const { return LangOpts; }
1924 void setBlockID(signed i) { CurrentBlock = i; }
1925 void setStmtID(unsigned i) { CurrentStmt = i; }
1927 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
1929 StmtMapTy::iterator I = StmtMap.find(Terminator);
1931 if (I == StmtMap.end())
1934 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1935 && I->second.second == CurrentStmt) {
1939 OS << "[B" << I->second.first << "." << I->second.second << "]";
1943 } // end anonymous namespace
1947 class CFGBlockTerminatorPrint
1948 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1950 llvm::raw_ostream& OS;
1951 StmtPrinterHelper* Helper;
1952 PrintingPolicy Policy;
1954 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
1955 const PrintingPolicy &Policy)
1956 : OS(os), Helper(helper), Policy(Policy) {}
1958 void VisitIfStmt(IfStmt* I) {
1960 I->getCond()->printPretty(OS,Helper,Policy);
1964 void VisitStmt(Stmt* Terminator) {
1965 Terminator->printPretty(OS, Helper, Policy);
1968 void VisitForStmt(ForStmt* F) {
1973 if (Stmt* C = F->getCond())
1974 C->printPretty(OS, Helper, Policy);
1981 void VisitWhileStmt(WhileStmt* W) {
1983 if (Stmt* C = W->getCond())
1984 C->printPretty(OS, Helper, Policy);
1987 void VisitDoStmt(DoStmt* D) {
1988 OS << "do ... while ";
1989 if (Stmt* C = D->getCond())
1990 C->printPretty(OS, Helper, Policy);
1993 void VisitSwitchStmt(SwitchStmt* Terminator) {
1995 Terminator->getCond()->printPretty(OS, Helper, Policy);
1998 void VisitCXXTryStmt(CXXTryStmt* CS) {
2002 void VisitConditionalOperator(ConditionalOperator* C) {
2003 C->getCond()->printPretty(OS, Helper, Policy);
2004 OS << " ? ... : ...";
2007 void VisitChooseExpr(ChooseExpr* C) {
2008 OS << "__builtin_choose_expr( ";
2009 C->getCond()->printPretty(OS, Helper, Policy);
2013 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
2015 I->getTarget()->printPretty(OS, Helper, Policy);
2018 void VisitBinaryOperator(BinaryOperator* B) {
2019 if (!B->isLogicalOp()) {
2024 B->getLHS()->printPretty(OS, Helper, Policy);
2026 switch (B->getOpcode()) {
2027 case BinaryOperator::LOr:
2030 case BinaryOperator::LAnd:
2034 assert(false && "Invalid logical operator.");
2038 void VisitExpr(Expr* E) {
2039 E->printPretty(OS, Helper, Policy);
2042 } // end anonymous namespace
2045 static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
2046 const CFGElement &E) {
2047 Stmt *Terminator = E;
2049 if (E.asStartScope()) {
2050 OS << "start scope\n";
2053 if (E.asEndScope()) {
2054 OS << "end scope\n";
2059 // special printing for statement-expressions.
2060 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
2061 CompoundStmt* Sub = SE->getSubStmt();
2063 if (Sub->child_begin() != Sub->child_end()) {
2065 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
2071 // special printing for comma expressions.
2072 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
2073 if (B->getOpcode() == BinaryOperator::Comma) {
2075 Helper->handledStmt(B->getRHS(),OS);
2082 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
2084 // Expressions need a newline.
2085 if (isa<Expr>(Terminator)) OS << '\n';
2088 static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
2090 StmtPrinterHelper* Helper, bool print_edges) {
2092 if (Helper) Helper->setBlockID(B.getBlockID());
2094 // Print the header.
2095 OS << "\n [ B" << B.getBlockID();
2097 if (&B == &cfg->getEntry())
2098 OS << " (ENTRY) ]\n";
2099 else if (&B == &cfg->getExit())
2100 OS << " (EXIT) ]\n";
2101 else if (&B == cfg->getIndirectGotoBlock())
2102 OS << " (INDIRECT GOTO DISPATCH) ]\n";
2106 // Print the label of this block.
2107 if (Stmt* Label = const_cast<Stmt*>(B.getLabel())) {
2112 if (LabelStmt* L = dyn_cast<LabelStmt>(Label))
2114 else if (CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
2116 C->getLHS()->printPretty(OS, Helper,
2117 PrintingPolicy(Helper->getLangOpts()));
2120 C->getRHS()->printPretty(OS, Helper,
2121 PrintingPolicy(Helper->getLangOpts()));
2123 } else if (isa<DefaultStmt>(Label))
2125 else if (CXXCatchStmt *CS = dyn_cast<CXXCatchStmt>(Label)) {
2127 if (CS->getExceptionDecl())
2128 CS->getExceptionDecl()->print(OS, PrintingPolicy(Helper->getLangOpts()),
2135 assert(false && "Invalid label statement in CFGBlock.");
2140 // Iterate through the statements in the block and print them.
2143 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
2144 I != E ; ++I, ++j ) {
2146 // Print the statement # in the basic block and the statement itself.
2150 OS << llvm::format("%3d", j) << ": ";
2153 Helper->setStmtID(j);
2155 print_stmt(OS,Helper,*I);
2158 // Print the terminator of this block.
2159 if (B.getTerminator()) {
2165 if (Helper) Helper->setBlockID(-1);
2167 CFGBlockTerminatorPrint TPrinter(OS, Helper,
2168 PrintingPolicy(Helper->getLangOpts()));
2169 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
2174 // Print the predecessors of this block.
2175 OS << " Predecessors (" << B.pred_size() << "):";
2178 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
2181 if (i == 8 || (i-8) == 0)
2184 OS << " B" << (*I)->getBlockID();
2189 // Print the successors of this block.
2190 OS << " Successors (" << B.succ_size() << "):";
2193 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
2196 if (i == 8 || (i-8) % 10 == 0)
2200 OS << " B" << (*I)->getBlockID();
2210 /// dump - A simple pretty printer of a CFG that outputs to stderr.
2211 void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
2213 /// print - A simple pretty printer of a CFG that outputs to an ostream.
2214 void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
2215 StmtPrinterHelper Helper(this, LO);
2217 // Print the entry block.
2218 print_block(OS, this, getEntry(), &Helper, true);
2220 // Iterate through the CFGBlocks and print them one by one.
2221 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
2222 // Skip the entry block, because we already printed it.
2223 if (&(**I) == &getEntry() || &(**I) == &getExit())
2226 print_block(OS, this, **I, &Helper, true);
2229 // Print the exit block.
2230 print_block(OS, this, getExit(), &Helper, true);
2234 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
2235 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
2236 print(llvm::errs(), cfg, LO);
2239 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
2240 /// Generally this will only be called from CFG::print.
2241 void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
2242 const LangOptions &LO) const {
2243 StmtPrinterHelper Helper(cfg, LO);
2244 print_block(OS, cfg, *this, &Helper, true);
2247 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
2248 void CFGBlock::printTerminator(llvm::raw_ostream &OS,
2249 const LangOptions &LO) const {
2250 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
2251 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
2254 Stmt* CFGBlock::getTerminatorCondition() {
2261 switch (Terminator->getStmtClass()) {
2265 case Stmt::ForStmtClass:
2266 E = cast<ForStmt>(Terminator)->getCond();
2269 case Stmt::WhileStmtClass:
2270 E = cast<WhileStmt>(Terminator)->getCond();
2273 case Stmt::DoStmtClass:
2274 E = cast<DoStmt>(Terminator)->getCond();
2277 case Stmt::IfStmtClass:
2278 E = cast<IfStmt>(Terminator)->getCond();
2281 case Stmt::ChooseExprClass:
2282 E = cast<ChooseExpr>(Terminator)->getCond();
2285 case Stmt::IndirectGotoStmtClass:
2286 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
2289 case Stmt::SwitchStmtClass:
2290 E = cast<SwitchStmt>(Terminator)->getCond();
2293 case Stmt::ConditionalOperatorClass:
2294 E = cast<ConditionalOperator>(Terminator)->getCond();
2297 case Stmt::BinaryOperatorClass: // '&&' and '||'
2298 E = cast<BinaryOperator>(Terminator)->getLHS();
2301 case Stmt::ObjCForCollectionStmtClass:
2305 return E ? E->IgnoreParens() : NULL;
2308 bool CFGBlock::hasBinaryBranchTerminator() const {
2315 switch (Terminator->getStmtClass()) {
2319 case Stmt::ForStmtClass:
2320 case Stmt::WhileStmtClass:
2321 case Stmt::DoStmtClass:
2322 case Stmt::IfStmtClass:
2323 case Stmt::ChooseExprClass:
2324 case Stmt::ConditionalOperatorClass:
2325 case Stmt::BinaryOperatorClass:
2329 return E ? E->IgnoreParens() : NULL;
2333 //===----------------------------------------------------------------------===//
2334 // CFG Graphviz Visualization
2335 //===----------------------------------------------------------------------===//
2339 static StmtPrinterHelper* GraphHelper;
2342 void CFG::viewCFG(const LangOptions &LO) const {
2344 StmtPrinterHelper H(this, LO);
2346 llvm::ViewGraph(this,"CFG");
2353 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
2355 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2357 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
2360 std::string OutSStr;
2361 llvm::raw_string_ostream Out(OutSStr);
2362 print_block(Out,Graph, *Node, GraphHelper, false);
2363 std::string& OutStr = Out.str();
2365 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
2367 // Process string output to make it nicer...
2368 for (unsigned i = 0; i != OutStr.length(); ++i)
2369 if (OutStr[i] == '\n') { // Left justify
2371 OutStr.insert(OutStr.begin()+i+1, 'l');
2380 } // end namespace llvm