1 //===- LexicalScopes.cpp - Collecting lexical scope info ------------------===//
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 implements LexicalScopes analysis.
12 // This pass collects lexical scope information and maps machine instructions
13 // to respective lexical scopes.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/CodeGen/LexicalScopes.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/IR/DebugInfoMetadata.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
36 #define DEBUG_TYPE "lexicalscopes"
38 /// reset - Reset the instance so that it's prepared for another function.
39 void LexicalScopes::reset() {
41 CurrentFnLexicalScope = nullptr;
42 LexicalScopeMap.clear();
43 AbstractScopeMap.clear();
44 InlinedLexicalScopeMap.clear();
45 AbstractScopesList.clear();
48 /// initialize - Scan machine function and constuct lexical scope nest.
49 void LexicalScopes::initialize(const MachineFunction &Fn) {
50 // Don't attempt any lexical scope creation for a NoDebug compile unit.
51 if (Fn.getFunction()->getSubprogram()->getUnit()->getEmissionKind() ==
52 DICompileUnit::NoDebug)
56 SmallVector<InsnRange, 4> MIRanges;
57 DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;
58 extractLexicalScopes(MIRanges, MI2ScopeMap);
59 if (CurrentFnLexicalScope) {
60 constructScopeNest(CurrentFnLexicalScope);
61 assignInstructionRanges(MIRanges, MI2ScopeMap);
65 /// extractLexicalScopes - Extract instruction ranges for each lexical scopes
66 /// for the given machine function.
67 void LexicalScopes::extractLexicalScopes(
68 SmallVectorImpl<InsnRange> &MIRanges,
69 DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
70 // Scan each instruction and create scopes. First build working set of scopes.
71 for (const auto &MBB : *MF) {
72 const MachineInstr *RangeBeginMI = nullptr;
73 const MachineInstr *PrevMI = nullptr;
74 const DILocation *PrevDL = nullptr;
75 for (const auto &MInsn : MBB) {
76 // Check if instruction has valid location information.
77 const DILocation *MIDL = MInsn.getDebugLoc();
83 // If scope has not changed then skip this instruction.
89 // Ignore DBG_VALUE. It does not contribute to any instruction in output.
90 if (MInsn.isDebugValue())
94 // If we have already seen a beginning of an instruction range and
95 // current instruction scope does not match scope of first instruction
96 // in this range then create a new instruction range.
97 InsnRange R(RangeBeginMI, PrevMI);
98 MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
99 MIRanges.push_back(R);
102 // This is a beginning of a new instruction range.
103 RangeBeginMI = &MInsn;
105 // Reset previous markers.
110 // Create last instruction range.
111 if (RangeBeginMI && PrevMI && PrevDL) {
112 InsnRange R(RangeBeginMI, PrevMI);
113 MIRanges.push_back(R);
114 MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
119 /// findLexicalScope - Find lexical scope, either regular or inlined, for the
120 /// given DebugLoc. Return NULL if not found.
121 LexicalScope *LexicalScopes::findLexicalScope(const DILocation *DL) {
122 DILocalScope *Scope = DL->getScope();
126 // The scope that we were created with could have an extra file - which
127 // isn't what we care about in this case.
128 Scope = Scope->getNonLexicalBlockFileScope();
130 if (auto *IA = DL->getInlinedAt()) {
131 auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
132 return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
134 return findLexicalScope(Scope);
137 /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
138 /// not available then create new lexical scope.
139 LexicalScope *LexicalScopes::getOrCreateLexicalScope(const DILocalScope *Scope,
140 const DILocation *IA) {
142 // Skip scopes inlined from a NoDebug compile unit.
143 if (Scope->getSubprogram()->getUnit()->getEmissionKind() ==
144 DICompileUnit::NoDebug)
145 return getOrCreateLexicalScope(IA);
146 // Create an abstract scope for inlined function.
147 getOrCreateAbstractScope(Scope);
148 // Create an inlined scope for inlined function.
149 return getOrCreateInlinedScope(Scope, IA);
152 return getOrCreateRegularScope(Scope);
155 /// getOrCreateRegularScope - Find or create a regular lexical scope.
157 LexicalScopes::getOrCreateRegularScope(const DILocalScope *Scope) {
158 assert(Scope && "Invalid Scope encoding!");
159 Scope = Scope->getNonLexicalBlockFileScope();
161 auto I = LexicalScopeMap.find(Scope);
162 if (I != LexicalScopeMap.end())
165 // FIXME: Should the following dyn_cast be DILexicalBlock?
166 LexicalScope *Parent = nullptr;
167 if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
168 Parent = getOrCreateLexicalScope(Block->getScope());
169 I = LexicalScopeMap.emplace(std::piecewise_construct,
170 std::forward_as_tuple(Scope),
171 std::forward_as_tuple(Parent, Scope, nullptr,
175 assert(cast<DISubprogram>(Scope)->describes(MF->getFunction()));
176 assert(!CurrentFnLexicalScope);
177 CurrentFnLexicalScope = &I->second;
183 /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
185 LexicalScopes::getOrCreateInlinedScope(const DILocalScope *Scope,
186 const DILocation *InlinedAt) {
187 assert(Scope && "Invalid Scope encoding!");
188 Scope = Scope->getNonLexicalBlockFileScope();
189 std::pair<const DILocalScope *, const DILocation *> P(Scope, InlinedAt);
190 auto I = InlinedLexicalScopeMap.find(P);
191 if (I != InlinedLexicalScopeMap.end())
194 LexicalScope *Parent;
195 if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
196 Parent = getOrCreateInlinedScope(Block->getScope(), InlinedAt);
198 Parent = getOrCreateLexicalScope(InlinedAt);
200 I = InlinedLexicalScopeMap
201 .emplace(std::piecewise_construct, std::forward_as_tuple(P),
202 std::forward_as_tuple(Parent, Scope, InlinedAt, false))
207 /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
209 LexicalScopes::getOrCreateAbstractScope(const DILocalScope *Scope) {
210 assert(Scope && "Invalid Scope encoding!");
211 Scope = Scope->getNonLexicalBlockFileScope();
212 auto I = AbstractScopeMap.find(Scope);
213 if (I != AbstractScopeMap.end())
216 // FIXME: Should the following isa be DILexicalBlock?
217 LexicalScope *Parent = nullptr;
218 if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
219 Parent = getOrCreateAbstractScope(Block->getScope());
221 I = AbstractScopeMap.emplace(std::piecewise_construct,
222 std::forward_as_tuple(Scope),
223 std::forward_as_tuple(Parent, Scope,
224 nullptr, true)).first;
225 if (isa<DISubprogram>(Scope))
226 AbstractScopesList.push_back(&I->second);
230 /// constructScopeNest
231 void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
232 assert(Scope && "Unable to calculate scope dominance graph!");
233 SmallVector<LexicalScope *, 4> WorkStack;
234 WorkStack.push_back(Scope);
235 unsigned Counter = 0;
236 while (!WorkStack.empty()) {
237 LexicalScope *WS = WorkStack.back();
238 const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
239 bool visitedChildren = false;
240 for (auto &ChildScope : Children)
241 if (!ChildScope->getDFSOut()) {
242 WorkStack.push_back(ChildScope);
243 visitedChildren = true;
244 ChildScope->setDFSIn(++Counter);
247 if (!visitedChildren) {
248 WorkStack.pop_back();
249 WS->setDFSOut(++Counter);
254 /// assignInstructionRanges - Find ranges of instructions covered by each
256 void LexicalScopes::assignInstructionRanges(
257 SmallVectorImpl<InsnRange> &MIRanges,
258 DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
259 LexicalScope *PrevLexicalScope = nullptr;
260 for (const auto &R : MIRanges) {
261 LexicalScope *S = MI2ScopeMap.lookup(R.first);
262 assert(S && "Lost LexicalScope for a machine instruction!");
263 if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
264 PrevLexicalScope->closeInsnRange(S);
265 S->openInsnRange(R.first);
266 S->extendInsnRange(R.second);
267 PrevLexicalScope = S;
270 if (PrevLexicalScope)
271 PrevLexicalScope->closeInsnRange();
274 /// getMachineBasicBlocks - Populate given set using machine basic blocks which
275 /// have machine instructions that belong to lexical scope identified by
277 void LexicalScopes::getMachineBasicBlocks(
278 const DILocation *DL, SmallPtrSetImpl<const MachineBasicBlock *> &MBBs) {
280 LexicalScope *Scope = getOrCreateLexicalScope(DL);
284 if (Scope == CurrentFnLexicalScope) {
285 for (const auto &MBB : *MF)
290 SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
291 for (auto &R : InsnRanges)
292 MBBs.insert(R.first->getParent());
295 /// dominates - Return true if DebugLoc's lexical scope dominates at least one
296 /// machine instruction's lexical scope in a given machine basic block.
297 bool LexicalScopes::dominates(const DILocation *DL, MachineBasicBlock *MBB) {
298 LexicalScope *Scope = getOrCreateLexicalScope(DL);
302 // Current function scope covers all basic blocks in the function.
303 if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
307 for (auto &I : *MBB) {
308 if (const DILocation *IDL = I.getDebugLoc())
309 if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))
310 if (Scope->dominates(IScope))
316 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
317 LLVM_DUMP_METHOD void LexicalScope::dump(unsigned Indent) const {
318 raw_ostream &err = dbgs();
320 err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
321 const MDNode *N = Desc;
325 err << std::string(Indent, ' ') << "Abstract Scope\n";
327 if (!Children.empty())
328 err << std::string(Indent + 2, ' ') << "Children ...\n";
329 for (unsigned i = 0, e = Children.size(); i != e; ++i)
330 if (Children[i] != this)
331 Children[i]->dump(Indent + 2);