/ICSharpCode.Decompiler/FlowAnalysis/ControlStructureDetector.cs

http://github.com/icsharpcode/ILSpy · C# · 241 lines · 153 code · 20 blank · 68 comment · 30 complexity · d4b7e26b4f2127d3e9fc428f9788354b MD5 · raw file

  1. // Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4. // software and associated documentation files (the "Software"), to deal in the Software
  5. // without restriction, including without limitation the rights to use, copy, modify, merge,
  6. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7. // to whom the Software is furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in all copies or
  10. // substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  14. // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  15. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. // DEALINGS IN THE SOFTWARE.
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Diagnostics;
  21. using System.Linq;
  22. using System.Threading;
  23. using Mono.Cecil.Cil;
  24. namespace ICSharpCode.Decompiler.FlowAnalysis
  25. {
  26. /// <summary>
  27. /// Detects the structure of the control flow (exception blocks and loops).
  28. /// </summary>
  29. public class ControlStructureDetector
  30. {
  31. public static ControlStructure DetectStructure(ControlFlowGraph g, IEnumerable<ExceptionHandler> exceptionHandlers, CancellationToken cancellationToken)
  32. {
  33. ControlStructure root = new ControlStructure(new HashSet<ControlFlowNode>(g.Nodes), g.EntryPoint, ControlStructureType.Root);
  34. // First build a structure tree out of the exception table
  35. DetectExceptionHandling(root, g, exceptionHandlers);
  36. // Then run the loop detection.
  37. DetectLoops(g, root, cancellationToken);
  38. return root;
  39. }
  40. #region Exception Handling
  41. static void DetectExceptionHandling(ControlStructure current, ControlFlowGraph g, IEnumerable<ExceptionHandler> exceptionHandlers)
  42. {
  43. // We rely on the fact that the exception handlers are sorted so that the innermost come first.
  44. // For each exception handler, we determine the nodes and substructures inside that handler, and move them into a new substructure.
  45. // This is always possible because exception handlers are guaranteed (by the CLR spec) to be properly nested and non-overlapping;
  46. // so they directly form the tree that we need.
  47. foreach (ExceptionHandler eh in exceptionHandlers) {
  48. var tryNodes = FindNodes(current, eh.TryStart, eh.TryEnd);
  49. current.Nodes.ExceptWith(tryNodes);
  50. ControlStructure tryBlock = new ControlStructure(
  51. tryNodes,
  52. g.Nodes.Single(n => n.Start == eh.TryStart),
  53. ControlStructureType.Try);
  54. tryBlock.ExceptionHandler = eh;
  55. MoveControlStructures(current, tryBlock, eh.TryStart, eh.TryEnd);
  56. current.Children.Add(tryBlock);
  57. if (eh.FilterStart != null) {
  58. throw new NotSupportedException();
  59. }
  60. var handlerNodes = FindNodes(current, eh.HandlerStart, eh.HandlerEnd);
  61. var handlerNode = current.Nodes.Single(n => n.ExceptionHandler == eh);
  62. handlerNodes.Add(handlerNode);
  63. if (handlerNode.EndFinallyOrFaultNode != null)
  64. handlerNodes.Add(handlerNode.EndFinallyOrFaultNode);
  65. current.Nodes.ExceptWith(handlerNodes);
  66. ControlStructure handlerBlock = new ControlStructure(
  67. handlerNodes, handlerNode, ControlStructureType.Handler);
  68. handlerBlock.ExceptionHandler = eh;
  69. MoveControlStructures(current, handlerBlock, eh.HandlerStart, eh.HandlerEnd);
  70. current.Children.Add(handlerBlock);
  71. }
  72. }
  73. /// <summary>
  74. /// Removes all nodes from start to end (exclusive) from this ControlStructure and moves them to the target structure.
  75. /// </summary>
  76. static HashSet<ControlFlowNode> FindNodes(ControlStructure current, Instruction startInst, Instruction endInst)
  77. {
  78. HashSet<ControlFlowNode> result = new HashSet<ControlFlowNode>();
  79. int start = startInst.Offset;
  80. int end = endInst.Offset;
  81. foreach (var node in current.Nodes.ToArray()) {
  82. if (node.Start != null && start <= node.Start.Offset && node.Start.Offset < end) {
  83. result.Add(node);
  84. }
  85. }
  86. return result;
  87. }
  88. static void MoveControlStructures(ControlStructure current, ControlStructure target, Instruction startInst, Instruction endInst)
  89. {
  90. for (int i = 0; i < current.Children.Count; i++) {
  91. var child = current.Children[i];
  92. if (startInst.Offset <= child.EntryPoint.Offset && child.EntryPoint.Offset < endInst.Offset) {
  93. current.Children.RemoveAt(i--);
  94. target.Children.Add(child);
  95. target.AllNodes.UnionWith(child.AllNodes);
  96. }
  97. }
  98. }
  99. #endregion
  100. #region Loop Detection
  101. // Loop detection works like this:
  102. // We find a top-level loop by looking for its entry point, which is characterized by a node dominating its own predecessor.
  103. // Then we determine all other nodes that belong to such a loop (all nodes which lead to the entry point, and are dominated by it).
  104. // Finally, we check whether our result conforms with potential existing exception structures, and create the substructure for the loop if successful.
  105. // This algorithm is applied recursively for any substructures (both detected loops and exception blocks)
  106. // But maybe we should get rid of this complex stuff and instead treat every backward jump as a loop?
  107. // That should still work with the IL produced by compilers, and has the advantage that the detected loop bodies are consecutive IL regions.
  108. static void DetectLoops(ControlFlowGraph g, ControlStructure current, CancellationToken cancellationToken)
  109. {
  110. if (!current.EntryPoint.IsReachable)
  111. return;
  112. g.ResetVisited();
  113. cancellationToken.ThrowIfCancellationRequested();
  114. FindLoops(current, current.EntryPoint);
  115. foreach (ControlStructure loop in current.Children)
  116. DetectLoops(g, loop, cancellationToken);
  117. }
  118. static void FindLoops(ControlStructure current, ControlFlowNode node)
  119. {
  120. if (node.Visited)
  121. return;
  122. node.Visited = true;
  123. if (current.Nodes.Contains(node)
  124. && node.DominanceFrontier.Contains(node)
  125. && !(node == current.EntryPoint && current.Type == ControlStructureType.Loop))
  126. {
  127. HashSet<ControlFlowNode> loopContents = new HashSet<ControlFlowNode>();
  128. FindLoopContents(current, loopContents, node, node);
  129. List<ControlStructure> containedChildStructures = new List<ControlStructure>();
  130. bool invalidNesting = false;
  131. foreach (ControlStructure childStructure in current.Children) {
  132. if (childStructure.AllNodes.IsSubsetOf(loopContents)) {
  133. containedChildStructures.Add(childStructure);
  134. } else if (childStructure.AllNodes.Intersect(loopContents).Any()) {
  135. invalidNesting = true;
  136. }
  137. }
  138. if (!invalidNesting) {
  139. current.Nodes.ExceptWith(loopContents);
  140. ControlStructure ctl = new ControlStructure(loopContents, node, ControlStructureType.Loop);
  141. foreach (ControlStructure childStructure in containedChildStructures) {
  142. ctl.Children.Add(childStructure);
  143. current.Children.Remove(childStructure);
  144. ctl.Nodes.ExceptWith(childStructure.AllNodes);
  145. }
  146. current.Children.Add(ctl);
  147. }
  148. }
  149. foreach (var edge in node.Outgoing) {
  150. FindLoops(current, edge.Target);
  151. }
  152. }
  153. static void FindLoopContents(ControlStructure current, HashSet<ControlFlowNode> loopContents, ControlFlowNode loopHead, ControlFlowNode node)
  154. {
  155. if (current.AllNodes.Contains(node) && loopHead.Dominates(node) && loopContents.Add(node)) {
  156. foreach (var edge in node.Incoming) {
  157. FindLoopContents(current, loopContents, loopHead, edge.Source);
  158. }
  159. }
  160. }
  161. #endregion
  162. }
  163. public enum ControlStructureType
  164. {
  165. /// <summary>
  166. /// The root block of the method
  167. /// </summary>
  168. Root,
  169. /// <summary>
  170. /// A nested control structure representing a loop.
  171. /// </summary>
  172. Loop,
  173. /// <summary>
  174. /// A nested control structure representing a try block.
  175. /// </summary>
  176. Try,
  177. /// <summary>
  178. /// A nested control structure representing a catch, finally, or fault block.
  179. /// </summary>
  180. Handler,
  181. /// <summary>
  182. /// A nested control structure representing an exception filter block.
  183. /// </summary>
  184. Filter
  185. }
  186. /// <summary>
  187. /// Represents the structure detected by the <see cref="ControlStructureDetector"/>.
  188. ///
  189. /// This is a tree of ControlStructure nodes. Each node contains a set of CFG nodes, and every CFG node is contained in exactly one ControlStructure node.
  190. /// </summary>
  191. public class ControlStructure
  192. {
  193. public readonly ControlStructureType Type;
  194. public readonly List<ControlStructure> Children = new List<ControlStructure>();
  195. /// <summary>
  196. /// The nodes in this control structure.
  197. /// </summary>
  198. public readonly HashSet<ControlFlowNode> Nodes;
  199. /// <summary>
  200. /// The nodes in this control structure and in all child control structures.
  201. /// </summary>
  202. public readonly HashSet<ControlFlowNode> AllNodes;
  203. /// <summary>
  204. /// The entry point of this control structure.
  205. /// </summary>
  206. public readonly ControlFlowNode EntryPoint;
  207. /// <summary>
  208. /// The exception handler associated with this Try,Handler or Finally structure.
  209. /// </summary>
  210. public ExceptionHandler ExceptionHandler;
  211. public ControlStructure(HashSet<ControlFlowNode> nodes, ControlFlowNode entryPoint, ControlStructureType type)
  212. {
  213. if (nodes == null)
  214. throw new ArgumentNullException("nodes");
  215. this.Nodes = nodes;
  216. this.EntryPoint = entryPoint;
  217. this.Type = type;
  218. this.AllNodes = new HashSet<ControlFlowNode>(nodes);
  219. }
  220. }
  221. }