GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — PSScriptAnalyzer/Engine/VariableAnalysisBase.cs at main · PowerShell/PSScriptAnalyzer Expand file tree/ Copy pathVariableAnalysisBase.csMore file actions 3494 lines (2997 loc) · 121 KB / Copy pathVariableAnalysisBase.csFile metadata and controls3494 lines (2997 loc) · 121 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Management.Automation; using System.Management.Automation.Language; using System.Reflection; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer { /// <summary> /// Base class for variable details /// </summary> public class VariableDetails { /// <summary> /// Type of variable /// </summary> public Type Type = typeof(Unreached); /// <summary> /// Name of variable (can be set by ssa) /// </summary> public string Name; /// <summary> /// Real name of variable /// </summary> public string RealName; /// <summary> /// Value of variable /// </summary> public object Constant = Unreached.UnreachedConstant; /// <summary> /// Block that variable is initialized in /// </summary> public Block DefinedBlock; /// <summary> /// Returns true if the two variable details have the same constant and same type /// </summary> /// <param name="varDetailsA"></param> /// <param name="varDetailsB"></param> /// <returns></returns> public static bool SameConstantAndType(VariableDetails varDetailsA, VariableDetails varDetailsB) { if (varDetailsA == null) { if (varDetailsB != null) { return false; } return true; } return ((varDetailsA.Constant == null && varDetailsB.Constant == null) || (varDetailsA.Constant != null && varDetailsA.Constant.Equals(varDetailsB.Constant))) && varDetailsA.Type == varDetailsB.Type; } } /// <summary> /// Class that stores the details of variable analysis /// </summary> public class VariableAnalysisDetails : VariableDetails { internal VariableAnalysisDetails() { this.AssociatedAsts = new List<Ast>(); } /// <summary> /// The Asts associated with the variables /// </summary> public List<Ast> AssociatedAsts { get; internal set; } internal List<Block> AssignedBlocks = new List<Block>(); } /// <summary> /// This class is used to find all the variables in an ast /// </summary> public class FindAllVariablesVisitor : AstVisitor { /// <summary> /// Visit an Ast and gets details about all the variables /// </summary> /// <param name="ast"></param> /// <returns></returns> public static Dictionary<string, VariableAnalysisDetails> Visit(Ast ast) { if (!(ast is ScriptBlockAst || ast is FunctionMemberAst || ast is FunctionDefinitionAst)) { return null; } var visitor = new FindAllVariablesVisitor(); visitor.InitializeVariables(ast); // Visit the body before the parameters so we don't allocate any tuple slots for parameters // if we won't be optimizing because of a call to new-variable/remove-variable, etc. if (ast is ScriptBlockAst) { (ast as ScriptBlockAst).Visit(visitor); } else if (ast is FunctionMemberAst) { (ast as FunctionMemberAst).Body.Visit(visitor); } else if (ast is FunctionDefinitionAst) { (ast as FunctionDefinitionAst).Body.Visit(visitor); } if (ast is FunctionMemberAst && (ast as FunctionMemberAst).Parameters != null) { visitor.VisitParameters((ast as FunctionMemberAst).Parameters); } else if (ast is FunctionDefinitionAst && (ast as FunctionDefinitionAst).Parameters != null) { visitor.VisitParameters((ast as FunctionDefinitionAst).Parameters); } return visitor._variables; } internal readonly Dictionary<string, VariableAnalysisDetails> _variables = new Dictionary<string, VariableAnalysisDetails>(StringComparer.OrdinalIgnoreCase); internal void InitializeVariables(Ast ast) { _variables.Add("true", new VariableAnalysisDetails { Name = "true", RealName = "true", Type = typeof(bool) }); _variables.Add("false", new VariableAnalysisDetails { Name = "false", RealName = "true", Type = typeof(bool) }); if (ast is FunctionMemberAst) { TypeDefinitionAst psClass = AssignmentTarget.FindClassAncestor(ast); if (psClass != null) { _variables.Add("this", new VariableAnalysisDetails { Name = "this", RealName = "this", Constant = SpecialVars.ThisVariable }); } } } internal void VisitParameters(ReadOnlyCollection<ParameterAst> parameters) { foreach (ParameterAst t in parameters) { var variableExpressionAst = t.Name; var varPath = variableExpressionAst.VariablePath; var variableName = AssignmentTarget.GetUnaliasedVariableName(varPath); VariableAnalysisDetails analysisDetails; if (_variables.TryGetValue(variableName, out analysisDetails)) { // Forget whatever type we deduced in the body, we'll revisit that type after walking // the flow graph. We should see the parameter type for the variable first. analysisDetails.Type = t.StaticType; } else { NoteVariable(variableName, t.StaticType); } } } /// <summary> /// Visit datastatement /// </summary> /// <param name="dataStatementAst"></param> /// <returns></returns> public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) { if (dataStatementAst != null && dataStatementAst.Variable != null) { NoteVariable(dataStatementAst.Variable, null); } return AstVisitAction.Continue; } /// <summary> /// Visit SwitchStatement /// </summary> /// <param name="switchStatementAst"></param> /// <returns></returns> public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { NoteVariable(SpecialVars.@switch, typeof(IEnumerator)); return AstVisitAction.Continue; } /// <summary> /// Visit Foreach statement /// </summary> /// <param name="forEachStatementAst"></param> /// <returns></returns> public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { NoteVariable(SpecialVars.@foreach, typeof(IEnumerator)); return AstVisitAction.Continue; } /// <summary> /// Visit VariableExpression /// </summary> /// <param name="variableExpressionAst"></param> /// <returns></returns> public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) { if (variableExpressionAst == null) { return AstVisitAction.Continue; } NoteVariable(AssignmentTarget.GetUnaliasedVariableName(variableExpressionAst.VariablePath), null); return AstVisitAction.Continue; } /// <summary> /// Visit UsingExpression /// </summary> /// <param name="usingExpressionAst"></param> /// <returns></returns> public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpressionAst) { // On the local machine, we may have set the index because of a call to ScriptBlockToPowerShell or Invoke-Command. // On the remote machine, the index probably isn't set yet, so we set it here, mostly to avoid another pass // over the ast. We assert below to ensure we're setting to the same value in both the local and remote cases. // Cannot access the RuntimeUsingIndex //if (usingExpressionAst.RuntimeUsingIndex == -1) //{ // usingExpressionAst.RuntimeUsingIndex = _runtimeUsingIndex; //} //System.Diagnostics.Debug.Assert(usingExpressionAst.RuntimeUsingIndex == _runtimeUsingIndex, "Logic error in visiting using expressions."); return AstVisitAction.Continue; } /// <summary> /// Visit Command /// </summary> /// <param name="commandAst"></param> /// <returns></returns> public override AstVisitAction VisitCommand(CommandAst commandAst) { return AstVisitAction.Continue; } /// <summary> /// Visit Function /// </summary> /// <param name="functionDefinitionAst"></param> /// <returns></returns> public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { // We don't want to discover any variables in nested functions - they get their own scope. return AstVisitAction.SkipChildren; } /// <summary> /// Visit ScriptBlock /// </summary> /// <param name="scriptBlockExpressionAst"></param> /// <returns></returns> public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { // We don't want to discover any variables in script block expressions - they get their own scope. return AstVisitAction.Continue; } /// <summary> /// Visit Trap /// </summary> /// <param name="trapStatementAst"></param> /// <returns></returns> public override AstVisitAction VisitTrap(TrapStatementAst trapStatementAst) { // We don't want to discover any variables in traps - they get their own scope. return AstVisitAction.SkipChildren; } // Return true if the variable is newly allocated and should be allocated in the locals tuple. internal void NoteVariable(string variableName, Type type) { if (!_variables.ContainsKey(variableName)) { var details = new VariableAnalysisDetails { Name = variableName, Type = type }; _variables.Add(variableName, details); } } } class LoopGotoTargets { internal LoopGotoTargets(string label, Block breakTarget, Block continueTarget) { this.Label = label; this.BreakTarget = breakTarget; this.ContinueTarget = continueTarget; } internal string Label { get; private set; } internal Block BreakTarget { get; private set; } internal Block ContinueTarget { get; private set; } } /// <summary> /// Represents unreached variable /// </summary> public class Unreached { internal static object UnreachedConstant = new object(); } /// <summary> /// Represent undetermined variable /// </summary> public class Undetermined { internal static object UndeterminedConstant = new object(); } /// <summary> /// Class that represents a Phi function /// </summary> public class Phi : VariableDetails { internal VariableTarget[] Operands; /// <summary> /// Constructor /// </summary> /// <param name="VarName"></param> /// <param name="block"></param> internal Phi(String VarName, Block block) { Name = VarName; Operands = new VariableTarget[block._predecessors.Count()]; for (int i = 0; i < Operands.Length; i += 1) { Operands[i] = new VariableTarget(); } RealName = Name; DefinedBlock = block; } } /// <summary> /// A block in the data flow graph /// </summary> public class Block { /// <summary> /// Asts in the block /// </summary> public LinkedList<object> _asts = new LinkedList<object>(); internal readonly List<Block> _successors = new List<Block>(); /// <summary> /// Predecessor blocks /// </summary> public List<Block> _predecessors = new List<Block>(); internal readonly HashSet<Block> SSASuccessors = new HashSet<Block>(); internal List<Block> DominatorSuccessors = new List<Block>(); internal static int count; internal int PostOrder; internal HashSet<Block> dominanceFrontierSet = new HashSet<Block>(); internal List<Phi> Phis = new List<Phi>(); private static Dictionary<string, Stack<VariableAnalysisDetails>> SSADictionary = new Dictionary<string, Stack<VariableAnalysisDetails>>(StringComparer.OrdinalIgnoreCase); internal static Dictionary<string, VariableAnalysisDetails> VariablesDictionary; internal static Dictionary<string, VariableAnalysisDetails> InternalVariablesDictionary = new Dictionary<string, VariableAnalysisDetails>(StringComparer.OrdinalIgnoreCase); private static Dictionary<string, int> Counters = new Dictionary<string, int>(); internal object _visitData; internal bool _visited; internal bool _throws; internal bool _returns; internal bool _unreachable; // Only Entry block, that can be constructed via NewEntryBlock() is reachable initially. // all other blocks are unreachable. // reachability of block should be proved with FlowsTo() calls. public Block() { this._unreachable = true; } public static Block NewEntryBlock() { return new Block(unreachable: false); } private Block(bool unreachable) { this._unreachable = unreachable; } /// <summary> /// Tell flow analysis that this block can flow to next block. /// </summary> /// <param name="next"></param> internal void FlowsTo(Block next) { if (_successors.IndexOf(next) < 0) { if (!_unreachable) { next._unreachable = false; } _successors.Add(next); next._predecessors.Add(this); } } internal void AddAst(object ast) { _asts.AddLast(ast); } internal void AddFirstAst(object ast) { _asts.AddFirst(ast); } /// <summary> /// Insert phi nodes at dominance frontier of each set. /// </summary> /// <param name="Variables"></param> internal static void InsertPhiNodes(Dictionary<string, VariableAnalysisDetails> Variables) { foreach (var variable in Variables.Keys.ToList()) { List<Block> everOnWorkList = new List<Block>(); List<Block> workList = new List<Block>(); List<Block> hasPhiAlready = new List<Block>(); everOnWorkList.AddRange(Variables[variable].AssignedBlocks); workList.AddRange(Variables[variable].AssignedBlocks); while (workList.Count != 0) { Block block = workList[workList.Count - 1]; workList.RemoveAt(workList.Count - 1); foreach (Block frontier in block.dominanceFrontierSet) { if (!hasPhiAlready.Contains(frontier)) { // INSERT PHI FUNCTION frontier.Phis.Add(new Phi(variable, frontier)); hasPhiAlready.Add(frontier); } if (!everOnWorkList.Contains(frontier)) { workList.Add(frontier); everOnWorkList.Add(frontier); } } } } } /// <summary> /// Fill in the DominanceFrontiersSet of each block. /// </summary> /// <param name="Blocks"></param> /// <param name="Entry"></param> internal static void DominanceFrontiers(List<Block> Blocks, Block Entry) { Block[] dominators = SetDominators(Entry, Blocks); foreach (Block block in Blocks) { if (block._predecessors.Count >= 2) { foreach (Block pred in block._predecessors) { Block runner = pred; while (runner != dominators[block.PostOrder]) { runner.dominanceFrontierSet.Add(block); runner = dominators[block.PostOrder]; } } } } } /// <summary> /// Returns the immediate dominator of each block. The array returned is /// indexed by postorder number of each block. /// Based on https://www.cs.rice.edu/~keith/Embed/dom.pdf /// </summary> /// <param name="entry"></param> /// <param name="Blocks"></param> /// <returns></returns> internal static Block[] SetDominators(Block entry, List<Block> Blocks) { Block[] dominators = new Block[Blocks.Count]; foreach (var block in Blocks) { dominators[block.PostOrder] = null; } dominators[entry.PostOrder] = entry; bool updated = true; while (updated) { updated = false; foreach (var block in Blocks) { if (block == entry) { continue; } if (block._predecessors.Count == 0) { continue; } Block dom = block._predecessors[0]; // Get first processed node foreach (var pred in block._predecessors) { if (dominators[pred.PostOrder] != null) { dom = pred; break; } } Block firstSelected = dom; foreach (var pred in block._predecessors) { if (firstSelected != pred && dominators[pred.PostOrder] != null) { // The order is reversed so we have to subtract from total dom = Blocks[Blocks.Count - Intersect(pred, dom, dominators) - 1]; } } if (dominators[block.PostOrder] != dom) { dominators[block.PostOrder] = dom; updated = true; } } } // Construct dominator tree foreach (var block in Blocks) { dominators[block.PostOrder].DominatorSuccessors.Add(block); } return dominators; } /// <summary> /// Given two nodes, return the postorder number of the closest node /// that dominates both. /// </summary> /// <param name="block1"></param> /// <param name="block2"></param> /// <param name="Dominators"></param> /// <returns></returns> internal static int Intersect(Block block1, Block block2, Block[] Dominators) { int b1 = block1.PostOrder; int b2 = block2.PostOrder; while (b1 != b2) { while (b1 < b2) { b1 = Dominators[b1].PostOrder; } while (b2 < b1) { b2 = Dominators[b2].PostOrder; } } return b1; } /// <summary> /// Generate new name for each assignment using the counters. /// </summary> /// <param name="VarName"></param> /// <param name="DefinedBlock"></param> /// <returns></returns> internal static string GenerateNewName(string VarName, Block DefinedBlock) { int i = Counters[VarName]; Counters[VarName] += 1; string newName = String.Format(CultureInfo.CurrentCulture, "{0}{1}", VarName, i); var varAnalysis = new VariableAnalysisDetails { Name = newName, DefinedBlock = DefinedBlock, RealName = VarName }; SSADictionary[VarName].Push(varAnalysis); InternalVariablesDictionary[newName] = varAnalysis; return newName; } /// <summary> /// Rename each variable (each assignment will give variable a new name). /// Also rename the phi function in each block as well /// </summary> /// <param name="block"></param> internal static void RenameVariables(Block block) { if (block._visited) { return; } block._visited = true; // foreach phi node generate new name foreach (var phi in block.Phis) { phi.Name = GenerateNewName(phi.RealName, block); } foreach (object ast in block._asts) { AssignmentTarget assignTarget = ast as AssignmentTarget; VariableTarget varTarget = null; if (assignTarget != null && !String.IsNullOrEmpty(assignTarget.Name)) { assignTarget.Name = GenerateNewName(assignTarget.Name, block); varTarget = assignTarget._rightHandSideVariable; } varTarget = (varTarget != null) ? varTarget : ast as VariableTarget; if (varTarget != null) { // If stack is empty then variable was not initialized; if (SSADictionary[varTarget.RealName].Count == 0) { VariablesDictionary[VariableAnalysis.AnalysisDictionaryKey(varTarget.VarAst)] = new VariableAnalysisDetails { Name = varTarget.Name, DefinedBlock = null, Type = varTarget.Type, RealName = null }; } else { VariableAnalysisDetails previous = SSADictionary[varTarget.RealName].Peek(); varTarget.Name = previous.Name; if (previous.DefinedBlock != null) { previous.DefinedBlock.SSASuccessors.Add(block); } VariablesDictionary[VariableAnalysis.AnalysisDictionaryKey(varTarget.VarAst)] = previous; } } } foreach (var successor in block._successors) { int index = successor._predecessors.IndexOf(block); foreach (var phi in successor.Phis) { // Stacks may be empty when variable was not initialized on all paths; if (SSADictionary[phi.RealName].Count != 0) { VariableAnalysisDetails previous = SSADictionary[phi.RealName].Peek(); if (previous.DefinedBlock != null) { previous.DefinedBlock.SSASuccessors.Add(successor); } phi.Operands[index] = new VariableTarget(previous); } else { phi.Operands[index] = new VariableTarget(); phi.Operands[index].Name = GenerateNewName(phi.RealName, null); } } } // Preorder travel along the dominator tree foreach (var successor in block.DominatorSuccessors) { RenameVariables(successor); } foreach (var phi in block.Phis) { SSADictionary[phi.RealName].Pop(); } foreach (object ast in block._asts) { AssignmentTarget assignTarget = ast as AssignmentTarget; if (assignTarget != null && !String.IsNullOrEmpty(assignTarget.RealName)) { SSADictionary[assignTarget.RealName].Pop(); } } } /// <summary> /// Initialize SSA /// </summary> /// <param name="VariableAnalysis"></param> /// <param name="Entry"></param> /// <param name="Blocks"></param> internal static void InitializeSSA(Dictionary<string, VariableAnalysisDetails> VariableAnalysis, Block Entry, List<Block> Blocks) { VariablesDictionary = new Dictionary<string, VariableAnalysisDetails>(StringComparer.OrdinalIgnoreCase); foreach (var block in Blocks) { List<Block> _unreachables = new List<Block>(); foreach (var pred in block._predecessors) { if (pred._unreachable) { _unreachables.Add(pred); pred._successors.Remove(block); } } foreach (var pred in _unreachables) { block._predecessors.Remove(pred); } } InternalVariablesDictionary.Clear(); SSADictionary.Clear(); Counters.Clear(); DominanceFrontiers(Blocks, Entry); InsertPhiNodes(VariableAnalysis); foreach (var key in VariableAnalysis.Keys.ToList()) { SSADictionary[key] = new Stack<VariableAnalysisDetails>(); Counters[key] = 0; } RenameVariables(Entry); } /// <summary> /// Sparse simple constant algorithm using use-def chain from SSA graph. /// </summary> /// <param name="Variables"></param> /// <param name="Entry"></param> /// <param name="Classes"></param> /// <returns></returns> internal static Tuple<Dictionary<string, VariableAnalysisDetails>, Dictionary<string, VariableAnalysisDetails>> SparseSimpleConstants( Dictionary<string, VariableAnalysisDetails> Variables, Block Entry, List<TypeDefinitionAst> Classes) { List<Block> blocks = GenerateReverseDepthFirstOrder(Entry); // Populate unreached variable with type from variables foreach (var block in blocks) { foreach (var ast in block._asts) { VariableTarget varTarget = (ast is AssignmentTarget) ? (ast as AssignmentTarget)._rightHandSideVariable : (ast as VariableTarget); if (varTarget != null && varTarget.Type == typeof(Unreached) && Variables.ContainsKey(varTarget.Name)) { varTarget.Type = Variables[varTarget.Name].Type; } } } InitializeSSA(Variables, Entry, blocks); LinkedList<Tuple<Block, Block>> workLists = new LinkedList<Tuple<Block, Block>>(); foreach (var block in blocks) { // Add a worklist from a block to itself to force analysis when variable is initialized but not used. // This is useful in the case where the variable is used in the inner function workLists.AddLast(Tuple.Create(block, block)); foreach (var ssaSucc in block.SSASuccessors) { if (ssaSucc != block) { workLists.AddLast(Tuple.Create(block, ssaSucc)); } } } // Initialize variables in internal dictionary to undetermined foreach (var key in InternalVariablesDictionary.Keys.ToList()) { InternalVariablesDictionary[key].Constant = Undetermined.UndeterminedConstant; InternalVariablesDictionary[key].Type = typeof(Undetermined); } // Initialize DefinedBlock of phi function. If it is null then that phi function is not initialized; foreach (var block in blocks) { foreach (var phi in block.Phis) { foreach (var operand in phi.Operands) { phi.DefinedBlock = operand.DefinedBlock; if (phi.DefinedBlock == null) { break; } } InternalVariablesDictionary[phi.Name].DefinedBlock = phi.DefinedBlock; } } while (workLists.Count != 0) { Tuple<Block, Block> SSAEdge = workLists.Last.Value; workLists.RemoveLast(); Block start = SSAEdge.Item1; Block end = SSAEdge.Item2; HashSet<string> defVariables = new HashSet<string>(); foreach (var obj in start._asts) { var assigned = obj as AssignmentTarget; if (assigned != null && assigned.Name != null && InternalVariablesDictionary.ContainsKey(assigned.Name)) { VariableAnalysisDetails varAnalysis = InternalVariablesDictionary[assigned.Name]; // For cases where the type or constant of the rhs is initialized not through assignment. if (assigned._rightHandSideVariable != null && !InternalVariablesDictionary.ContainsKey(assigned._rightHandSideVariable.Name) && Variables.ContainsKey(assigned._rightHandSideVariable.Name)) { VariableAnalysisDetails rhsAnalysis = Variables[assigned._rightHandSideVariable.Name]; assigned.Type = rhsAnalysis.Type; assigned.Constant = rhsAnalysis.Constant; } varAnalysis.Constant = assigned.Constant; varAnalysis.Type = assigned.Type; defVariables.Add(assigned.Name); } } foreach (var phi in start.Phis) { EvaluatePhiConstant(phi); EvaluatePhiType(phi); defVariables.Add(phi.Name); } bool updated = false; List<VariableTarget> varTargets = new List<VariableTarget>(); varTargets.AddRange(end._asts.Where(item => item is VariableTarget).Cast<VariableTarget>()); foreach (var phi in end.Phis) { varTargets.AddRange(phi.Operands); } foreach (var varTarget in varTargets) { if (defVariables.Contains(varTarget.Name)) { var analysisDetails = InternalVariablesDictionary[varTarget.Name]; if (!VariableDetails.SameConstantAndType(varTarget, analysisDetails)) { updated = true; } varTarget.Constant = analysisDetails.Constant; varTarget.Type = analysisDetails.Type; VariablesDictionary[VariableAnalysis.AnalysisDictionaryKey(varTarget.VarAst)] = InternalVariablesDictionary[varTarget.Name]; } } foreach (var ast in end._asts) { var assigned = ast as AssignmentTarget; if (assigned != null && assigned.Name != null && assigned._leftHandSideVariable != null) { // Handle cases like $b = $a after we found out the value of $a if (assigned._rightHandSideVariable != null && defVariables.Contains(assigned._rightHandSideVariable.Name)) { // Ignore assignments like $a = $a if (!String.Equals(assigned._rightHandSideVariable.Name, assigned.Name, StringComparison.OrdinalIgnoreCase)) { if (!InternalVariablesDictionary.ContainsKey(assigned._rightHandSideVariable.Name)) { continue; } var analysisDetails = InternalVariablesDictionary[assigned._rightHandSideVariable.Name]; if (!VariableDetails.SameConstantAndType(assigned, analysisDetails)) { updated = true; } assigned.Constant = analysisDetails.Constant; assigned.Type = analysisDetails.Type; } continue; } //TODO // Handle cases like $b = $a.SomeMethod or $a.SomeType after we found out the value of $a if (assigned._rightAst != null) { CommandExpressionAst cmeAst = assigned._rightAst as CommandExpressionAst; MemberExpressionAst memAst = (cmeAst != null) ? (cmeAst.Expression as MemberExpressionAst) : null; // Don't handle the this case because this is handled in assignment target if (memAst != null && memAst.Expression is VariableExpressionAst) { VariableAnalysisDetails analysis = VariablesDictionary[VariableAnalysis.AnalysisDictionaryKey(memAst.Expression as VariableExpressionAst)]; TypeDefinitionAst psClass = Classes.FirstOrDefault(item => String.Equals(item.Name, analysis.Type?.FullName, StringComparison.OrdinalIgnoreCase)); Type possibleType = AssignmentTarget.GetTypeFromMemberExpressionAst(memAst, analysis, psClass); if (possibleType != null && possibleType != assigned.Type) { assigned.Type = possibleType; updated = true; continue; } } } } } if (updated) { foreach (var block in end.SSASuccessors) { // Add to the front instead of the end since we are removing from end. workLists.AddFirst(Tuple.Create(end, block)); } } } return Tuple.Create(VariablesDictionary, InternalVariablesDictionary); } /// <summary> /// Evaluate the constant value at a phi node /// </summary> /// <param name="phi"></param> internal static void EvaluatePhiConstant(Phi phi) { int allUnreached = 0; object constantSoFar = null; bool first = true; if (phi.Operands.Length == 0 || phi.DefinedBlock == null) { return; } foreach (var operand in phi.Operands) { var operandDetails = InternalVariablesDictionary[operand.Name]; |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |