LexicalScopes.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. //===- LexicalScopes.cpp - Collecting lexical scope info ------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements LexicalScopes analysis.
  10. //
  11. // This pass collects lexical scope information and maps machine instructions
  12. // to respective lexical scopes.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/LexicalScopes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/CodeGen/MachineBasicBlock.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineInstr.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/IR/DebugInfoMetadata.h"
  23. #include "llvm/IR/Metadata.h"
  24. #include "llvm/Support/Casting.h"
  25. #include "llvm/Support/Compiler.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <cassert>
  29. #include <string>
  30. #include <tuple>
  31. #include <utility>
  32. using namespace llvm;
  33. #define DEBUG_TYPE "lexicalscopes"
  34. /// reset - Reset the instance so that it's prepared for another function.
  35. void LexicalScopes::reset() {
  36. MF = nullptr;
  37. CurrentFnLexicalScope = nullptr;
  38. LexicalScopeMap.clear();
  39. AbstractScopeMap.clear();
  40. InlinedLexicalScopeMap.clear();
  41. AbstractScopesList.clear();
  42. }
  43. /// initialize - Scan machine function and constuct lexical scope nest.
  44. void LexicalScopes::initialize(const MachineFunction &Fn) {
  45. reset();
  46. // Don't attempt any lexical scope creation for a NoDebug compile unit.
  47. if (Fn.getFunction().getSubprogram()->getUnit()->getEmissionKind() ==
  48. DICompileUnit::NoDebug)
  49. return;
  50. MF = &Fn;
  51. SmallVector<InsnRange, 4> MIRanges;
  52. DenseMap<const MachineInstr *, LexicalScope *> MI2ScopeMap;
  53. extractLexicalScopes(MIRanges, MI2ScopeMap);
  54. if (CurrentFnLexicalScope) {
  55. constructScopeNest(CurrentFnLexicalScope);
  56. assignInstructionRanges(MIRanges, MI2ScopeMap);
  57. }
  58. }
  59. /// extractLexicalScopes - Extract instruction ranges for each lexical scopes
  60. /// for the given machine function.
  61. void LexicalScopes::extractLexicalScopes(
  62. SmallVectorImpl<InsnRange> &MIRanges,
  63. DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
  64. // Scan each instruction and create scopes. First build working set of scopes.
  65. for (const auto &MBB : *MF) {
  66. const MachineInstr *RangeBeginMI = nullptr;
  67. const MachineInstr *PrevMI = nullptr;
  68. const DILocation *PrevDL = nullptr;
  69. for (const auto &MInsn : MBB) {
  70. // Check if instruction has valid location information.
  71. const DILocation *MIDL = MInsn.getDebugLoc();
  72. if (!MIDL) {
  73. PrevMI = &MInsn;
  74. continue;
  75. }
  76. // If scope has not changed then skip this instruction.
  77. if (MIDL == PrevDL) {
  78. PrevMI = &MInsn;
  79. continue;
  80. }
  81. // Ignore DBG_VALUE and similar instruction that do not contribute to any
  82. // instruction in the output.
  83. if (MInsn.isMetaInstruction())
  84. continue;
  85. if (RangeBeginMI) {
  86. // If we have already seen a beginning of an instruction range and
  87. // current instruction scope does not match scope of first instruction
  88. // in this range then create a new instruction range.
  89. InsnRange R(RangeBeginMI, PrevMI);
  90. MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
  91. MIRanges.push_back(R);
  92. }
  93. // This is a beginning of a new instruction range.
  94. RangeBeginMI = &MInsn;
  95. // Reset previous markers.
  96. PrevMI = &MInsn;
  97. PrevDL = MIDL;
  98. }
  99. // Create last instruction range.
  100. if (RangeBeginMI && PrevMI && PrevDL) {
  101. InsnRange R(RangeBeginMI, PrevMI);
  102. MIRanges.push_back(R);
  103. MI2ScopeMap[RangeBeginMI] = getOrCreateLexicalScope(PrevDL);
  104. }
  105. }
  106. }
  107. /// findLexicalScope - Find lexical scope, either regular or inlined, for the
  108. /// given DebugLoc. Return NULL if not found.
  109. LexicalScope *LexicalScopes::findLexicalScope(const DILocation *DL) {
  110. DILocalScope *Scope = DL->getScope();
  111. if (!Scope)
  112. return nullptr;
  113. // The scope that we were created with could have an extra file - which
  114. // isn't what we care about in this case.
  115. Scope = Scope->getNonLexicalBlockFileScope();
  116. if (auto *IA = DL->getInlinedAt()) {
  117. auto I = InlinedLexicalScopeMap.find(std::make_pair(Scope, IA));
  118. return I != InlinedLexicalScopeMap.end() ? &I->second : nullptr;
  119. }
  120. return findLexicalScope(Scope);
  121. }
  122. /// getOrCreateLexicalScope - Find lexical scope for the given DebugLoc. If
  123. /// not available then create new lexical scope.
  124. LexicalScope *LexicalScopes::getOrCreateLexicalScope(const DILocalScope *Scope,
  125. const DILocation *IA) {
  126. if (IA) {
  127. // Skip scopes inlined from a NoDebug compile unit.
  128. if (Scope->getSubprogram()->getUnit()->getEmissionKind() ==
  129. DICompileUnit::NoDebug)
  130. return getOrCreateLexicalScope(IA);
  131. // Create an abstract scope for inlined function.
  132. getOrCreateAbstractScope(Scope);
  133. // Create an inlined scope for inlined function.
  134. return getOrCreateInlinedScope(Scope, IA);
  135. }
  136. return getOrCreateRegularScope(Scope);
  137. }
  138. /// getOrCreateRegularScope - Find or create a regular lexical scope.
  139. LexicalScope *
  140. LexicalScopes::getOrCreateRegularScope(const DILocalScope *Scope) {
  141. assert(Scope && "Invalid Scope encoding!");
  142. Scope = Scope->getNonLexicalBlockFileScope();
  143. auto I = LexicalScopeMap.find(Scope);
  144. if (I != LexicalScopeMap.end())
  145. return &I->second;
  146. // FIXME: Should the following dyn_cast be DILexicalBlock?
  147. LexicalScope *Parent = nullptr;
  148. if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
  149. Parent = getOrCreateLexicalScope(Block->getScope());
  150. I = LexicalScopeMap.emplace(std::piecewise_construct,
  151. std::forward_as_tuple(Scope),
  152. std::forward_as_tuple(Parent, Scope, nullptr,
  153. false)).first;
  154. if (!Parent) {
  155. assert(cast<DISubprogram>(Scope)->describes(&MF->getFunction()));
  156. assert(!CurrentFnLexicalScope);
  157. CurrentFnLexicalScope = &I->second;
  158. }
  159. return &I->second;
  160. }
  161. /// getOrCreateInlinedScope - Find or create an inlined lexical scope.
  162. LexicalScope *
  163. LexicalScopes::getOrCreateInlinedScope(const DILocalScope *Scope,
  164. const DILocation *InlinedAt) {
  165. assert(Scope && "Invalid Scope encoding!");
  166. Scope = Scope->getNonLexicalBlockFileScope();
  167. std::pair<const DILocalScope *, const DILocation *> P(Scope, InlinedAt);
  168. auto I = InlinedLexicalScopeMap.find(P);
  169. if (I != InlinedLexicalScopeMap.end())
  170. return &I->second;
  171. LexicalScope *Parent;
  172. if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
  173. Parent = getOrCreateInlinedScope(Block->getScope(), InlinedAt);
  174. else
  175. Parent = getOrCreateLexicalScope(InlinedAt);
  176. I = InlinedLexicalScopeMap
  177. .emplace(std::piecewise_construct, std::forward_as_tuple(P),
  178. std::forward_as_tuple(Parent, Scope, InlinedAt, false))
  179. .first;
  180. return &I->second;
  181. }
  182. /// getOrCreateAbstractScope - Find or create an abstract lexical scope.
  183. LexicalScope *
  184. LexicalScopes::getOrCreateAbstractScope(const DILocalScope *Scope) {
  185. assert(Scope && "Invalid Scope encoding!");
  186. Scope = Scope->getNonLexicalBlockFileScope();
  187. auto I = AbstractScopeMap.find(Scope);
  188. if (I != AbstractScopeMap.end())
  189. return &I->second;
  190. // FIXME: Should the following isa be DILexicalBlock?
  191. LexicalScope *Parent = nullptr;
  192. if (auto *Block = dyn_cast<DILexicalBlockBase>(Scope))
  193. Parent = getOrCreateAbstractScope(Block->getScope());
  194. I = AbstractScopeMap.emplace(std::piecewise_construct,
  195. std::forward_as_tuple(Scope),
  196. std::forward_as_tuple(Parent, Scope,
  197. nullptr, true)).first;
  198. if (isa<DISubprogram>(Scope))
  199. AbstractScopesList.push_back(&I->second);
  200. return &I->second;
  201. }
  202. /// constructScopeNest
  203. void LexicalScopes::constructScopeNest(LexicalScope *Scope) {
  204. assert(Scope && "Unable to calculate scope dominance graph!");
  205. SmallVector<LexicalScope *, 4> WorkStack;
  206. WorkStack.push_back(Scope);
  207. unsigned Counter = 0;
  208. while (!WorkStack.empty()) {
  209. LexicalScope *WS = WorkStack.back();
  210. const SmallVectorImpl<LexicalScope *> &Children = WS->getChildren();
  211. bool visitedChildren = false;
  212. for (auto &ChildScope : Children)
  213. if (!ChildScope->getDFSOut()) {
  214. WorkStack.push_back(ChildScope);
  215. visitedChildren = true;
  216. ChildScope->setDFSIn(++Counter);
  217. break;
  218. }
  219. if (!visitedChildren) {
  220. WorkStack.pop_back();
  221. WS->setDFSOut(++Counter);
  222. }
  223. }
  224. }
  225. /// assignInstructionRanges - Find ranges of instructions covered by each
  226. /// lexical scope.
  227. void LexicalScopes::assignInstructionRanges(
  228. SmallVectorImpl<InsnRange> &MIRanges,
  229. DenseMap<const MachineInstr *, LexicalScope *> &MI2ScopeMap) {
  230. LexicalScope *PrevLexicalScope = nullptr;
  231. for (const auto &R : MIRanges) {
  232. LexicalScope *S = MI2ScopeMap.lookup(R.first);
  233. assert(S && "Lost LexicalScope for a machine instruction!");
  234. if (PrevLexicalScope && !PrevLexicalScope->dominates(S))
  235. PrevLexicalScope->closeInsnRange(S);
  236. S->openInsnRange(R.first);
  237. S->extendInsnRange(R.second);
  238. PrevLexicalScope = S;
  239. }
  240. if (PrevLexicalScope)
  241. PrevLexicalScope->closeInsnRange();
  242. }
  243. /// getMachineBasicBlocks - Populate given set using machine basic blocks which
  244. /// have machine instructions that belong to lexical scope identified by
  245. /// DebugLoc.
  246. void LexicalScopes::getMachineBasicBlocks(
  247. const DILocation *DL, SmallPtrSetImpl<const MachineBasicBlock *> &MBBs) {
  248. assert(MF && "Method called on a uninitialized LexicalScopes object!");
  249. MBBs.clear();
  250. LexicalScope *Scope = getOrCreateLexicalScope(DL);
  251. if (!Scope)
  252. return;
  253. if (Scope == CurrentFnLexicalScope) {
  254. for (const auto &MBB : *MF)
  255. MBBs.insert(&MBB);
  256. return;
  257. }
  258. SmallVectorImpl<InsnRange> &InsnRanges = Scope->getRanges();
  259. for (auto &R : InsnRanges)
  260. MBBs.insert(R.first->getParent());
  261. }
  262. /// dominates - Return true if DebugLoc's lexical scope dominates at least one
  263. /// machine instruction's lexical scope in a given machine basic block.
  264. bool LexicalScopes::dominates(const DILocation *DL, MachineBasicBlock *MBB) {
  265. assert(MF && "Unexpected uninitialized LexicalScopes object!");
  266. LexicalScope *Scope = getOrCreateLexicalScope(DL);
  267. if (!Scope)
  268. return false;
  269. // Current function scope covers all basic blocks in the function.
  270. if (Scope == CurrentFnLexicalScope && MBB->getParent() == MF)
  271. return true;
  272. bool Result = false;
  273. for (auto &I : *MBB) {
  274. if (const DILocation *IDL = I.getDebugLoc())
  275. if (LexicalScope *IScope = getOrCreateLexicalScope(IDL))
  276. if (Scope->dominates(IScope))
  277. return true;
  278. }
  279. return Result;
  280. }
  281. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  282. LLVM_DUMP_METHOD void LexicalScope::dump(unsigned Indent) const {
  283. raw_ostream &err = dbgs();
  284. err.indent(Indent);
  285. err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
  286. const MDNode *N = Desc;
  287. err.indent(Indent);
  288. N->dump();
  289. if (AbstractScope)
  290. err << std::string(Indent, ' ') << "Abstract Scope\n";
  291. if (!Children.empty())
  292. err << std::string(Indent + 2, ' ') << "Children ...\n";
  293. for (unsigned i = 0, e = Children.size(); i != e; ++i)
  294. if (Children[i] != this)
  295. Children[i]->dump(Indent + 2);
  296. }
  297. #endif