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/StmtVisitor.h"
18 #include "clang/AST/PrettyPrinter.h"
19 #include "llvm/Support/GraphWriter.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/OwningPtr.h"
26 using namespace clang;
30 static SourceLocation GetEndLoc(Decl* D) {
31 if (VarDecl* VD = dyn_cast<VarDecl>(D))
32 if (Expr* Ex = VD->getInit())
33 return Ex->getSourceRange().getEnd();
35 return D->getLocation();
38 /// CFGBuilder - This class implements CFG construction from an AST.
39 /// The builder is stateful: an instance of the builder should be used to only
40 /// construct a single CFG.
44 /// CFGBuilder builder;
45 /// CFG* cfg = builder.BuildAST(stmt1);
47 /// CFG construction is done via a recursive walk of an AST. We actually parse
48 /// the AST in reverse order so that the successor of a basic block is
49 /// constructed prior to its predecessor. This allows us to nicely capture
50 /// implicit fall-throughs without extra basic blocks.
54 llvm::OwningPtr<CFG> cfg;
58 CFGBlock* ContinueTargetBlock;
59 CFGBlock* BreakTargetBlock;
60 CFGBlock* SwitchTerminatedBlock;
61 CFGBlock* DefaultCaseBlock;
63 // LabelMap records the mapping from Label expressions to their blocks.
64 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
67 // A list of blocks that end with a "goto" that must be backpatched to their
68 // resolved targets upon completion of CFG construction.
69 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
70 BackpatchBlocksTy BackpatchBlocks;
72 // A list of labels whose address has been taken (for indirect gotos).
73 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
74 LabelSetTy AddressTakenLabels;
77 explicit CFGBuilder() : cfg(new CFG()), // crew a new CFG
78 Block(NULL), Succ(NULL),
79 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
80 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {}
82 // buildCFG - Used by external clients to construct the CFG.
83 CFG* buildCFG(Stmt *Statement, ASTContext *C);
86 // Visitors to walk an AST and construct the CFG.
87 CFGBlock *VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd);
88 CFGBlock *VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd);
89 CFGBlock *VisitBlockExpr(BlockExpr* E, bool alwaysAdd);
90 CFGBlock *VisitBreakStmt(BreakStmt *B);
91 CFGBlock *VisitCallExpr(CallExpr *C, bool alwaysAdd);
92 CFGBlock *VisitCaseStmt(CaseStmt *C);
93 CFGBlock *VisitChooseExpr(ChooseExpr *C);
94 CFGBlock *VisitCompoundStmt(CompoundStmt *C);
95 CFGBlock *VisitConditionalOperator(ConditionalOperator *C);
96 CFGBlock *VisitContinueStmt(ContinueStmt *C);
97 CFGBlock *VisitCXXCatchStmt(CXXCatchStmt *S) { return NYS(); }
98 CFGBlock *VisitCXXThrowExpr(CXXThrowExpr *T);
99 CFGBlock *VisitCXXTryStmt(CXXTryStmt *S) { return NYS(); }
100 CFGBlock *VisitDeclStmt(DeclStmt *DS);
101 CFGBlock *VisitDeclSubExpr(Decl* D);
102 CFGBlock *VisitDefaultStmt(DefaultStmt *D);
103 CFGBlock *VisitDoStmt(DoStmt *D);
104 CFGBlock *VisitForStmt(ForStmt *F);
105 CFGBlock *VisitGotoStmt(GotoStmt* G);
106 CFGBlock *VisitIfStmt(IfStmt *I);
107 CFGBlock *VisitIndirectGotoStmt(IndirectGotoStmt *I);
108 CFGBlock *VisitLabelStmt(LabelStmt *L);
109 CFGBlock *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
110 CFGBlock *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
111 CFGBlock *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
112 CFGBlock *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
113 CFGBlock *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
114 CFGBlock *VisitReturnStmt(ReturnStmt* R);
115 CFGBlock *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E, bool alwaysAdd);
116 CFGBlock *VisitStmtExpr(StmtExpr *S, bool alwaysAdd);
117 CFGBlock *VisitSwitchStmt(SwitchStmt *S);
118 CFGBlock *VisitWhileStmt(WhileStmt *W);
120 CFGBlock *Visit(Stmt *S, bool alwaysAdd = false);
121 CFGBlock *VisitStmt(Stmt *S, bool alwaysAdd);
122 CFGBlock *VisitChildren(Stmt* S);
124 // NYS == Not Yet Supported
130 void autoCreateBlock() { if (!Block) Block = createBlock(); }
131 CFGBlock *createBlock(bool add_successor = true);
132 bool FinishBlock(CFGBlock* B);
133 CFGBlock *addStmt(Stmt *S) { return Visit(S, true); }
135 void AppendStmt(CFGBlock *B, Stmt *S) {
136 B->appendStmt(S, cfg->getBumpVectorContext());
139 void AddSuccessor(CFGBlock *B, CFGBlock *S) {
140 B->addSuccessor(S, cfg->getBumpVectorContext());
143 /// TryResult - a class representing a variant over the values
144 /// 'true', 'false', or 'unknown'. This is returned by TryEvaluateBool,
145 /// and is used by the CFGBuilder to decide if a branch condition
146 /// can be decided up front during CFG construction.
150 TryResult(bool b) : X(b ? 1 : 0) {}
151 TryResult() : X(-1) {}
153 bool isTrue() const { return X == 1; }
154 bool isFalse() const { return X == 0; }
155 bool isKnown() const { return X >= 0; }
162 /// TryEvaluateBool - Try and evaluate the Stmt and return 0 or 1
163 /// if we can evaluate to a known value, otherwise return -1.
164 TryResult TryEvaluateBool(Expr *S) {
165 Expr::EvalResult Result;
166 if (!S->isTypeDependent() && !S->isValueDependent() &&
167 S->Evaluate(Result, *Context) && Result.Val.isInt())
168 return Result.Val.getInt().getBoolValue();
176 // FIXME: Add support for dependent-sized array types in C++?
177 // Does it even make sense to build a CFG for an uninstantiated template?
178 static VariableArrayType* FindVA(Type* t) {
179 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
180 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
181 if (vat->getSizeExpr())
184 t = vt->getElementType().getTypePtr();
190 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can represent an
191 /// arbitrary statement. Examples include a single expression or a function
192 /// body (compound statement). The ownership of the returned CFG is
193 /// transferred to the caller. If CFG construction fails, this method returns
195 CFG* CFGBuilder::buildCFG(Stmt* Statement, ASTContext* C) {
203 // Create an empty block that will serve as the exit block for the CFG. Since
204 // this is the first block added to the CFG, it will be implicitly registered
205 // as the exit block.
206 Succ = createBlock();
207 assert(Succ == &cfg->getExit());
208 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
210 // Visit the statements and create the CFG.
211 CFGBlock* B = addStmt(Statement);
216 // Finalize the last constructed block. This usually involves reversing the
217 // order of the statements in the block.
218 if (Block) FinishBlock(B);
220 // Backpatch the gotos whose label -> block mappings we didn't know when we
222 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
223 E = BackpatchBlocks.end(); I != E; ++I ) {
226 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
227 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
229 // If there is no target for the goto, then we are looking at an
230 // incomplete AST. Handle this by not registering a successor.
231 if (LI == LabelMap.end()) continue;
233 AddSuccessor(B, LI->second);
236 // Add successors to the Indirect Goto Dispatch block (if we have one).
237 if (CFGBlock* B = cfg->getIndirectGotoBlock())
238 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
239 E = AddressTakenLabels.end(); I != E; ++I ) {
241 // Lookup the target block.
242 LabelMapTy::iterator LI = LabelMap.find(*I);
244 // If there is no target block that contains label, then we are looking
245 // at an incomplete AST. Handle this by not registering a successor.
246 if (LI == LabelMap.end()) continue;
248 AddSuccessor(B, LI->second);
254 // Create an empty entry block that has no predecessors.
255 cfg->setEntry(createBlock());
257 return badCFG ? NULL : cfg.take();
260 /// createBlock - Used to lazily create blocks that are connected
261 /// to the current (global) succcessor.
262 CFGBlock* CFGBuilder::createBlock(bool add_successor) {
263 CFGBlock* B = cfg->createBlock();
264 if (add_successor && Succ)
265 AddSuccessor(B, Succ);
269 /// FinishBlock - "Finalize" the block by checking if we have a bad CFG.
270 bool CFGBuilder::FinishBlock(CFGBlock* B) {
278 /// Visit - Walk the subtree of a statement and add extra
279 /// blocks for ternary operators, &&, and ||. We also process "," and
280 /// DeclStmts (which may contain nested control-flow).
281 CFGBlock* CFGBuilder::Visit(Stmt * S, bool alwaysAdd) {
283 switch (S->getStmtClass()) {
285 return VisitStmt(S, alwaysAdd);
287 case Stmt::AddrLabelExprClass:
288 return VisitAddrLabelExpr(cast<AddrLabelExpr>(S), alwaysAdd);
290 case Stmt::BinaryOperatorClass:
291 return VisitBinaryOperator(cast<BinaryOperator>(S), alwaysAdd);
293 case Stmt::BlockExprClass:
294 return VisitBlockExpr(cast<BlockExpr>(S), alwaysAdd);
296 case Stmt::BreakStmtClass:
297 return VisitBreakStmt(cast<BreakStmt>(S));
299 case Stmt::CallExprClass:
300 return VisitCallExpr(cast<CallExpr>(S), alwaysAdd);
302 case Stmt::CaseStmtClass:
303 return VisitCaseStmt(cast<CaseStmt>(S));
305 case Stmt::ChooseExprClass:
306 return VisitChooseExpr(cast<ChooseExpr>(S));
308 case Stmt::CompoundStmtClass:
309 return VisitCompoundStmt(cast<CompoundStmt>(S));
311 case Stmt::ConditionalOperatorClass:
312 return VisitConditionalOperator(cast<ConditionalOperator>(S));
314 case Stmt::ContinueStmtClass:
315 return VisitContinueStmt(cast<ContinueStmt>(S));
317 case Stmt::DeclStmtClass:
318 return VisitDeclStmt(cast<DeclStmt>(S));
320 case Stmt::DefaultStmtClass:
321 return VisitDefaultStmt(cast<DefaultStmt>(S));
323 case Stmt::DoStmtClass:
324 return VisitDoStmt(cast<DoStmt>(S));
326 case Stmt::ForStmtClass:
327 return VisitForStmt(cast<ForStmt>(S));
329 case Stmt::GotoStmtClass:
330 return VisitGotoStmt(cast<GotoStmt>(S));
332 case Stmt::IfStmtClass:
333 return VisitIfStmt(cast<IfStmt>(S));
335 case Stmt::IndirectGotoStmtClass:
336 return VisitIndirectGotoStmt(cast<IndirectGotoStmt>(S));
338 case Stmt::LabelStmtClass:
339 return VisitLabelStmt(cast<LabelStmt>(S));
341 case Stmt::ObjCAtCatchStmtClass:
342 return VisitObjCAtCatchStmt(cast<ObjCAtCatchStmt>(S));
344 case Stmt::CXXThrowExprClass:
345 return VisitCXXThrowExpr(cast<CXXThrowExpr>(S));
347 case Stmt::ObjCAtSynchronizedStmtClass:
348 return VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S));
350 case Stmt::ObjCAtThrowStmtClass:
351 return VisitObjCAtThrowStmt(cast<ObjCAtThrowStmt>(S));
353 case Stmt::ObjCAtTryStmtClass:
354 return VisitObjCAtTryStmt(cast<ObjCAtTryStmt>(S));
356 case Stmt::ObjCForCollectionStmtClass:
357 return VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S));
359 case Stmt::ParenExprClass:
360 S = cast<ParenExpr>(S)->getSubExpr();
363 case Stmt::NullStmtClass:
366 case Stmt::ReturnStmtClass:
367 return VisitReturnStmt(cast<ReturnStmt>(S));
369 case Stmt::SizeOfAlignOfExprClass:
370 return VisitSizeOfAlignOfExpr(cast<SizeOfAlignOfExpr>(S), alwaysAdd);
372 case Stmt::StmtExprClass:
373 return VisitStmtExpr(cast<StmtExpr>(S), alwaysAdd);
375 case Stmt::SwitchStmtClass:
376 return VisitSwitchStmt(cast<SwitchStmt>(S));
378 case Stmt::WhileStmtClass:
379 return VisitWhileStmt(cast<WhileStmt>(S));
383 CFGBlock *CFGBuilder::VisitStmt(Stmt *S, bool alwaysAdd) {
386 AppendStmt(Block, S);
389 return VisitChildren(S);
392 /// VisitChildren - Visit the children of a Stmt.
393 CFGBlock *CFGBuilder::VisitChildren(Stmt* Terminator) {
395 for (Stmt::child_iterator I = Terminator->child_begin(),
396 E = Terminator->child_end(); I != E; ++I) {
397 if (*I) B = Visit(*I);
402 CFGBlock *CFGBuilder::VisitAddrLabelExpr(AddrLabelExpr *A, bool alwaysAdd) {
403 AddressTakenLabels.insert(A->getLabel());
407 AppendStmt(Block, A);
413 CFGBlock *CFGBuilder::VisitBinaryOperator(BinaryOperator *B, bool alwaysAdd) {
414 if (B->isLogicalOp()) { // && or ||
415 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
416 AppendStmt(ConfluenceBlock, B);
418 if (!FinishBlock(ConfluenceBlock))
421 // create the block evaluating the LHS
422 CFGBlock* LHSBlock = createBlock(false);
423 LHSBlock->setTerminator(B);
425 // create the block evaluating the RHS
426 Succ = ConfluenceBlock;
428 CFGBlock* RHSBlock = addStmt(B->getRHS());
429 if (!FinishBlock(RHSBlock))
432 // See if this is a known constant.
433 TryResult KnownVal = TryEvaluateBool(B->getLHS());
434 if (KnownVal.isKnown() && (B->getOpcode() == BinaryOperator::LOr))
437 // Now link the LHSBlock with RHSBlock.
438 if (B->getOpcode() == BinaryOperator::LOr) {
439 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
440 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
442 assert (B->getOpcode() == BinaryOperator::LAnd);
443 AddSuccessor(LHSBlock, KnownVal.isFalse() ? NULL : RHSBlock);
444 AddSuccessor(LHSBlock, KnownVal.isTrue() ? NULL : ConfluenceBlock);
447 // Generate the blocks for evaluating the LHS.
449 return addStmt(B->getLHS());
451 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
453 AppendStmt(Block, B);
454 addStmt(B->getRHS());
455 return addStmt(B->getLHS());
458 return VisitStmt(B, alwaysAdd);
461 CFGBlock *CFGBuilder::VisitBlockExpr(BlockExpr *E, bool alwaysAdd) {
464 AppendStmt(Block, E);
469 CFGBlock *CFGBuilder::VisitBreakStmt(BreakStmt *B) {
470 // "break" is a control-flow statement. Thus we stop processing the current
472 if (Block && !FinishBlock(Block))
475 // Now create a new block that ends with the break statement.
476 Block = createBlock(false);
477 Block->setTerminator(B);
479 // If there is no target for the break, then we are looking at an incomplete
480 // AST. This means that the CFG cannot be constructed.
481 if (BreakTargetBlock)
482 AddSuccessor(Block, BreakTargetBlock);
490 CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, bool alwaysAdd) {
491 // If this is a call to a no-return function, this stops the block here.
492 bool NoReturn = false;
493 if (C->getCallee()->getType().getNoReturnAttr()) {
497 if (FunctionDecl *FD = C->getDirectCallee())
498 if (FD->hasAttr<NoReturnAttr>())
502 return VisitStmt(C, alwaysAdd);
504 if (Block && !FinishBlock(Block))
507 // Create new block with no successor for the remaining pieces.
508 Block = createBlock(false);
509 AppendStmt(Block, C);
511 // Wire this to the exit block directly.
512 AddSuccessor(Block, &cfg->getExit());
514 return VisitChildren(C);
517 CFGBlock *CFGBuilder::VisitChooseExpr(ChooseExpr *C) {
518 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
519 AppendStmt(ConfluenceBlock, C);
520 if (!FinishBlock(ConfluenceBlock))
523 Succ = ConfluenceBlock;
525 CFGBlock* LHSBlock = addStmt(C->getLHS());
526 if (!FinishBlock(LHSBlock))
529 Succ = ConfluenceBlock;
531 CFGBlock* RHSBlock = addStmt(C->getRHS());
532 if (!FinishBlock(RHSBlock))
535 Block = createBlock(false);
536 // See if this is a known constant.
537 const TryResult& KnownVal = TryEvaluateBool(C->getCond());
538 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
539 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
540 Block->setTerminator(C);
541 return addStmt(C->getCond());
545 CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
546 CFGBlock* LastBlock = Block;
548 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
550 LastBlock = addStmt(*I);
558 CFGBlock *CFGBuilder::VisitConditionalOperator(ConditionalOperator *C) {
559 // Create the confluence block that will "merge" the results of the ternary
561 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
562 AppendStmt(ConfluenceBlock, C);
563 if (!FinishBlock(ConfluenceBlock))
566 // Create a block for the LHS expression if there is an LHS expression. A
567 // GCC extension allows LHS to be NULL, causing the condition to be the
568 // value that is returned instead.
569 // e.g: x ?: y is shorthand for: x ? x : y;
570 Succ = ConfluenceBlock;
572 CFGBlock* LHSBlock = NULL;
574 LHSBlock = addStmt(C->getLHS());
575 if (!FinishBlock(LHSBlock))
580 // Create the block for the RHS expression.
581 Succ = ConfluenceBlock;
582 CFGBlock* RHSBlock = addStmt(C->getRHS());
583 if (!FinishBlock(RHSBlock))
586 // Create the block that will contain the condition.
587 Block = createBlock(false);
589 // See if this is a known constant.
590 const TryResult& KnownVal = TryEvaluateBool(C->getCond());
592 AddSuccessor(Block, KnownVal.isFalse() ? NULL : LHSBlock);
594 if (KnownVal.isFalse()) {
595 // If we know the condition is false, add NULL as the successor for
596 // the block containing the condition. In this case, the confluence
597 // block will have just one predecessor.
598 AddSuccessor(Block, 0);
599 assert(ConfluenceBlock->pred_size() == 1);
601 // If we have no LHS expression, add the ConfluenceBlock as a direct
602 // successor for the block containing the condition. Moreover, we need to
603 // reverse the order of the predecessors in the ConfluenceBlock because
604 // the RHSBlock will have been added to the succcessors already, and we
605 // want the first predecessor to the the block containing the expression
606 // for the case when the ternary expression evaluates to true.
607 AddSuccessor(Block, ConfluenceBlock);
608 assert(ConfluenceBlock->pred_size() == 2);
609 std::reverse(ConfluenceBlock->pred_begin(),
610 ConfluenceBlock->pred_end());
614 AddSuccessor(Block, KnownVal.isTrue() ? NULL : RHSBlock);
615 Block->setTerminator(C);
616 return addStmt(C->getCond());
619 CFGBlock *CFGBuilder::VisitDeclStmt(DeclStmt *DS) {
622 if (DS->isSingleDecl()) {
623 AppendStmt(Block, DS);
624 return VisitDeclSubExpr(DS->getSingleDecl());
629 // FIXME: Add a reverse iterator for DeclStmt to avoid this extra copy.
630 typedef llvm::SmallVector<Decl*,10> BufTy;
631 BufTy Buf(DS->decl_begin(), DS->decl_end());
633 for (BufTy::reverse_iterator I = Buf.rbegin(), E = Buf.rend(); I != E; ++I) {
634 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
635 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
636 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
638 // Allocate the DeclStmt using the BumpPtrAllocator. It will get
639 // automatically freed with the CFG.
642 void *Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
643 DeclStmt *DSNew = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
645 // Append the fake DeclStmt to block.
646 AppendStmt(Block, DSNew);
647 B = VisitDeclSubExpr(D);
653 /// VisitDeclSubExpr - Utility method to add block-level expressions for
654 /// initializers in Decls.
655 CFGBlock *CFGBuilder::VisitDeclSubExpr(Decl* D) {
658 VarDecl *VD = dyn_cast<VarDecl>(D);
663 Expr *Init = VD->getInit();
666 // Optimization: Don't create separate block-level statements for literals.
667 switch (Init->getStmtClass()) {
668 case Stmt::IntegerLiteralClass:
669 case Stmt::CharacterLiteralClass:
670 case Stmt::StringLiteralClass:
673 Block = addStmt(Init);
677 // If the type of VD is a VLA, then we must process its size expressions.
678 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
679 VA = FindVA(VA->getElementType().getTypePtr()))
680 Block = addStmt(VA->getSizeExpr());
685 CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
686 // We may see an if statement in the middle of a basic block, or it may be the
687 // first statement we are processing. In either case, we create a new basic
688 // block. First, we create the blocks for the then...else statements, and
689 // then we create the block containing the if statement. If we were in the
690 // middle of a block, we stop processing that block. That block is then the
691 // implicit successor for the "then" and "else" clauses.
693 // The block we were proccessing is now finished. Make it the successor
697 if (!FinishBlock(Block))
701 // Process the false branch.
702 CFGBlock* ElseBlock = Succ;
704 if (Stmt* Else = I->getElse()) {
705 SaveAndRestore<CFGBlock*> sv(Succ);
707 // NULL out Block so that the recursive call to Visit will
708 // create a new basic block.
710 ElseBlock = addStmt(Else);
712 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
713 ElseBlock = sv.get();
715 if (!FinishBlock(ElseBlock))
720 // Process the true branch.
723 Stmt* Then = I->getThen();
725 SaveAndRestore<CFGBlock*> sv(Succ);
727 ThenBlock = addStmt(Then);
730 // We can reach here if the "then" body has all NullStmts.
731 // Create an empty block so we can distinguish between true and false
732 // branches in path-sensitive analyses.
733 ThenBlock = createBlock(false);
734 AddSuccessor(ThenBlock, sv.get());
736 if (!FinishBlock(ThenBlock))
741 // Now create a new block containing the if statement.
742 Block = createBlock(false);
744 // Set the terminator of the new block to the If statement.
745 Block->setTerminator(I);
747 // See if this is a known constant.
748 const TryResult &KnownVal = TryEvaluateBool(I->getCond());
750 // Now add the successors.
751 AddSuccessor(Block, KnownVal.isFalse() ? NULL : ThenBlock);
752 AddSuccessor(Block, KnownVal.isTrue()? NULL : ElseBlock);
754 // Add the condition as the last statement in the new block. This may create
755 // new blocks as the condition may contain control-flow. Any newly created
756 // blocks will be pointed to be "Block".
757 return addStmt(I->getCond());
761 CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
762 // If we were in the middle of a block we stop processing that block.
764 // NOTE: If a "return" appears in the middle of a block, this means that the
765 // code afterwards is DEAD (unreachable). We still keep a basic block
766 // for that code; a simple "mark-and-sweep" from the entry block will be
767 // able to report such dead blocks.
771 // Create the new block.
772 Block = createBlock(false);
774 // The Exit block is the only successor.
775 AddSuccessor(Block, &cfg->getExit());
777 // Add the return statement to the block. This may create new blocks if R
778 // contains control-flow (short-circuit operations).
779 return VisitStmt(R, true);
782 CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
783 // Get the block of the labeled statement. Add it to our map.
784 addStmt(L->getSubStmt());
785 CFGBlock* LabelBlock = Block;
787 if (!LabelBlock) // This can happen when the body is empty, i.e.
788 LabelBlock = createBlock(); // scopes that only contains NullStmts.
790 assert(LabelMap.find(L) == LabelMap.end() && "label already in map");
791 LabelMap[ L ] = LabelBlock;
793 // Labels partition blocks, so this is the end of the basic block we were
794 // processing (L is the block's label). Because this is label (and we have
795 // already processed the substatement) there is no extra control-flow to worry
797 LabelBlock->setLabel(L);
798 if (!FinishBlock(LabelBlock))
801 // We set Block to NULL to allow lazy creation of a new block (if necessary);
804 // This block is now the implicit successor of other blocks.
810 CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
811 // Goto is a control-flow statement. Thus we stop processing the current
812 // block and create a new one.
816 Block = createBlock(false);
817 Block->setTerminator(G);
819 // If we already know the mapping to the label block add the successor now.
820 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
822 if (I == LabelMap.end())
823 // We will need to backpatch this block later.
824 BackpatchBlocks.push_back(Block);
826 AddSuccessor(Block, I->second);
831 CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
832 CFGBlock* LoopSuccessor = NULL;
834 // "for" is a control-flow statement. Thus we stop processing the current
837 if (!FinishBlock(Block))
839 LoopSuccessor = Block;
841 LoopSuccessor = Succ;
843 // Because of short-circuit evaluation, the condition of the loop can span
844 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
845 // evaluate the condition.
846 CFGBlock* ExitConditionBlock = createBlock(false);
847 CFGBlock* EntryConditionBlock = ExitConditionBlock;
849 // Set the terminator for the "exit" condition block.
850 ExitConditionBlock->setTerminator(F);
852 // Now add the actual condition to the condition block. Because the condition
853 // itself may contain control-flow, new blocks may be created.
854 if (Stmt* C = F->getCond()) {
855 Block = ExitConditionBlock;
856 EntryConditionBlock = addStmt(C);
858 if (!FinishBlock(EntryConditionBlock))
863 // The condition block is the implicit successor for the loop body as well as
864 // any code above the loop.
865 Succ = EntryConditionBlock;
867 // See if this is a known constant.
868 TryResult KnownVal(true);
871 KnownVal = TryEvaluateBool(F->getCond());
873 // Now create the loop body.
875 assert (F->getBody());
877 // Save the current values for Block, Succ, and continue and break targets
878 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
879 save_continue(ContinueTargetBlock),
880 save_break(BreakTargetBlock);
882 // Create a new block to contain the (bottom) of the loop body.
885 if (Stmt* I = F->getInc()) {
886 // Generate increment code in its own basic block. This is the target of
887 // continue statements.
890 // No increment code. Create a special, empty, block that is used as the
891 // target block for "looping back" to the start of the loop.
892 assert(Succ == EntryConditionBlock);
893 Succ = createBlock();
896 // Finish up the increment (or empty) block if it hasn't been already.
898 assert(Block == Succ);
899 if (!FinishBlock(Block))
904 ContinueTargetBlock = Succ;
906 // The starting block for the loop increment is the block that should
907 // represent the 'loop target' for looping back to the start of the loop.
908 ContinueTargetBlock->setLoopTarget(F);
910 // All breaks should go to the code following the loop.
911 BreakTargetBlock = LoopSuccessor;
913 // Now populate the body block, and in the process create new blocks as we
914 // walk the body of the loop.
915 CFGBlock* BodyBlock = addStmt(F->getBody());
918 BodyBlock = ContinueTargetBlock; // can happen for "for (...;...;...) ;"
919 else if (Block && !FinishBlock(BodyBlock))
922 // This new body block is a successor to our "exit" condition block.
923 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
926 // Link up the condition block with the code that follows the loop. (the
928 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
930 // If the loop contains initialization, create a new block for those
931 // statements. This block can also contain statements that precede the loop.
932 if (Stmt* I = F->getInit()) {
933 Block = createBlock();
936 // There is no loop initialization. We are thus basically a while loop.
937 // NULL out Block to force lazy block construction.
939 Succ = EntryConditionBlock;
940 return EntryConditionBlock;
944 CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
945 // Objective-C fast enumeration 'for' statements:
946 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
948 // for ( Type newVariable in collection_expression ) { statements }
953 // 1. collection_expression
954 // T. jump to loop_entry
956 // 1. side-effects of element expression
957 // 1. ObjCForCollectionStmt [performs binding to newVariable]
958 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
961 // T. jump to loop_entry
967 // Type existingItem;
968 // for ( existingItem in expression ) { statements }
972 // the same with newVariable replaced with existingItem; the binding works
973 // the same except that for one ObjCForCollectionStmt::getElement() returns
974 // a DeclStmt and the other returns a DeclRefExpr.
977 CFGBlock* LoopSuccessor = 0;
980 if (!FinishBlock(Block))
982 LoopSuccessor = Block;
985 LoopSuccessor = Succ;
987 // Build the condition blocks.
988 CFGBlock* ExitConditionBlock = createBlock(false);
989 CFGBlock* EntryConditionBlock = ExitConditionBlock;
991 // Set the terminator for the "exit" condition block.
992 ExitConditionBlock->setTerminator(S);
994 // The last statement in the block should be the ObjCForCollectionStmt, which
995 // performs the actual binding to 'element' and determines if there are any
996 // more items in the collection.
997 AppendStmt(ExitConditionBlock, S);
998 Block = ExitConditionBlock;
1000 // Walk the 'element' expression to see if there are any side-effects. We
1001 // generate new blocks as necesary. We DON'T add the statement by default to
1002 // the CFG unless it contains control-flow.
1003 EntryConditionBlock = Visit(S->getElement(), false);
1005 if (!FinishBlock(EntryConditionBlock))
1010 // The condition block is the implicit successor for the loop body as well as
1011 // any code above the loop.
1012 Succ = EntryConditionBlock;
1014 // Now create the true branch.
1016 // Save the current values for Succ, continue and break targets.
1017 SaveAndRestore<CFGBlock*> save_Succ(Succ),
1018 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
1020 BreakTargetBlock = LoopSuccessor;
1021 ContinueTargetBlock = EntryConditionBlock;
1023 CFGBlock* BodyBlock = addStmt(S->getBody());
1026 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
1028 if (!FinishBlock(BodyBlock))
1032 // This new body block is a successor to our "exit" condition block.
1033 AddSuccessor(ExitConditionBlock, BodyBlock);
1036 // Link up the condition block with the code that follows the loop.
1037 // (the false branch).
1038 AddSuccessor(ExitConditionBlock, LoopSuccessor);
1040 // Now create a prologue block to contain the collection expression.
1041 Block = createBlock();
1042 return addStmt(S->getCollection());
1045 CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
1046 // FIXME: Add locking 'primitives' to CFG for @synchronized.
1049 CFGBlock *SyncBlock = addStmt(S->getSynchBody());
1051 // The sync body starts its own basic block. This makes it a little easier
1052 // for diagnostic clients.
1054 if (!FinishBlock(SyncBlock))
1062 // Inline the sync expression.
1063 return addStmt(S->getSynchExpr());
1066 CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
1071 CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
1072 CFGBlock* LoopSuccessor = NULL;
1074 // "while" is a control-flow statement. Thus we stop processing the current
1077 if (!FinishBlock(Block))
1079 LoopSuccessor = Block;
1081 LoopSuccessor = Succ;
1083 // Because of short-circuit evaluation, the condition of the loop can span
1084 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1085 // evaluate the condition.
1086 CFGBlock* ExitConditionBlock = createBlock(false);
1087 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1089 // Set the terminator for the "exit" condition block.
1090 ExitConditionBlock->setTerminator(W);
1092 // Now add the actual condition to the condition block. Because the condition
1093 // itself may contain control-flow, new blocks may be created. Thus we update
1094 // "Succ" after adding the condition.
1095 if (Stmt* C = W->getCond()) {
1096 Block = ExitConditionBlock;
1097 EntryConditionBlock = addStmt(C);
1098 assert(Block == EntryConditionBlock);
1100 if (!FinishBlock(EntryConditionBlock))
1105 // The condition block is the implicit successor for the loop body as well as
1106 // any code above the loop.
1107 Succ = EntryConditionBlock;
1109 // See if this is a known constant.
1110 const TryResult& KnownVal = TryEvaluateBool(W->getCond());
1112 // Process the loop body.
1114 assert(W->getBody());
1116 // Save the current values for Block, Succ, and continue and break targets
1117 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1118 save_continue(ContinueTargetBlock),
1119 save_break(BreakTargetBlock);
1121 // Create an empty block to represent the transition block for looping back
1122 // to the head of the loop.
1124 assert(Succ == EntryConditionBlock);
1125 Succ = createBlock();
1126 Succ->setLoopTarget(W);
1127 ContinueTargetBlock = Succ;
1129 // All breaks should go to the code following the loop.
1130 BreakTargetBlock = LoopSuccessor;
1132 // NULL out Block to force lazy instantiation of blocks for the body.
1135 // Create the body. The returned block is the entry to the loop body.
1136 CFGBlock* BodyBlock = addStmt(W->getBody());
1139 BodyBlock = ContinueTargetBlock; // can happen for "while(...) ;"
1141 if (!FinishBlock(BodyBlock))
1145 // Add the loop body entry as a successor to the condition.
1146 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : BodyBlock);
1149 // Link up the condition block with the code that follows the loop. (the
1151 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1153 // There can be no more statements in the condition block since we loop back
1154 // to this block. NULL out Block to force lazy creation of another block.
1157 // Return the condition block, which is the dominating block for the loop.
1158 Succ = EntryConditionBlock;
1159 return EntryConditionBlock;
1163 CFGBlock *CFGBuilder::VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
1164 // FIXME: For now we pretend that @catch and the code it contains does not
1169 CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1170 // FIXME: This isn't complete. We basically treat @throw like a return
1173 // If we were in the middle of a block we stop processing that block.
1174 if (Block && !FinishBlock(Block))
1177 // Create the new block.
1178 Block = createBlock(false);
1180 // The Exit block is the only successor.
1181 AddSuccessor(Block, &cfg->getExit());
1183 // Add the statement to the block. This may create new blocks if S contains
1184 // control-flow (short-circuit operations).
1185 return VisitStmt(S, true);
1188 CFGBlock* CFGBuilder::VisitCXXThrowExpr(CXXThrowExpr* T) {
1189 // If we were in the middle of a block we stop processing that block.
1190 if (Block && !FinishBlock(Block))
1193 // Create the new block.
1194 Block = createBlock(false);
1196 // The Exit block is the only successor.
1197 AddSuccessor(Block, &cfg->getExit());
1199 // Add the statement to the block. This may create new blocks if S contains
1200 // control-flow (short-circuit operations).
1201 return VisitStmt(T, true);
1204 CFGBlock *CFGBuilder::VisitDoStmt(DoStmt* D) {
1205 CFGBlock* LoopSuccessor = NULL;
1207 // "do...while" is a control-flow statement. Thus we stop processing the
1210 if (!FinishBlock(Block))
1212 LoopSuccessor = Block;
1214 LoopSuccessor = Succ;
1216 // Because of short-circuit evaluation, the condition of the loop can span
1217 // multiple basic blocks. Thus we need the "Entry" and "Exit" blocks that
1218 // evaluate the condition.
1219 CFGBlock* ExitConditionBlock = createBlock(false);
1220 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1222 // Set the terminator for the "exit" condition block.
1223 ExitConditionBlock->setTerminator(D);
1225 // Now add the actual condition to the condition block. Because the condition
1226 // itself may contain control-flow, new blocks may be created.
1227 if (Stmt* C = D->getCond()) {
1228 Block = ExitConditionBlock;
1229 EntryConditionBlock = addStmt(C);
1231 if (!FinishBlock(EntryConditionBlock))
1236 // The condition block is the implicit successor for the loop body.
1237 Succ = EntryConditionBlock;
1239 // See if this is a known constant.
1240 const TryResult &KnownVal = TryEvaluateBool(D->getCond());
1242 // Process the loop body.
1243 CFGBlock* BodyBlock = NULL;
1245 assert (D->getBody());
1247 // Save the current values for Block, Succ, and continue and break targets
1248 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1249 save_continue(ContinueTargetBlock),
1250 save_break(BreakTargetBlock);
1252 // All continues within this loop should go to the condition block
1253 ContinueTargetBlock = EntryConditionBlock;
1255 // All breaks should go to the code following the loop.
1256 BreakTargetBlock = LoopSuccessor;
1258 // NULL out Block to force lazy instantiation of blocks for the body.
1261 // Create the body. The returned block is the entry to the loop body.
1262 BodyBlock = addStmt(D->getBody());
1265 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
1267 if (!FinishBlock(BodyBlock))
1271 // Add an intermediate block between the BodyBlock and the
1272 // ExitConditionBlock to represent the "loop back" transition. Create an
1273 // empty block to represent the transition block for looping back to the
1274 // head of the loop.
1275 // FIXME: Can we do this more efficiently without adding another block?
1278 CFGBlock *LoopBackBlock = createBlock();
1279 LoopBackBlock->setLoopTarget(D);
1281 // Add the loop body entry as a successor to the condition.
1282 AddSuccessor(ExitConditionBlock, KnownVal.isFalse() ? NULL : LoopBackBlock);
1285 // Link up the condition block with the code that follows the loop.
1286 // (the false branch).
1287 AddSuccessor(ExitConditionBlock, KnownVal.isTrue() ? NULL : LoopSuccessor);
1289 // There can be no more statements in the body block(s) since we loop back to
1290 // the body. NULL out Block to force lazy creation of another block.
1293 // Return the loop body, which is the dominating block for the loop.
1298 CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1299 // "continue" is a control-flow statement. Thus we stop processing the
1301 if (Block && !FinishBlock(Block))
1304 // Now create a new block that ends with the continue statement.
1305 Block = createBlock(false);
1306 Block->setTerminator(C);
1308 // If there is no target for the continue, then we are looking at an
1309 // incomplete AST. This means the CFG cannot be constructed.
1310 if (ContinueTargetBlock)
1311 AddSuccessor(Block, ContinueTargetBlock);
1318 CFGBlock *CFGBuilder::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E,
1323 AppendStmt(Block, E);
1326 // VLA types have expressions that must be evaluated.
1327 if (E->isArgumentType()) {
1328 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
1329 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
1330 addStmt(VA->getSizeExpr());
1336 /// VisitStmtExpr - Utility method to handle (nested) statement
1337 /// expressions (a GCC extension).
1338 CFGBlock* CFGBuilder::VisitStmtExpr(StmtExpr *SE, bool alwaysAdd) {
1341 AppendStmt(Block, SE);
1343 return VisitCompoundStmt(SE->getSubStmt());
1346 CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
1347 // "switch" is a control-flow statement. Thus we stop processing the current
1349 CFGBlock* SwitchSuccessor = NULL;
1352 if (!FinishBlock(Block))
1354 SwitchSuccessor = Block;
1355 } else SwitchSuccessor = Succ;
1357 // Save the current "switch" context.
1358 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
1359 save_break(BreakTargetBlock),
1360 save_default(DefaultCaseBlock);
1362 // Set the "default" case to be the block after the switch statement. If the
1363 // switch statement contains a "default:", this value will be overwritten with
1364 // the block for that code.
1365 DefaultCaseBlock = SwitchSuccessor;
1367 // Create a new block that will contain the switch statement.
1368 SwitchTerminatedBlock = createBlock(false);
1370 // Now process the switch body. The code after the switch is the implicit
1372 Succ = SwitchSuccessor;
1373 BreakTargetBlock = SwitchSuccessor;
1375 // When visiting the body, the case statements should automatically get linked
1376 // up to the switch. We also don't keep a pointer to the body, since all
1377 // control-flow from the switch goes to case/default statements.
1378 assert (Terminator->getBody() && "switch must contain a non-NULL body");
1380 CFGBlock *BodyBlock = addStmt(Terminator->getBody());
1382 if (!FinishBlock(BodyBlock))
1386 // If we have no "default:" case, the default transition is to the code
1387 // following the switch body.
1388 AddSuccessor(SwitchTerminatedBlock, DefaultCaseBlock);
1390 // Add the terminator and condition in the switch block.
1391 SwitchTerminatedBlock->setTerminator(Terminator);
1392 assert (Terminator->getCond() && "switch condition must be non-NULL");
1393 Block = SwitchTerminatedBlock;
1395 return addStmt(Terminator->getCond());
1398 CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* CS) {
1399 // CaseStmts are essentially labels, so they are the first statement in a
1402 if (CS->getSubStmt())
1403 addStmt(CS->getSubStmt());
1405 CFGBlock* CaseBlock = Block;
1407 CaseBlock = createBlock();
1409 // Cases statements partition blocks, so this is the top of the basic block we
1410 // were processing (the "case XXX:" is the label).
1411 CaseBlock->setLabel(CS);
1413 if (!FinishBlock(CaseBlock))
1416 // Add this block to the list of successors for the block with the switch
1418 assert(SwitchTerminatedBlock);
1419 AddSuccessor(SwitchTerminatedBlock, CaseBlock);
1421 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1424 // This block is now the implicit successor of other blocks.
1430 CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1431 if (Terminator->getSubStmt())
1432 addStmt(Terminator->getSubStmt());
1434 DefaultCaseBlock = Block;
1436 if (!DefaultCaseBlock)
1437 DefaultCaseBlock = createBlock();
1439 // Default statements partition blocks, so this is the top of the basic block
1440 // we were processing (the "default:" is the label).
1441 DefaultCaseBlock->setLabel(Terminator);
1443 if (!FinishBlock(DefaultCaseBlock))
1446 // Unlike case statements, we don't add the default block to the successors
1447 // for the switch statement immediately. This is done when we finish
1448 // processing the switch statement. This allows for the default case
1449 // (including a fall-through to the code after the switch statement) to always
1450 // be the last successor of a switch-terminated block.
1452 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1455 // This block is now the implicit successor of other blocks.
1456 Succ = DefaultCaseBlock;
1458 return DefaultCaseBlock;
1461 CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1462 // Lazily create the indirect-goto dispatch block if there isn't one already.
1463 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1466 IBlock = createBlock(false);
1467 cfg->setIndirectGotoBlock(IBlock);
1470 // IndirectGoto is a control-flow statement. Thus we stop processing the
1471 // current block and create a new one.
1472 if (Block && !FinishBlock(Block))
1475 Block = createBlock(false);
1476 Block->setTerminator(I);
1477 AddSuccessor(Block, IBlock);
1478 return addStmt(I->getTarget());
1481 } // end anonymous namespace
1483 /// createBlock - Constructs and adds a new CFGBlock to the CFG. The block has
1484 /// no successors or predecessors. If this is the first block created in the
1485 /// CFG, it is automatically set to be the Entry and Exit of the CFG.
1486 CFGBlock* CFG::createBlock() {
1487 bool first_block = begin() == end();
1489 // Create the block.
1490 CFGBlock *Mem = getAllocator().Allocate<CFGBlock>();
1491 new (Mem) CFGBlock(NumBlockIDs++, BlkBVC);
1492 Blocks.push_back(Mem, BlkBVC);
1494 // If this is the first block, set it as the Entry and Exit.
1496 Entry = Exit = &back();
1498 // Return the block.
1502 /// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1503 /// CFG is returned to the caller.
1504 CFG* CFG::buildCFG(Stmt* Statement, ASTContext *C) {
1506 return Builder.buildCFG(Statement, C);
1509 //===----------------------------------------------------------------------===//
1510 // CFG: Queries for BlkExprs.
1511 //===----------------------------------------------------------------------===//
1514 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
1517 static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1521 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
1524 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1525 if (B->isAssignmentOp()) Set.insert(B);
1527 FindSubExprAssignments(*I, Set);
1531 static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1532 BlkExprMapTy* M = new BlkExprMapTy();
1534 // Look for assignments that are used as subexpressions. These are the only
1535 // assignments that we want to *possibly* register as a block-level
1536 // expression. Basically, if an assignment occurs both in a subexpression and
1537 // at the block-level, it is a block-level expression.
1538 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1540 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1541 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1542 FindSubExprAssignments(*BI, SubExprAssignments);
1544 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1546 // Iterate over the statements again on identify the Expr* and Stmt* at the
1547 // block-level that are block-level expressions.
1549 for (CFGBlock::iterator BI=(*I)->begin(), EI=(*I)->end(); BI != EI; ++BI)
1550 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
1552 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
1553 // Assignment expressions that are not nested within another
1554 // expression are really "statements" whose value is never used by
1555 // another expression.
1556 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
1558 } else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
1559 // Special handling for statement expressions. The last statement in
1560 // the statement expression is also a block-level expr.
1561 const CompoundStmt* C = Terminator->getSubStmt();
1562 if (!C->body_empty()) {
1563 unsigned x = M->size();
1564 (*M)[C->body_back()] = x;
1568 unsigned x = M->size();
1572 // Look at terminators. The condition is a block-level expression.
1574 Stmt* S = (*I)->getTerminatorCondition();
1576 if (S && M->find(S) == M->end()) {
1577 unsigned x = M->size();
1585 CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1587 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1589 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1590 BlkExprMapTy::iterator I = M->find(S);
1592 if (I == M->end()) return CFG::BlkExprNumTy();
1593 else return CFG::BlkExprNumTy(I->second);
1596 unsigned CFG::getNumBlkExprs() {
1597 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1600 // We assume callers interested in the number of BlkExprs will want
1601 // the map constructed if it doesn't already exist.
1602 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1603 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1607 //===----------------------------------------------------------------------===//
1608 // Cleanup: CFG dstor.
1609 //===----------------------------------------------------------------------===//
1612 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1615 //===----------------------------------------------------------------------===//
1616 // CFG pretty printing
1617 //===----------------------------------------------------------------------===//
1621 class StmtPrinterHelper : public PrinterHelper {
1623 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1625 signed CurrentBlock;
1626 unsigned CurrentStmt;
1627 const LangOptions &LangOpts;
1630 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1631 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
1632 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1634 for (CFGBlock::const_iterator BI = (*I)->begin(), BEnd = (*I)->end() ;
1635 BI != BEnd; ++BI, ++j )
1636 StmtMap[*BI] = std::make_pair((*I)->getBlockID(),j);
1640 virtual ~StmtPrinterHelper() {}
1642 const LangOptions &getLangOpts() const { return LangOpts; }
1643 void setBlockID(signed i) { CurrentBlock = i; }
1644 void setStmtID(unsigned i) { CurrentStmt = i; }
1646 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
1648 StmtMapTy::iterator I = StmtMap.find(Terminator);
1650 if (I == StmtMap.end())
1653 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1654 && I->second.second == CurrentStmt)
1657 OS << "[B" << I->second.first << "." << I->second.second << "]";
1661 } // end anonymous namespace
1665 class CFGBlockTerminatorPrint
1666 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1668 llvm::raw_ostream& OS;
1669 StmtPrinterHelper* Helper;
1670 PrintingPolicy Policy;
1673 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
1674 const PrintingPolicy &Policy)
1675 : OS(os), Helper(helper), Policy(Policy) {}
1677 void VisitIfStmt(IfStmt* I) {
1679 I->getCond()->printPretty(OS,Helper,Policy);
1683 void VisitStmt(Stmt* Terminator) {
1684 Terminator->printPretty(OS, Helper, Policy);
1687 void VisitForStmt(ForStmt* F) {
1689 if (F->getInit()) OS << "...";
1691 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy);
1693 if (F->getInc()) OS << "...";
1697 void VisitWhileStmt(WhileStmt* W) {
1699 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy);
1702 void VisitDoStmt(DoStmt* D) {
1703 OS << "do ... while ";
1704 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy);
1707 void VisitSwitchStmt(SwitchStmt* Terminator) {
1709 Terminator->getCond()->printPretty(OS, Helper, Policy);
1712 void VisitConditionalOperator(ConditionalOperator* C) {
1713 C->getCond()->printPretty(OS, Helper, Policy);
1714 OS << " ? ... : ...";
1717 void VisitChooseExpr(ChooseExpr* C) {
1718 OS << "__builtin_choose_expr( ";
1719 C->getCond()->printPretty(OS, Helper, Policy);
1723 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1725 I->getTarget()->printPretty(OS, Helper, Policy);
1728 void VisitBinaryOperator(BinaryOperator* B) {
1729 if (!B->isLogicalOp()) {
1734 B->getLHS()->printPretty(OS, Helper, Policy);
1736 switch (B->getOpcode()) {
1737 case BinaryOperator::LOr:
1740 case BinaryOperator::LAnd:
1744 assert(false && "Invalid logical operator.");
1748 void VisitExpr(Expr* E) {
1749 E->printPretty(OS, Helper, Policy);
1752 } // end anonymous namespace
1755 static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
1758 // special printing for statement-expressions.
1759 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
1760 CompoundStmt* Sub = SE->getSubStmt();
1762 if (Sub->child_begin() != Sub->child_end()) {
1764 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
1770 // special printing for comma expressions.
1771 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
1772 if (B->getOpcode() == BinaryOperator::Comma) {
1774 Helper->handledStmt(B->getRHS(),OS);
1781 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
1783 // Expressions need a newline.
1784 if (isa<Expr>(Terminator)) OS << '\n';
1787 static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
1789 StmtPrinterHelper* Helper, bool print_edges) {
1791 if (Helper) Helper->setBlockID(B.getBlockID());
1793 // Print the header.
1794 OS << "\n [ B" << B.getBlockID();
1796 if (&B == &cfg->getEntry())
1797 OS << " (ENTRY) ]\n";
1798 else if (&B == &cfg->getExit())
1799 OS << " (EXIT) ]\n";
1800 else if (&B == cfg->getIndirectGotoBlock())
1801 OS << " (INDIRECT GOTO DISPATCH) ]\n";
1805 // Print the label of this block.
1806 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
1811 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
1813 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
1815 C->getLHS()->printPretty(OS, Helper,
1816 PrintingPolicy(Helper->getLangOpts()));
1819 C->getRHS()->printPretty(OS, Helper,
1820 PrintingPolicy(Helper->getLangOpts()));
1822 } else if (isa<DefaultStmt>(Terminator))
1825 assert(false && "Invalid label statement in CFGBlock.");
1830 // Iterate through the statements in the block and print them.
1833 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1834 I != E ; ++I, ++j ) {
1836 // Print the statement # in the basic block and the statement itself.
1840 OS << llvm::format("%3d", j) << ": ";
1843 Helper->setStmtID(j);
1845 print_stmt(OS,Helper,*I);
1848 // Print the terminator of this block.
1849 if (B.getTerminator()) {
1855 if (Helper) Helper->setBlockID(-1);
1857 CFGBlockTerminatorPrint TPrinter(OS, Helper,
1858 PrintingPolicy(Helper->getLangOpts()));
1859 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
1864 // Print the predecessors of this block.
1865 OS << " Predecessors (" << B.pred_size() << "):";
1868 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1871 if (i == 8 || (i-8) == 0)
1874 OS << " B" << (*I)->getBlockID();
1879 // Print the successors of this block.
1880 OS << " Successors (" << B.succ_size() << "):";
1883 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1886 if (i == 8 || (i-8) % 10 == 0)
1890 OS << " B" << (*I)->getBlockID();
1900 /// dump - A simple pretty printer of a CFG that outputs to stderr.
1901 void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
1903 /// print - A simple pretty printer of a CFG that outputs to an ostream.
1904 void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
1905 StmtPrinterHelper Helper(this, LO);
1907 // Print the entry block.
1908 print_block(OS, this, getEntry(), &Helper, true);
1910 // Iterate through the CFGBlocks and print them one by one.
1911 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1912 // Skip the entry block, because we already printed it.
1913 if (&(**I) == &getEntry() || &(**I) == &getExit())
1916 print_block(OS, this, **I, &Helper, true);
1919 // Print the exit block.
1920 print_block(OS, this, getExit(), &Helper, true);
1924 /// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1925 void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
1926 print(llvm::errs(), cfg, LO);
1929 /// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1930 /// Generally this will only be called from CFG::print.
1931 void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
1932 const LangOptions &LO) const {
1933 StmtPrinterHelper Helper(cfg, LO);
1934 print_block(OS, cfg, *this, &Helper, true);
1937 /// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1938 void CFGBlock::printTerminator(llvm::raw_ostream &OS,
1939 const LangOptions &LO) const {
1940 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
1941 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1944 Stmt* CFGBlock::getTerminatorCondition() {
1951 switch (Terminator->getStmtClass()) {
1955 case Stmt::ForStmtClass:
1956 E = cast<ForStmt>(Terminator)->getCond();
1959 case Stmt::WhileStmtClass:
1960 E = cast<WhileStmt>(Terminator)->getCond();
1963 case Stmt::DoStmtClass:
1964 E = cast<DoStmt>(Terminator)->getCond();
1967 case Stmt::IfStmtClass:
1968 E = cast<IfStmt>(Terminator)->getCond();
1971 case Stmt::ChooseExprClass:
1972 E = cast<ChooseExpr>(Terminator)->getCond();
1975 case Stmt::IndirectGotoStmtClass:
1976 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1979 case Stmt::SwitchStmtClass:
1980 E = cast<SwitchStmt>(Terminator)->getCond();
1983 case Stmt::ConditionalOperatorClass:
1984 E = cast<ConditionalOperator>(Terminator)->getCond();
1987 case Stmt::BinaryOperatorClass: // '&&' and '||'
1988 E = cast<BinaryOperator>(Terminator)->getLHS();
1991 case Stmt::ObjCForCollectionStmtClass:
1995 return E ? E->IgnoreParens() : NULL;
1998 bool CFGBlock::hasBinaryBranchTerminator() const {
2005 switch (Terminator->getStmtClass()) {
2009 case Stmt::ForStmtClass:
2010 case Stmt::WhileStmtClass:
2011 case Stmt::DoStmtClass:
2012 case Stmt::IfStmtClass:
2013 case Stmt::ChooseExprClass:
2014 case Stmt::ConditionalOperatorClass:
2015 case Stmt::BinaryOperatorClass:
2019 return E ? E->IgnoreParens() : NULL;
2023 //===----------------------------------------------------------------------===//
2024 // CFG Graphviz Visualization
2025 //===----------------------------------------------------------------------===//
2029 static StmtPrinterHelper* GraphHelper;
2032 void CFG::viewCFG(const LangOptions &LO) const {
2034 StmtPrinterHelper H(this, LO);
2036 llvm::ViewGraph(this,"CFG");
2043 struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
2045 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2047 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
2050 std::string OutSStr;
2051 llvm::raw_string_ostream Out(OutSStr);
2052 print_block(Out,Graph, *Node, GraphHelper, false);
2053 std::string& OutStr = Out.str();
2055 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
2057 // Process string output to make it nicer...
2058 for (unsigned i = 0; i != OutStr.length(); ++i)
2059 if (OutStr[i] == '\n') { // Left justify
2061 OutStr.insert(OutStr.begin()+i+1, 'l');
2070 } // end namespace llvm