blob: 965eca1b3c9017b323d6b1c6a632e9e229e472ed [file] [log] [blame]
Ted Kremeneka6d69302010-08-04 18:23:15 +00001//===--- CFGStmtMap.h - Map from Stmt* to CFGBlock* -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFGStmtMap class, which defines a mapping from
11// Stmt* to CFGBlock*
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/DenseMap.h"
16#include "clang/AST/ParentMap.h"
17#include "clang/Analysis/CFG.h"
18#include "clang/Analysis/CFGStmtMap.h"
19
20using namespace clang;
21
22typedef llvm::DenseMap<Stmt*,CFGBlock*> SMap;
23static SMap *AsMap(void *m) { return (SMap*) m; }
24
25CFGStmtMap::~CFGStmtMap() { delete AsMap(M); }
26
27CFGBlock *CFGStmtMap::getBlock(Stmt *S) {
28 SMap *SM = AsMap(M);
29 Stmt *X = S;
30
31 // If 'S' isn't in the map, walk the ParentMap to see if one of its ancestors
32 // is in the map.
33 while (X) {
Tom Careb5049d82010-08-11 23:36:58 +000034 SMap::iterator I = SM->find(X);
Ted Kremeneka6d69302010-08-04 18:23:15 +000035 if (I != SM->end()) {
36 CFGBlock *B = I->second;
37 // Memoize this lookup.
38 if (X != S)
39 (*SM)[X] = B;
40 return B;
41 }
42
Ted Kremenekeea0d932010-08-05 00:03:46 +000043 X = PM->getParentIgnoreParens(X);
Ted Kremeneka6d69302010-08-04 18:23:15 +000044 }
45
46 return 0;
47}
48
49static void Accumulate(SMap &SM, CFGBlock *B) {
50 // First walk the block-level expressions.
51 for (CFGBlock::iterator I = B->begin(), E = B->end(); I != E; ++I) {
52 const CFGElement &CE = *I;
53 if (Stmt *S = CE.getStmt()) {
54 CFGBlock *&Entry = SM[S];
55 // If 'Entry' is already initialized (e.g., a terminator was already),
56 // skip.
57 if (Entry)
58 continue;
59
60 Entry = B;
61 }
62 }
63
64 // Look at the label of the block.
65 if (Stmt *Label = B->getLabel())
66 SM[Label] = B;
67
68 // Finally, look at the terminator. If the terminator was already added
69 // because it is a block-level expression in another block, overwrite
70 // that mapping.
71 if (Stmt *Term = B->getTerminator())
72 SM[Term] = B;
73}
74
75CFGStmtMap *CFGStmtMap::Build(CFG *C, ParentMap *PM) {
76 if (!C || !PM)
77 return 0;
78
79 SMap *SM = new SMap();
80
81 // Walk all blocks, accumulating the block-level expressions, labels,
82 // and terminators.
83 for (CFG::iterator I = C->begin(), E = C->end(); I != E; ++I)
84 Accumulate(*SM, *I);
85
86 return new CFGStmtMap(PM, SM);
87}
88