<html><head><style id="css_styles" type="text/css"><!--blockquote.cite { margin-left: 5px; margin-right: 0px; padding-left: 10px; padding-right:0px; border-left: 1px solid #cccccc }
blockquote.cite2 {margin-left: 5px; margin-right: 0px; padding-left: 10px; padding-right:0px; border-left: 1px solid #cccccc; margin-top: 3px; padding-top: 0px; }
a img { border: 0px; }
li[style='text-align: center;'], li[style='text-align: right;'] {  list-style-position: inside;}
body { font-family: Segoe UI; font-size: 12pt;   }--></style></head><body><div>(Moving the conversation<span> off the list.)</span></div>
<div><br /></div>
<div>------ Originalnachricht ------</div>
<div>Von: "Csaba Hruska" <<a href="mailto:csaba.hruska@gmail.com">csaba.hruska@gmail.com</a>></div>
<div>An: "Sebastian Graf" <<a href="mailto:sgraf1337@gmail.com">sgraf1337@gmail.com</a>></div>
<div>Cc: "ghc-devs" <<a href="mailto:ghc-devs@haskell.org">ghc-devs@haskell.org</a>>; "Sebastian Scheper" <<a href="mailto:sebastian.scheper@student.kit.edu">sebastian.scheper@student.kit.edu</a>></div>
<div>Gesendet: 16.12.2021 18:22:30</div>
<div>Betreff: Re: Re[2]: Transparently hooking into the STG stack to validate an escape analysis</div><div><br /></div>
<div id="xa5cf0a723f664ec"><blockquote cite="CANjChEqv_w4Arv-=nZ7XPii40tS8bZbip5OMi5KhrtqqXE5J=g@mail.gmail.com" type="cite" class="cite2">
<div dir="ltr"><div>Thanks for the feedback! <br /></div><div>Let's have a video meeting. My schedule is flexible. What time is best for you?</div><div><br /></div><div>Cheers,</div><div>Csaba<br /></div></div><br /><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Thu, Dec 16, 2021 at 5:29 PM Sebastian Graf <<a href="mailto:sgraf1337@gmail.com">sgraf1337@gmail.com</a>> wrote:<br /></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div><div>Hey Csaba,</div><div><br /></div><div>After catching up on your talk and reflecting about it a bit, it seems quite obvious that your tool is the right way to collect the data and validate our analysis!</div><div>Even if meanwhile we decided that a "transparent stack frame" (which I believe is something similar to what you are doing <a href="https://github.com/grin-compiler/ghc-whole-program-compiler-project/blob/d3ed07d9f3167ad1afa01d1aa95aec2472b2708f/external-stg-interpreter/lib/Stg/Interpreter.hs#L130">here</a>, with an explicit `argCount` which we do not know) is not the ideal solution we've been looking for (for different reasons).</div><div><br /></div><div>Essentially, we have two things</div><div><ol style="list-style-type:decimal"><li>An escape analysis, implemented as an STG-to-STG pass that attaches a boolean flag to each Id whether it "escapes its scope" (for a suitable definition of that).<br />We'd like to implement it in a way that it would be reusable within GHC with moderate effort (e.g., renaming Binder to Id or accounting for different fields), operating on a module at a time rather than whole program.</li><li>The instrumentation that tries to measure how many heap objects could be allocated on the stack. E.g., set a closure-specific flag whenever the closure is entered, unset that bit (once) when we "leave the scope" that defines the closure.<br />If my understanding is right, we could just implement this "instrumentation" as a simple extra field to <a href="https://github.com/grin-compiler/ghc-whole-program-compiler-project/blob/d3ed07d9f3167ad1afa01d1aa95aec2472b2708f/external-stg-interpreter/lib/Stg/Interpreter/Base.hs#L135">Closure</a>, right? Neat!</li></ol><div>A bit tangential: I see that your interpreter currently allocates a <a href="https://github.com/grin-compiler/ghc-whole-program-compiler-project/blob/d3ed07d9f3167ad1afa01d1aa95aec2472b2708f/external-stg-interpreter/lib/Stg/Interpreter.hs#L606">fresh closure for let-no-escapes</a> when it could just re-use the closure of its defining scope. That would skew our numbers somewhat compared to instrumenting GHC-compiled programs, but I think we'd be able to work around that. I also wonder if the semantics of your let-no-escapes are actually as typically specified (operationally), in that a jump to a let-no-escape should also reset the stack pointer. It should hardly matter for the programs that GHC generates, though.</div></div><div><br /></div><div>I would also be interested in knowing whether the +RTS -s "bytes allocated in the heap" metric (very nearly) coincides with a similar metric you could produce. It would be fantastic if that was the case! Theoretically, that should be possible, right?</div><div><br /></div><div>I think your interpreter work is very valuable to collect data we otherwise would only be able to measure with a TickyTicky-based approach. Nice!</div><div>Another, similar use case would be to identify the fraction of closures that are only entered once. I remember that there was a <a href="https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/compiler/demand#instrumentation">ticky-based patch with which Joachim used to measure this fraction</a> (and similarly validate the analysis results), but unfortunately it couldn't end up in master. Ah, yes, we have a whole open ticket about it: <a href="https://gitlab.haskell.org/ghc/ghc/-/issues/10613">#10613</a>. In fact, that instrumentation is also somewhat similar (adding a field to every closure) as what we want to do.</div><div><br /></div><div>Anyway, it seems like your work will be very valuable in replacing some of the annoying ticky-based instrumentation ideas!</div><div><br /></div><div>Maybe we can have a call some time this or next week to discuss details, once Sebastian and I are more familiar with the code base?</div><div><br /></div><div>Thanks for sticking with the project and doing all the hard work that can build upon!</div><div>Sebastian</div>
<div><br /></div>
<div>------ Originalnachricht ------</div>
<div>Von: "Csaba Hruska" <<a href="mailto:csaba.hruska@gmail.com">csaba.hruska@gmail.com</a>></div>
<div>An: "Sebastian Graf" <<a href="mailto:sgraf1337@gmail.com">sgraf1337@gmail.com</a>></div>
<div>Cc: "ghc-devs" <<a href="mailto:ghc-devs@haskell.org">ghc-devs@haskell.org</a>>; "Sebastian Scheper" <<a href="mailto:sebastian.scheper@student.kit.edu">sebastian.scheper@student.kit.edu</a>></div>
<div>Gesendet: 15.12.2021 16:16:27</div>
<div>Betreff: Re: Transparently hooking into the STG stack to validate an escape analysis</div><div><br /></div>
<div id="gmail-m_-5501899713496201467xf7445fc85493439"><blockquote cite="http://CANjChEpmxM6ZWMv0M0NUXOTGmbUnTvVNcYGUOGRGx=m70V1g4w@mail.gmail.com" type="cite" class="gmail-m_-5501899713496201467cite2">
<div dir="ltr"><div>Hi,</div><div><br /></div><div>IMO the Cmm STG machine implementation is just too complex for student projects. It's not fun to work with at all.<br /></div><div>Why did you choose this approach?<br /></div><div>IMO the escape analysis development and validation would be much smoother and fun when you'd use the external STG interpreter.<br /></div><div>When you have a solid and working design of your analysis and transformations then you could implement it in GHC's native backend if it needs any changes at all.</div><div><br /></div><div>What do you think?<br /></div><div>Do you disagree?</div><div><br /></div><div>Have you seen my presentation about the stg interpreter?<br /><a href="https://www.youtube.com/watch?v=Ey5OFPkxF_w">https://www.youtube.com/watch?v=Ey5OFPkxF_w</a></div><div><br /></div><div>Cheers,</div><div>Csaba<br /></div></div><br /><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Wed, Dec 8, 2021 at 11:20 AM Sebastian Graf <<a href="mailto:sgraf1337@gmail.com">sgraf1337@gmail.com</a>> wrote:<br /></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">



<div><div>Hi Devs,</div><div><br /></div><div>my master's student Sebastian and I (also Sebastian :)) are working on an escape analysis in STG, see <a href="https://gitlab.haskell.org/ghc/ghc/-/issues/16891#note_347903" style="font-size:12pt">https://gitlab.haskell.org/ghc/ghc/-/issues/16891#note_347903</a>.</div><div><br /></div><div>We have a prototype for the escape analysis that we want to validate/exploit now.</div><div>The original plan was to write the transformation that allocates non-escaping objects on the STG stack. But that is quite tricky for many reasons, one of them being treatment of the GC.</div><div><span><br /></span></div><div><span>This mail is rather lengthy, so I suggest you skip to "What we hope could work" and see if you can answer it without the context I provide below. If you can't, I would be very grateful if you were willing to suffer through the exposition.</span></div><div><div><div></div></div></div><div><div><div><div><font style="font-size:18pt"><br /></font></div><div><font style="font-size:18pt"># Instrumentation</font></div></div></div></div><div><font style="font-size:18pt"><br /></font></div><div>So instead we thought about doing a (easily changed and thus versatile) instrumentation-based approach:</div><div>Assign a sequence number to every <span>instantiation </span><span>(a term I will use to mean "allocation of g's closure")</span><span> of things that we our analysis determines as escaping or non-escaping, such as STG's let bindings (focusing on non-let-</span><span>no-</span><span>escape functions for now).</span></div><div>(One sequence number *per allocation<span>* of the let binding's closure, not based on its syntactic identity.)</span></div><div>Then, we set a bit in a (dynamically growing) global bit vector whenever the let "RHS is entered" and then unset it when we "leave the let-body". Example:</div><div><br /></div><div>f = \x y -></div><div>  let {</div><div>    g = [y] \z -> y + z;</div><div>  } in g x</div><div><br /></div><div>Here, our analysis could see that no instantiation (which I say instead of "allocation of g's closure") of g will ever escape its scope within f.</div><div>Our validation would give a fresh sequence number to the <span>instantiation </span><span>of g whenever f is called and store it in g's closure (which we arrange by piggy-backing on -prof and adding an additional field to the profiling header).</span></div><div>Then, when g's RHS is entered, we set the bit in the global bit vector, indicating "this instantiation of g might escape".</div><div>After leaving the RHS of g, we also leave the body of the defining let, which means we unset the bit in the bit vector, meaning "every use so far wasn't in an escaping scenario".</div><div><br /></div><div>So far so good. Modifying the code upon entering g takes a bit of tinkering but can be done by building on TickyTicky in StgToCmm.</div><div>But what is not done so easily is inserting the continuation upon entering the let that will unset the bit!</div><div><br /></div><div><font style="font-size:18pt" size="5"># What doesn't work: Modifying the Sequel</font></div><div><br /></div><div>At first, we tried to modify the <a href="https://gitlab.haskell.org/ghc/ghc/-/blob/4c6985cc91b9cf89b393f69c9a603e8df0aea9e0/compiler/GHC/StgToCmm/Monad.hs#L210-222">sequel</a> of the let-body to an `AssignTo`.</div><div>That requires us to know the registers in which the let-body will return its results, which in turn means we have to know the representation of those results, so we have to write a function `stgExprPrimRep :: GenStgExpr p -> [PrimRep]`.</div><div>Urgh! We were very surprised that there was no such function. And while we tested our function, we very soon knew why. Consider the following pattern synonym matcher:</div><div><br /></div>GHC.Natural.$mNatJ#<br />  :: forall {rep :: GHC.Types.RuntimeRep} {r :: TYPE rep}.<br />     GHC.Num.Natural.Natural<br />     -> (GHC.Num.BigNat.BigNat -> r) -> ((# #) -> r) -> r<br /> = {} \r [scrut_sBE cont_sBF fail_sBG]<br />        case scrut_sBE of {<br />          GHC.Num.Natural.NS _ -> fail_sBG GHC.Prim.(##);<br />          GHC.Num.Natural.NB ds_sBJ -><br />              let {<br />                sat_sBK :: GHC.Num.BigNat.BigNat<br />                 = CCCS <a href="http://GHC.Num.BigNat.BN#">GHC.Num.BigNat.BN#</a>! [ds_sBJ];<br />              } in  cont_sBF sat_sBK;<br />        };<br />
<div><br /></div><div>Note how its result is representation-polymorphic! It only works because our machine implementation allows tail-calls.</div><div>It's obvious in hindsight that we could never write `<span>stgExprPrimRep` in such a way that it will work on the expression `</span><span>cont_sBF sat_sBK`.</span></div><div><span>So the sequel approach seems infeasible.</span></div><div><span><br /></span></div><div><div><div><div><font style="font-size:18pt"># What we hope could work: A special stack frame</font></div></div></div></div><div><font style="font-size:18pt"><br /></font></div><div><span>The other alternative would be to insert a special continuation frame on the stack when we enter the let-body (inspired by stg_restore_cccs).</span></div><div><span>This continuation frame would simply push all registers (FP regs, GP regs, Vec regs, ...) to the C stack, do its work (unsetting the bit), then pop all registers again and jump to the topmost continuation on the STG stack.</span></div><div><span>Example:</span></div><div><span><br /></span></div><div><span>f :: forall rep (r :: TYPE rep). Int# -> (Int# -> r) -> r</span></div><div><div><div><div>f = \x g -></div><div>  let {</div><div>    h = [x] \a -> x + a;</div><div>  } in</div><div>  case h x of b {</div><div>    __DEFAULT -> g b</div><div>  }</div></div></div></div><div><br /></div><div>We are only interested in unsetting the bit for h here. Consider the stack when entering the body of h.</div><div><br /></div><div>caller_of_f_cont_info <- Sp</div><div><br /></div><div>Now push our special continuation frame:</div><div><br /></div><div><div><div><div>caller_of_f_cont_info</div></div></div></div><div>seq_h</div><div>unset_bit_stk_info <- Sp</div><div><br /></div><div>E.g., the stack frame contains the info pointer and the sequence number. (Btw., I hope I got the stack layout about right and this is even possible)</div><div>Then, after we entered the continuation of the __DEFAULT alt, we do a jump to g.</div><div>Plot twist: g returns an unboxed 8-tuple of `Int#`s (as <span>caller_of_f_cont_info knows, but f certainly doesn't!)</span><span>, so before it returns it will push two args on the stack (correct?):</span></div><div><span><br /></span></div><div><div><div><div><div><div><div>caller_of_f_cont_info</div></div></div></div><div>seq_h</div><div>unset_bit_stk_info</div><div>unboxed tuple component 7</div><div>unboxed tuple component 8 <- Sp</div></div></div></div><div><br /></div><div>And then `g` jumps directly to the entry code for `unset_bit_stk_info` (which does the register saving I mentioned), which absolutely can't figure out from Sp alone where seq_h is.</div><div>Darn! I think Luite's recent work on the StgToByteCode had to work around similar issues, I found this <a href="https://gitlab.haskell.org/ghc/ghc-wiki-mirror/-/blob/master/Unboxed-Tuples-and-Sums-in-GHCi-bytecode.md#returning-a-tuple">wiki page</a>. But we aren't in a position where we know the representation of `r` *at all*!</div><div><br /></div><div>So our idea was to scan the stack, beginning from `Sp`, until I find `unset_bit_stk_info`, giving us the following situation:</div><div><br /></div><div><div><div><div><div><div><div><div><div><div>caller_of_f_cont_info</div></div></div></div><div>seq_h</div><div>unset_bit_stk_info <- Bp</div><div>unboxed tuple component 7</div><div>unboxed tuple component 8 <- Sp</div></div></div></div></div></div></div><div><br /></div><div>I suggestively named the register in which we store the result Bp in analogy to the traditional base pointer. This information would be enough to unset the bit at index seq_h</div><div>and then copy the unboxed tuple components 7 and 8 up by two words:</div><div><br /></div><div><div><div><div><div>caller_of_f_cont_info</div><div><span>unboxed tuple component 7</span></div></div></div></div><div>unboxed tuple component 8 <- Sp<br /></div></div><div><br /></div><div>Then jump to <span>caller_of_f_cont_info, which knows what to make of the stack and the register state.</span></div><div><br /></div><div>The stack scanning is horrible and too brittle and slow for a production setting, as any of the unboxed tuple components could have the same bit pattern as `unset_bit_stk_info`.</div><div>We simply hope that is never the case and it's fine for the purposes of a quick-and-dirty instrumentation.</div><div><br /></div><div>QUESTION 1: What do you think? Could this work? Can you anticipate pit falls of this approach?</div><div><div><div><div><br /></div><div><div><div><div><div><div><div><font style="font-size:18pt"># What about Thunks and StgRhsCon?</font></div></div></div></div></div></div></div></div></div></div><div><font style="font-size:18pt"><br /></font></div><div><div>QUESTION 2: The instrumentation as described won't work for Thunks (which are only entered once) and constructor applications (like <span>sat_sBK in the BigNat matcher above). Not sure how to change that without incurring huge performance hits (by deactivating memoisation). Ideas are welcome here.</span></div><div><span><br /></span></div><div><span>Thanks for reading this far. I hope you could follow and are now fizzing with excitement because you have a much better idea of how to do this and will let me know :)</span></div></div><div><br /></div><div><span>Sebastian</span></div></div>_______________________________________________<br />
ghc-devs mailing list<br />
<a href="mailto:ghc-devs@haskell.org">ghc-devs@haskell.org</a><br />
<a href="http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs" rel="noreferrer">http://mail.haskell.org/cgi-bin/mailman/listinfo/ghc-devs</a><br />
</blockquote></div>
</blockquote></div>
</div></blockquote></div>
</blockquote></div>
</body></html>