Documents

A Correspondence Between Continuation Passing Style and Static Single Assignment Form - Kelsey R.

Description
A Correspondence Between Continuation Passing Style and Static Single Assignment Form - Kelsey R.
Categories
Published
of 10
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Related Documents
Share
Transcript
  ACorrespondencebetweenContinuationPassingStyle  andStaticSingleAssignmentForm     RichardA.Kelsey NECResearchInstitute kelsey@research.nj.nec.com  Abstract  Wedenesyntactictransformationsthatcon- vertcontinuationpassingstyle(CPS)programs intostaticsingleassignmentform(SSA)andvice versa.SomeCPSprogramscannotbeconverted toSSA,butthesearenotproducedbytheusual CPStransformation.TheCPS  !  SSAtransforma- tionisespeciallyhelpfulforcompilingfunctional programs.Manyoptimizationsthatnormallyre- quireowanalysiscanbeperformeddirectlyon functionalCPSprogramsbyviewingthemasSSA programs.Wealsopresentasimpleprogram transformationthatmergesCPSproceduresto- getherandbydoingsogreatlyincreasesthescope oftheSSAowinformation.Thistransformation isusefulforanalyzingloopsexpressedasrecursive procedures. Permissiontocopywithoutfeeallorpartofthismaterialisgrantedprovidedthatthecopiesarenotmadeordistributedfordirectcommercialadvantage,theACMcopyrightnoticeandthetitleofthepublicationanditsdateappear,andnoticeisgiventhatcopyingisbypermissionoftheAssociationforComputingMachinery.Tocopyotherwise,ortorepublish,requiresafeeand/orspecicpermission.IR'95-1/95SanFrancisco,CaliforniaUSA  c    1995ACM  1Introduction  Continuation-passingstylehasbeenusedasan intermediatelanguageinanumberofcompilers forfunctionallanguages1,8,12].Staticsingle assignmentformhasbeenusedinoptimizations targetedtowardsimperativelanguages,forexam- pleeliminatinginductionvariables13]andpar- tialredundancies2].Inthispaperwedenesyn- tactictransformationsforconvertingcontinuation passingstyle(CPS)programsintostaticsingleas- signmentform(SSA)andviceversa.ThesimilaritiesbetweenCPSandSSAhave beennotedbyothers1,9].InCPSthereis exactlyonebindingformforeveryvariableand variableusesarelexicallyscoped.InSSAthereis exactlyoneassignmentstatementforeveryvari- able,andthatstatementdominatesallusesofthe variable.Thisisalsothemaindierencebetween thetwo:therestrictiononvariablereferencesin CPSislexical,whileinSSAitisdynamic.Thetwoformshavegenerallybeenusedinvery dierentcontexts.CPShasbeenusedincom- pilersforfunctionallanguages,andSSAforim- perativeones.Asaresult,theproblemofow analysishascometobeviewedasmoredicult 13   inCPS.Thisisreallyanartifactoftheprograms beingcompiledandnotaproblemwiththeCPS intermediatelanguage.Functionalprogramsex- presscontrolowthroughtheuseofprocedures,resultinginlargecollectionsofsmallprocedures,asopposedtosmallcollectionsoflargeprocedures inimperativelanguages(by`large'procedurewe meanonelargeenoughtocontainaloop).The writersofcompilersforimperativelanguageshave beenquitesuccessfulwithusingSSAtoexpress theresultsofintraproceduralow-analysisand thenanalyzingtheSSAprogram.CPSusespro- cedurestoexpresspracticallyeverything,soany- thingbutthemostlocaloptimizationappearsto requireinterproceduralanalysis,whichishardin anylanguage.Inthispaperwearenotgoingtoconcernour- selveswithinterproceduralowanalysis.What wewilldoisrestrictournotionofwhatconsti- tutesaprocedureinCPS.The    formsinCPS programswillbeannotatedtoindicatewhichrep- resentfullproceduresandwhicharecontinua- tions.Thisreducesthenumberoffullprocedures andgreatlysimpliesanalyzingtheprogram.Throughoutthepaperwewillassumethatany useoflexicalscopinginthesourceprogramhas beenimplementedbytheintroducingexpliciten- vironments,asdescribedin1,7].Wefurther assumethatintheCPSprogramscontinuations arecreatedandusedinalast-in/rst-outman- ner(seesection6foradiscussion).Thelat- terrestrictiononlyaectsthewayinwhichnon- localreturns,suchaslongjumpsinCorcall-with- current-continuationinScheme,areexpressedin CPS.Thepaperproceedsasfollows.Section2con- tainsthedenitionofanSSAlanguage.Section3 denesasourcelanguage,anannotatedCPSlan- guage,andanalgorithmforconvertingsource programsintoCPSprograms.Thefollowingtwo sectionsdenefunctionsthatconvertCPSproce- duresintoSSAproceduresandviceversa.The remainderofthepaperisadiscussionofpractical dierencesbetweenSSAandCPS,followedbya comparisontopreviouswork. 2StaticSingleAssignment  SSAisanimperativeforminwhichthereisex- actlyoneassignmentforeveryvariableandthat assignmentdominatesallusesofthevariable(see 4]foragoodoverviewofSSA).Tomakethecontrol-owgraphexplicit,control owisexpressedentirelyintermsof  if  and  goto  .Weallowexpressionsinsomenonstandardplaces,forexampleastheargumentstothe    -functionsremovingtheseonlyrequiresintroducingafew additionalassignmentstatements.Thesyntaxof expressionsdoesnotmatterandisleftunspeci- ed,withtherestrictionthattheymaynotcon- tainprocedurecalls(andtheytypicallydon'tin SSAlanguages).ThegrammarforaprocedureinourSSAlan- guageis:P::=  proc(  x  *  )  f  BL*  g  L::=  l  :I*B I::=  x      (  E*  )  B::=  x    E    B  j x    E  (  E*  )  B  j goto  l  i    j return  E    j return  E  (  E*  )  j if  E  then  B  else  B E::=  x  j E+E  j ::: where  x  2  variables  l  2  labels Thesemanticsisthe`obvious'one.   isas- signment,E  (  E, ::: )  isaprocedurecall,and  return  returnsfromthecurrentprocedure.The    -functionsatthebeginningofablockeachtake oneargumentforeachofthe  goto  'sthatjumpto thatblock.Thei'thargumentisreturnedwhen controlreachestheblockfrom  goto  l  i  .Cytronetal.4]describeatranslational- gorithmthatecientlyconvertsprogramsinto SSAwhileintroducingtheminimumnumberof 14     -functions.Becauseeveryvariablehasauniqueassign- ment,denition  $  usechainsaretrivialtocom- pute.Manyanalysesandoptimizationsaresim- plerwhenappliedtoaprograminSSAformthan totheoriginalsourceprogram.BelowisanexampleSSAprocedurethatcounts thenumberoftimeszeroappearsinthesequence  f(0)  ::: f(limit-1)  forsomefunction  f  andin- teger  limit  .Notethatsomeofthecomputation occursinthe    -functions.Inparticularthesec- ond  if  makessenseonlyinthecontextofthe    -functionfor  c  0 atlabel  j  .Wewillbeusingthis examplethroughoutthepaper. proc(flimit)  f  gotol  0   l:i      (0,i+1) c      (0,c  0 ) ifi=limitthen returnc else x    f(i) ifx=0then gotoj  0   else gotoj  1    g  j:c  0     (c+1,c) gotol  1    g  3AnnotatedCPS  Incontinuationpassingstyleproceduresdonot return.Insteadtheyarepassedanadditionalar- gument,acontinuation,whichisappliedtothe procedure'sreturnvalue(seechapter8of5]for afulldiscussion).ThecorrespondencebetweenCPSandSSAre- quiresaslightlymodiedalgorithmforconverting programsintoCPS.Themodiedalgorithman- notatesthe    formsintheCPScodetoshowhow theyareused.Theannotationshavenosemantic contentand,ifnotintroducedbytheCPSalgo- rithm,couldbeaddedtotheprogramviasome suitableanalysis(assumingtheCPSprogramis inasuitableformseesection6below).OursourcelanguageisasubsetofScheme3],withthesubsetchosenasacompromisebetween simplicityandrealism.Forsimplicitywewillas- sumethatthesourceandCPSlanguagesusethe sameexpressionsasintheSSAlanguageofthe previoussection.InthecontextofSchemepro- gramswewillrefertotheequivalentsoftheSSA expressionsastrivialexpressions,tokeepfrom confusingthemwithotherSchemeexpressions.Asdescribedabove,themainrestrictionon(triv- ial)expressionsisthattheycannotcontainpro- cedurecalls.TosimplifytheCPSalgorithmthesourcelan- guageisrestrictedtoallownon-trivialexpressions onlyintailpositionorastheboundvalueina  let  .Inanactualcompilerthesourceprogram couldbeputinthisformeitherbyapre-passor aspartofamorecomplexCPSalgorithm.We alsoassumethateveryidentierisunique.A  loop  expressionisaversionofScheme's named-  let  withtherestrictionthatcallstothe labelmayonlyoccurintailposition.Itisin- cludedtoshowhowiterativeconstructs,suchas  for  and  while  loops,maybeconvertedintoCPS.ThegrammarforthisSchemesubsetis:M::=E  j (  EE*  )  j (if  EMM  )  j (let((  x  M  ))  M  )  j (loop  l  ((  x  E  )  *  )  M  )  j (  l  E*  )  E::=  x  j (+EE)  j ::: P::=  (    (  x  *  )  M  )  where  x  2  variables  l  2  labels Thesemanticsofthesourcelanguageisthat ofScheme.Thissubsetissucienttoimplement mostofScheme,withexplicitcellsaddedforany variablesthatarethetargetsof  set!  expressions inthesourceprogram.AswasdoneintheRabbitcompiler12]our 15   F  :M    C  !  M  0 F  (E, k  ]])=  (  k  E  )  F  (E, (    cont  (  x  )  M  0 )  ]])=  (let((  x  E  ))  M  0 )  F  (  (  E  ::: )  ,C]])=  (let((  v  (  E  ::: )))(   jv  ))  ifC=  x  and  x  isboundby  letrec  =  (  E  ::: C  )  otherwise  F  (  (let((  x  M  1  ))  M  2  )  ,C]])=  F  (M  1  , (    (  x  )  F  (M  2  ,C]])  )  ]])  F  (  (if  EM  1  M  2  )  , k  ]])=  (if  E  F  (M  1  , k  ]])  F  (M  2  , k  ]])  )  F  (  (if  EM  1  M  2  )  , (    cont  (  x  )  M  0 )  ]])=  (letrec((  x  (     jump  (  x  )  M  0 )))(if  E  F  (M  1  , x  ]])  F  (M  2  , x  ]])  ))  F  (  (loop  l  ((  x  E  initial )  ::: )  M  )  ,C]])=  (letrec((  l  (     jump  (  x  ::: )  F  (M,C]])  )))(  l  E  initial ::: ))  F  (  (  l  E  ::: )  ,C]])=  (  l  E  ::: )  V  :P  !  P  0 V  (  (    (  x  ::: )  M  )  ]])=  (    proc  (  x  ::: k  )  F  (M, k  ]])  )  Figure1:ConversiontoCPS conversiontoCPSwilltreattrivialexpressionsas valuesandnotintroducecontinuationsforthem.IntheCPSgrammarall    'sareannotatedas beingeither  proc  , cont  ,or   jump  .Theannotations indicatehowthe    'sareused,and,equivalently,howtheycanbecompiled. Proc  isusedasthetranslationofthe    forms inthesourceprogram.Thesearefullprocedures thateventuallyreturnavalueandforthisreason takeacontinuationasanargument.The  cont  and   jump  formsarecontinuationsthatareused inslightlydierentways.The  cont  continuations arereturnpointsforcallsto  proc  's. Jump  indi- catesthatthecontinuationiscalledwithinthe currentprocedureinsteadofbeingpassedtoan- otherone.TheCPSalgorithmintroduces     jump  continuationswhenthetwoarmsofaconditional havetorejoinatacommonpointandforthebod- iesof  loop  's.Intermsofcompilationstrategy, cont    'sarere- turnpoints,  jump  'scanbecompiledasgotos,and  proc  'srequireacompleteprocedure-callmecha- nism.ThegrammarfortheCPSlanguageisasfol- lows:M  0 ::=  (  EE*C  )  j (  k  E  )  j (if  EM  0 M  0 )  j (let((  x  E  ))  M  0 )  j (letrec((  x  P  0 ))  M  0 )  C::=  k  j (    cont  (  x  )  M  0 )  P  0 ::=  (    proc  (  x  *  k  )  M  0 )  j (     jump  (  x  *  )  M  0 )  where  x,k  2  variables Thesemanticsistheobviouscall-by-valuese- mantics.Theannotated    'sarealljust    , let  is syntacticsugarfor    ,andsoon.Theidentiers  x  and  k  usedinthegrammar aremembersofthesamesyntacticclass.Mak- ingthemsyntacticallydistinct,asissometimes done8],restrictshowcontinuationsareusedand makesCPSandSSAentirelyequivalent(seeSec- tion6).Thefunction  F  denedinFigure1translates sourceexpressionsMtoCPSexpressionsM  0 .It 16 
Search
Tags
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks