Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

20101017 program analysis_for_security_livshits_lecture02_compilers

854 views

Published on

  • Be the first to comment

  • Be the first to like this

20101017 program analysis_for_security_livshits_lecture02_compilers

  1. 1. Introduction to Compilers<br />Ben Livshits<br />Based in part of Stanford class slides from <br />http://infolab.stanford.edu/~ullman/dragon/w06/w06.html<br />
  2. 2. Organization<br />Really basic stuff<br />Flow Graphs<br />Constant Folding<br />Global Common Subexpressions<br />Induction Variables/Reduction in Strength<br />Data-flow analysis<br />Proving Little Theorems<br />Data-Flow Equations<br />Major Examples<br />Pointer analysis<br />
  3. 3. Compiler Organization<br />
  4. 4. Dataflow Analysis Basics<br />L2: <br />Compiler Organization<br />Dataflow analysis basics<br />L3:<br />Dataflow lattices <br />Integrative dataflow solution<br />Gen/kill frameworks<br />
  5. 5. Pointer Analysis<br />L10:<br />Pointer analysis<br />L11<br />Pointer analysis and bddbddb<br />
  6. 6. 6<br />Really Basic Stuff<br /><ul><li>Flow Graphs
  7. 7. Constant Folding
  8. 8. Global Common Subexpressions
  9. 9. Induction Variables/Reduction in Strength</li></li></ul><li>7<br />Dawn of Code Optimization<br />A never-published Stanford technical report by Fran Allen in 1968<br />Flow graphs of intermediate code<br />Key things worth doing<br />
  10. 10. 8<br />Intermediate Code<br />for (i=0; i<n; i++)<br /> A[i] = 1;<br />Intermediate code exposes optimizable constructs we cannot see at source-code level.<br />Make flow explicit by breaking into basic blocks = sequences of steps with entry at beginning, exit at end.<br />
  11. 11. 9<br />i = 0<br />if i>=n goto …<br />t1 = 8*i <br />A[t1] = 1<br />i = i+1 <br />Basic Blocks <br />for (i=0; i<n; i++)<br /> A[i] = 1;<br />
  12. 12. 10<br />Induction Variables<br />x is an induction variable in a loop if it takes on a linear sequence of values each time through the loop.<br />Common case: loop index like i and computed array index like t1.<br />Eliminate “superfluous” induction variables.<br />Replace multiplication by addition (reduction in strength ). <br />
  13. 13. 11<br />Example<br />i = 0<br />if i>=n goto …<br />t1 = 8*i <br />A[t1] = 1<br />i = i+1 <br />t1 = 0 <br />n1 = 8*n<br />if t1>=n1 goto …<br />A[t1] = 1 <br />t1 = t1+8 <br />
  14. 14. 12<br />Loop-Invariant Code Motion<br />Sometimes, a computation is done each time around a loop.<br />Move it before the loop to save n-1 computations.<br />Be careful: could n=0? I.e., the loop is typically executed 0 times.<br />
  15. 15. 13<br />Example<br />i = 0<br />i = 0 <br />t1 = y+z<br />if i>=n goto …<br />if i>=n goto …<br />t1 = y+z <br />x = x+t1 <br />i = i+1 <br />x = x+t1<br />i = i+1 <br />
  16. 16. 14<br />Constant Folding<br />Sometimes a variable has a known constant value at a point.<br />If so, replacing the variable by the constant simplifies and speeds-up the code.<br />Easy within a basic block; harder across blocks.<br />
  17. 17. 15<br />Example<br />i = 0 <br />n = 100<br />if i>=n goto …<br />t1 = 8*i <br />A[t1] = 1<br />i = i+1 <br />t1 = 0 <br />if t1>=800 goto …<br />A[t1] = 1 <br />t1 = t1+8 <br />
  18. 18. 16<br />Global Common Subexpressions<br />Suppose block B has a computation of x+y.<br />Suppose we are sure that when we reach this computation, we are sure to have:<br />Computed x+y, and<br />Not subsequently reassigned x or y.<br />Then we can hold the value of x+y and use it in B.<br />
  19. 19. 17<br />Example<br />a = x+y <br />t = x+y<br />a = t <br />b = x+y <br />t = x+y<br />b = t <br />c = x+y <br />c = t <br />
  20. 20. 18<br />Example --- Even Better<br />t = x+y<br />a = t <br />t = x+y<br />b = t <br />c = t <br />t = x+y<br />a = t <br />b = t <br />t = x+y<br />b = t <br />c = t <br />
  21. 21. 19<br />Data-Flow Analysis<br /><ul><li>Proving Little Theorems
  22. 22. Data-Flow Equations
  23. 23. Major Examples</li></li></ul><li>20<br />An Obvious Theorem<br />boolean x = true;<br />while (x) {<br /> . . . // no change to x<br />}<br />Doesn’t terminate.<br />Proof: only assignment to x is at top, so x is always true.<br />
  24. 24. 21<br />As a Flow Graph<br />x = true<br />if x == true<br />“body”<br />
  25. 25. 22<br />Formulation: Reaching Definitions<br />Each place some variable x is assigned is a definition.<br />Ask: for this use of x, where could x last have been defined.<br />In our example: only at x=true.<br />
  26. 26. 23<br />d1<br />d2<br />Example: Reaching Definitions<br />d1: x = true<br />d1<br />if x == true<br />d2<br />d1<br />d2: a = 10<br />
  27. 27. 24<br />Clincher<br />Since at x == true, d1 is the only definition of x that reaches, it must be that x is true at that point.<br />The conditional is not really a conditional and can be replaced by a branch.<br />
  28. 28. 25<br />Not Always That Easy<br />int i = 2; int j = 3;<br />while (i != j) {<br /> if (i < j) i += 2;<br /> else j += 2;<br />}<br />We’ll develop techniques for this problem, but later …<br />
  29. 29. 26<br />d1<br />d2<br />d3<br />d4<br />d2, d3, d4<br />d1, d3, d4<br />d1, d2, d3, d4<br />d1, d2, d3, d4<br />The Flow Graph<br />d1: i = 2<br />d2: j = 3<br />if i != j<br />d1, d2, d3, d4<br />if i < j<br />d4: j = j+2<br />d3: i = i+2<br />
  30. 30. 27<br />DFA Is Sometimes Insufficient<br />In this example, i can be defined in two places, and j in two places.<br />No obvious way to discover that i!=j is always true.<br />But OK, because reaching definitions is sufficient to catch most opportunities for constant folding (replacement of a variable by its only possible value).<br />
  31. 31. 28<br />Be Conservative!<br />(Code optimization only)<br />It’s OK to discover a subset of the opportunities to make some code-improving transformation.<br />It’s notOK to think you have an opportunity that you don’t really have.<br />
  32. 32. 29<br />Example: Be Conservative<br />boolean x = true;<br />while (x) {<br /> . . . *p = false; . . .<br />}<br />Is it possible that p points to x?<br />
  33. 33. 30<br />Another<br />def of x<br />d2<br />As a Flow Graph<br />d1: x = true<br />d1<br />if x == true<br />d2: *p = false<br />
  34. 34. 31<br />Possible Resolution<br />Just as data-flow analysis of “reaching definitions” can tell what definitions of x might reach a point, another DFA can eliminate cases where p definitely does not point to x.<br />Example: the only definition of p is p = &y and there is no possibility that y is an alias of x.<br />
  35. 35. 32<br />Reaching Definitions Formalized<br />A definition d of a variable x is said to reach a point p in a flow graph if:<br />Every path from the entry of the flow graph to p has d on the path, and<br />After the last occurrence of d there is no possibility that x is redefined.<br />
  36. 36. 33<br />Data-Flow Equations --- (1)<br />A basic block can generate a definition.<br />A basic block can either<br />Kill a definition of x if it surely redefines x.<br />Transmit a definition if it may not redefine the same variable(s) as that definition.<br />
  37. 37. 34<br />Data-Flow Equations --- (2)<br />Variables:<br />IN(B) = set of definitions reaching the beginning of block B.<br />OUT(B) = set of definitions reaching the end of B.<br />
  38. 38. 35<br />Data-Flow Equations --- (3)<br />Two kinds of equations:<br />Confluence equations : IN(B) in terms of outs of predecessors of B.<br />Transfer equations : OUT(B) in terms of of IN(B) and what goes on in block B. <br />
  39. 39. 36<br />Confluence Equations<br />IN(B) = ∪predecessors P of B OUT(P)<br />{d2, d3}<br />{d1, d2}<br />P2<br />P1<br />{d1, d2, d3}<br />B<br />
  40. 40. 37<br />Transfer Equations<br />Generate a definition in the block if its variable is not definitely rewritten later in the basic block.<br />Kill a definition if its variable is definitely rewritten in the block.<br />An internal definition may be both killed and generated.<br />
  41. 41. 38<br />Example: Gen and Kill<br />IN = {d2(x), d3(y), d3(z), d5(y), d6(y), d7(z)} <br />d1: y = 3 <br />d2: x = y+z<br />d3: *p = 10<br />d4: y = 5 <br />Kill includes {d1(x), d2(x),<br />d3(y), d5(y), d6(y),…} <br />Gen = {d2(x), d3(x),<br /> d3(z),…, d4(y)} <br />OUT = {d2(x), d3(x), d3(z),…, d4(y), d7(z)} <br />
  42. 42. 39<br />Transfer Function for a Block<br />For any block B:<br />OUT(B) = (IN(B) – Kill(B)) ∪Gen(B)<br />
  43. 43. 40<br />Iterative Solution to Equations<br />For an n-block flow graph, there are 2n equations in 2n unknowns.<br />Alas, the solution is not unique.<br />Use iterative solution to get the least fixed-point.<br />Identifies any def that might reach a point.<br />
  44. 44. 41<br />Iterative Solution --- (2)<br />IN(entry) = ∅;<br />for each block B do OUT(B)= ∅;<br />while (changes occur) do<br /> for each block B do {<br />IN(B) = ∪predecessors P of B OUT(P);<br /> OUT(B) = (IN(B) – Kill(B)) ∪Gen(B);<br /> }<br />
  45. 45. 42<br />IN(B1) = {}<br />OUT(B1) = {<br />IN(B2) = {<br />d1,<br />OUT(B2) = {<br />IN(B3) = {<br />d1,<br />OUT(B3) = {<br />Example: Reaching Definitions<br />d1: x = 5<br />B1<br />d1}<br />d2}<br />if x == 10<br />B2<br />d1,<br />d2}<br />d2}<br />d2: x = 15<br />B3<br />d2}<br />
  46. 46. 43<br />Aside: Notice the Conservatism<br />Not only the most conservative assumption about when a def is killed or gen’d.<br />Also the conservative assumption that any path in the flow graph can actually be taken.<br />
  47. 47. 44<br />Everything Else About Data Flow Analysis<br /><ul><li>Flow- and Context-Sensitivity Logical Representation
  48. 48. Pointer Analysis
  49. 49. Interprocedural Analysis</li></li></ul><li>45<br />Three Levels of Sensitivity<br />In DFA so far, we have cared about where in the program we are.<br />Called flow-sensitivity.<br />But we didn’t care how we got there.<br />Called context-sensitivity.<br />We could even care about neither.<br />Example: where could x ever be defined in this program?<br />
  50. 50. 46<br />Flow/Context Insensitivity<br />Not so bad when program units are small (few assignments to any variable).<br />Example: Java code often consists of many small methods.<br />Remember: you can distinguish variables by their full name, e.g., class.method.block.identifier.<br />
  51. 51. 47<br />Context Sensitivity<br />Can distinguish paths to a given point.<br />Example: If we remembered paths, we would not have the problem in the constant-propagation framework where x+y = 5 but neither x nor y is constant over all paths.<br />
  52. 52. 48<br />The Example Again<br />x = 3<br />y = 2<br />x = 2<br />y = 3<br />z = x+y<br />
  53. 53. 49<br />An Interprocedural Example<br />int id(int x) {return x;}<br />void p() {a=2; b=id(a);…}<br />void q() {c=3; d=id(c);…}<br />If we distinguish p calling id from q calling id, then we can discover b=2 and d=3.<br />Otherwise, we think b, d = {2, 3}.<br />
  54. 54. 50<br />Context-Sensitivity --- (2)<br />Loops and recursive calls lead to an infinite number of contexts.<br />Generally used only for interprocedural analysis, so forget about loops.<br />Need to collapse strong components of the calling graph to a single group.<br />“Context” becomes the sequence of groups on the calling stack.<br />
  55. 55. 51<br />Example: Calling Graph<br />t<br />Contexts:<br />Green<br />Green, pink<br />Green, yellow<br />Green, pink, yellow<br />s<br />r<br />p<br />q<br />main<br />
  56. 56. 52<br />Comparative Complexity<br />Insensitive: proportional to size of program (number of variables).<br />Flow-Sensitive: size of program, squared (points times variables).<br />Context-Sensitive: worst-case exponential in program size (acyclic paths through the code).<br />
  57. 57. 53<br />Logical Representation<br />We have used a set-theoretic formulation of DFA.<br />IN = set of definitions, e.g.<br />There has been recent success with a logical formulation, involving predicates.<br />Example: Reach(d,x,i) = “definition d of variable x can reach point i.”<br />
  58. 58. 54<br />Comparison: Sets Vs. Logic<br />Both have an efficiency enhancement.<br />Sets: bit vectors and boolean ops.<br />Logic: BDD’s, incremental evaluation.<br />Logic allows integration of different aspects of a flow problem.<br />Think of PRE as an example. We needed 6 stages to compute what we wanted.<br />
  59. 59. 55<br />Datalog --- (1)<br />Predicate<br />Arguments:<br />variables or constants<br />The body :<br />For each assignment of values<br />to variables that makes all these<br />true …<br />Make this<br />atom true<br />(the head ).<br />Atom = Reach(d,x,i)<br />Literal = Atom or NOT Atom<br />Rule = Atom :- Literal & … & Literal<br />
  60. 60. 56<br />Example: Datalog Rules<br />Reach(d,x,j) :- Reach(d,x,i) &<br /> StatementAt(i,s) &<br /> NOT Assign(s,x) &<br /> Follows(i,j)<br />Reach(s,x,j) :- StatementAt(i,s) &<br /> Assign(s,x) &<br /> Follows(i,j)<br />
  61. 61. 57<br />Datalog --- (2)<br />Intuition: subgoals in the body are combined by “and” (strictly speaking: “join”).<br />Intuition: Multiple rules for a predicate (head) are combined by “or.”<br />
  62. 62. 58<br />Datalog --- (3)<br />Predicates can be implemented by relations (as in a database).<br />Each tuple, or assignment of values to the arguments, also represents a propositional (boolean) variable.<br />
  63. 63. 59<br />Iterative Algorithm for Datalog<br />Start with the EDB predicates = “whatever the code dictates,” and with all IDB predicates empty.<br />Repeatedly examine the bodies of the rules, and see what new IDB facts can be discovered from the EDB and existing IDB facts.<br />
  64. 64. 60<br />Example: Seminaive<br />Path(x,y) :- Arc(x,y)<br />Path(x,y) :- Path(x,z) & Path(z,y)<br />NewPath(x,y) = Arc(x,y); Path(x,y) = ∅;<br />while (NewPath != ∅) do {<br /> NewPath(x,y) = {(x,y) | NewPath(x,z)<br /> && Path(z,y) || Path(x,z) &&<br /> NewPath(z,y)} – Path(x,y);<br /> Path(x,y) = Path(x,y) ∪ NewPath(x,y);<br />}<br />
  65. 65. Pointer analysis<br />61<br />
  66. 66. 62<br />New Topic: Pointer Analysis<br />We shall consider Andersen’s formulation of Java object references.<br />Flow/context insensitive analysis.<br />Cast of characters:<br />Local variables, which point to:<br />Heap objects, which may have fields that are references to other heap objects.<br />
  67. 67. 63<br />Representing Heap Objects<br />A heap object is named by the statement in which it is created.<br />Note many run-time objects may have the same name.<br />Example: h: T v = new T;says variable v can point to (one of) the heap object(s) created by statement h.<br />v<br />h<br />
  68. 68. 64<br />Other Relevant Statements<br />v.f = w makes the f field of the heap object h pointed to by v point to what variable w points to.<br />f<br />v<br />w<br />f<br />h<br />g<br />i<br />
  69. 69. 65<br />Other Statements --- (2)<br />v = w.f makes v point to what the f field of the heap object h pointed to by w points to.<br />v<br />w<br />i<br />f<br />h<br />g<br />
  70. 70. 66<br />Other Statements --- (3)<br />v = w makes v point to whatever w points to.<br />Interprocedural Analysis : Also models copying an actual parameter to the corresponding formal or return value to a variable.<br />v<br />w<br />h<br />
  71. 71. 67<br />Datalog Rules<br />Pts(V,H) :- “H: V = new T”<br />Pts(V,H) :- “V=W” & Pts(W,H)<br />Pts(V,H) :- “V=W.F” & Pts(W,G) & Hpts(G,F,H)<br />Hpts(H,F,G) :- “V.F=W” & Pts(V,H) & Pts(W,G)<br />
  72. 72. 68<br />Example<br />T p(T x) {<br /> h: T a = new T;<br /> a.f = x;<br /> return a;<br />}<br />void main() {<br /> g: T b = new T;<br /> b = p(b);<br /> b = b.f;<br />}<br />
  73. 73. 69<br />Apply Rules Recursively --- Round 1<br />Pts(a,h)<br />Pts(b,g)<br />T p(T x) {h: T a = new T;<br /> a.f = x; return a;}<br />void main() {g: T b = new T;<br /> b = p(b); b = b.f;}<br />
  74. 74. 70<br />Apply Rules Recursively --- Round 2<br />Pts(x,g)<br />Pts(b,h)<br />T p(T x) {h: T a = new T;<br /> a.f = x; return a;}<br />void main() {g: T b = new T;<br /> b = p(b); b = b.f;}<br />Pts(a,h)<br />Pts(b,g)<br />
  75. 75. 71<br />Apply Rules Recursively --- Round 3<br />Hpts(h,f,g)<br />Pts(x,h)<br />T p(T x) {h: T a = new T;<br /> a.f = x; return a;}<br />void main() {g: T b = new T;<br /> b = p(b); b = b.f;}<br />Pts(a,h)<br />Pts(b,g)<br />Pts(x,g)<br />Pts(b,h)<br />
  76. 76. 72<br />Apply Rules Recursively --- Round 4<br />Hpts(h,f,h)<br />T p(T x) {h: T a = new T;<br /> a.f = x; return a;}<br />void main() {g: T b = new T;<br /> b = p(b); b = b.f;}<br />Pts(a,h)<br />Pts(b,g)<br />Pts(x,g)<br />Pts(b,h)<br />Pts(x,h)<br />Hpts(h,f,g)<br />
  77. 77. 73<br />Adding Context Sensitivity<br />Include a component C = context.<br />C doesn’t change within a function.<br />Call and return can extend the context if the called function is not mutually recursive with the caller.<br />
  78. 78. 74<br />Example of Rules: Context Sensitive<br />Pts(V,H,B,I+1,C) :- “B,I: V=W” & Pts(W,H,B,I,C)<br />Pts(X,H,B0,0,D) :- Pts(V,H,B,I,C) & “B,I: call P(…,V,…)” & “X is the corresponding actual to V in P” & “B0 is the entry of P” & “context D is C extended by P”<br />

×