252-210: compiler design - eth zürich · pdf file252-210: compiler design 9.6 available...
TRANSCRIPT
252-210:CompilerDesign9.6Availableexpressions9.7Busyexpressions
ThomasR.GrossComputerScienceDepartmentETHZurich,Switzerland
Availableexpressions
§ Anexpressiona+bisavailableatapointPifa+bisevaluatedoneverypathfromENTRYtoPandthereisnodefiniNonofaorbonthispathaOera+bwasevaluated§ InterestedinsetofexpressionsavailableatthestartofabasicblockB§ SetdependsonpathsthatleadtoPbefore_B
§ Assumethata+bhasnosideeffects§ ReadingamemorylocaConmayhavesideeffectstoo!§ NotaproblemforJavaLiorJava
2
3
e1: x = a + b if (Tcond)
e2: y = a + b
??
P
Availableexpressions
§ Isa+bcomputedine1availablefore2?§ AvailableatP
§ DependsonB2
B1
B2
B3
4
e1: x = a + b if (Tcond)
e2: y = a + b
a = …
P
Availableexpressions
§ Isa+bcomputedine1availablefore2?
§ No–amayhaveatPavaluethatdiffersfromthevalueate1.
B1
B2
B3
5
e1: x = a + b if (Tcond)
e2: y = a + b
a = … e3: z = a + b
P
Availableexpressions
§ Isa+bavailablefore2?§ Yes–eithercomputed
bye1orbye3
B1
B2
B3
TransferfuncNon
§ a+bisavailableattheendofbasicblockBifthereisnostmtinBthatfollowseandthatdefinesaorb§ MustbeconservaCve§ Ifastatementintheshadedregionmaymodifya(orb)thena+bisnot
availableattheendofB
6
… e: … = a + b …
B
TransferfuncNon
§ (Maybe)a+bisavailableatPbefore_B.
§ a+bisnotavailableatPaOer_B§ UnlessthereisastatementinBthatfollowsdandre-computesa+b,
seelastslide
§ DefiniNondhas“killed”theexpressiona+b
7
… d: a = … …
B
Pbefore_B
PaOer_B
TransferfuncNon
§ DefineforbasicblockB§ genB={expr|expra+bisevaluatedinB,neitheranorb
subsequentlydefinedinB}§ killB={expr|aorbofexpra+bdefinedinBanda+bisnot
subsequentlyevaluatedinB}
§ MustbeconservaNve§ Ingenonlyifwearesuretheexpressionisevaluated§ Inkillifthereisachancethatoneoftheoperandsofa+bisdefined
8
… d: x = … e: = a + b
TransferfuncNon
§ Wanttofindsets§ IN(B):setofexpressionsavailableatstartofB§ OUT(B):setofexpressionsavailableatendofB
§ TransferfuncNoncaptureshowstatementsinBdetermineOUT(B)
9
… d: x = … e: = a + b
IN(B)
OUT(B)
B
TransferfuncNon
§ GivenOUT(B1).§ WhatshouldbeIN(B2)andIN(B3)?
§ IN(B2)=OUT(B1),IN(B3)=OUT(B1)§ Anexpressionthatisavailablea_erB1isavailableatthestartofB2
andthestartofB310
...
… …
B1
B2 B3
TransferfuncNon
§ GivenOUT(B2)andOUT(B3)§ WhatshouldbeIN(B1)?
§ ExpressionEisavailableatPifEiscomputedoneverypathfromENTRYtoP(andnoneoftheoperandsofEiskilledsubsequently)
§ MustconsiderallpathsleadingtoP§ Emustbeavailableonallpaths 11
...
… …
B1
B2 B3
P
TransferfuncNon
§ GivenOUT(Bi)
§ IN(B)=∩Bi,BiispredecessorofBinCFGOUT(Bi)
12
...
… …
B1
B2 B3
FindingIN(B)andOUT(B)
§ genandkillcapturewhathappensinsideabasicblock§ Sometextsusee_genande_killtodisCnguishbetweensetsneeded
forreachingdefiniCons§ Thesesetsaredifferent!
§ WeneedINandOUTforeachbasicblock
§ IN(B)=∩Bi,BiispredecessorofBinCFGOUT(Bi)
§ OUT(B)=genB∪(IN(B)–killB)
§ Nbasicblocks,2×NsetsIN/OUT
13
FindingIN(B)andOUT(B)
§ Nbasicblocks,2×NsetsIN/OUT§ Systemwith2×Nunknowns
§ SolvebyiteraCngunClafixedpointisfound
§ HowtostartiteraNon?SafeassumpConOUT[ENTRY]=∅
14
FindingIN(B)andOUT(B)
§ SafeassumpNonOUT[ENTRY]=∅§ WhataboutOUT[Bi]forBi≠ENTRY?
§ ForreachingdefiniCons,wewantedsmallestsetofdefiniConsthat“reach”§ OKifwesaydreachesbutitdoesnot
§ Foravailableexpressions,wewantlargestsetofexpressionsthat“reach”§ OKifexprisavailablebutnotincludedinset
§ SostartwithalargeapproximaNonandremoveexpressionsthatareclearlynotavailable§ OUT[Bi]= U!§ U isthesetofallexpressionsthatappearintheprogram!
15
Findingavailableexpressions
OUT[ENTRY]=∅IniCalizeOUT[B]=U for∀B≠ENTRY
while(changestoanyOUT(B)){for(eachbasicblockB≠ENTRY){
IN(B)=∩Bi,BiispredecessorofBinCFGOUT(Bi) OUT(B)=genB∪(IN(B)–killB)}}
16
Comments
§ Thealgorithm(previousslide)idenNfiesanexpressionexpras“available”onlyifexpristrulyavailable.§ InducCononlengthofpath§ Ifexprisnotavailable(alongsomepath)thenexprisnotinOUT(B)for
ablockB§ exprisnotavailableforsomepredecessorB’ofBasweuse∩toformIN[B]
§ Again,theorderofvisiNngnodesmakers§ Forspeedofconvergence,notcorrectness
17
Availableexpressions
§ Isthisaforwardorabackwardproblem?
18
Availableexpressions
§ Isthisaforwardorabackwardproblem?§ Forward
§ Howsimilarisitto“reachingdefiniNons”?
§ ReachingdefiniCons:IN(B)=∪Bi,BiispredecessorofBinCFGOUT(Bi)
§ Availableexpressions:IN(B)=∩Bi,BiispredecessorofBinCFGOUT(Bi)
19
§ Summaryfordataflowproblems§ ComputetwosetsforeachbasicblockB
§ SoluCon=OUT(B)/IN(B)§ Context=IN(B)/OUT(B)
§ Twosetstocapturelocaleffects§ DefineadirecCon
§ ReachingdefiniCons,availableexpressions:Forward§ Ancestor:predecessor
§ Livevariables:Backward§ Ancestor:successor
§ InitSoluCon(ENTRY)/SoluCon(EXIT)§ InitremainingSoluConsets§ Definea“meetoperator”⟗
§ ReachingdefiniCons,livevariables:∪
§ Availableexpressions:∩
§ IterateoverbasicblocksBContext(B)=⟗Bi,BiisancestorofBinCFGSoluCon(Bi) SoluCon(B)=local_newB∪(Context(B)–local_cutB) 20
Dataflowproblems
21
Forward Backward
∪
∩
Dataflowproblems
22
Forward Backward
∪
∩
ReachingdefiniCons
Availableexpressions
Livevariables
9.7Busyexpressions
…
if (…) {
A[j] = 0;
} else {
A[j] = 1;
}
23
IRview
…
if (…) {
tmp1 = j * 4
tmp2 = &A + tmp1
*tmp2 = 0
} else {
tmp3 = j * 4
tmp4 = &A + tmp3
*tmp4 = 1
} 24
§ Expression j*4 isevaluatedinbothbranchesoftheif-stmt
§ HoisNng j*4 toblockabovetheif-stmtreducesthesizeoftheobjectcode§ No(immediate)speedbenefit
§ Expressionj*4isa“(very)busyexpression”.§ Anexpressiona+bisverybusyatapointPifa+bis
evaluatedonallpathsfromPtoEXITandthereisnodefiniNonofaorbonapathbetweenPandanevaluaNonofa+b § InterestedinsetofexpressionsavailableatthestartofabasicblockB§ SetdependsonpathsthatstartatPbefore_B 26
TransferfuncNon
§ a+bisverybusyatthestartofbasicblockBifthereisnostmtinBpriortoSthatdefinesaorb.
27
… S: … = a ⊕ b …
B
TransferfuncNon
§ a+bisnot(very)busyatthestartofbasicblockBasthereisastmtinBpriortoSthatdefinesa(stmtS’)
28
S’: a = S: … = a ⊕ b …
TransferfuncNon
§ DefineforbasicblockB§ killB={expr|anoperandofexprisdefinedinBbystmtSandexpris
notevaluatedbeforeS}§ genB={expr|exprisevaluatedinBpriortoadefiniConofanyofits
operands}
§ Setskillandgen:mustbeconservaNve§ Ingenonlyifwearesuretheexpressionisevaluated§ Inkillifthereisachancethattheexpressioniskilled
29
… S: … = a ⊕ b …
TransferfuncNon
§ NoNcethatwemaybeinterestedinthesetofbusyexpressionsatthestartofabasicblock§ Determinedbystatementsinbasicblockandstatementsin
subsequentbasicblocks
§ Setofbusyexpressionsattheendofabasicblock§ Determinedbystatementsinsubsequentbasicblocks§ Anotherterm:expressionisdownwardexposed
30
TransferfuncNon
31
§ ForabasicblockBwedefine§ IN(B)={expr|exprverybusyatPbefore_B}§ OUT(B)={expr|exprverybusyatPa_er_B}
§ Expressionb∈IN(B)§ bisevaluatedinBpriortodefiniConofanoperand,i.e.b∈genB§ b∈OUT(B)andoperandsofbnotdefinedinB,i.e.b∉killB
§ IN(B)=genB∪(OUT(B)–killB)
… S: … = a ⊕ b …
IN(B)={b1,b2,…,bn}
OUT(B)={b’1,b’2,…,v’m}
TransferfuncNon
§ GivenIN(B1)§ WhatshouldbeOUT(B2)andOUT(B3)?
§ OUT(B2)=IN(B1),OUT(B3)=IN(B1)
32
...
… …
B1
B2 B3
TransferfuncNon
§ GivenIN(B2)andIN(B3)§ WhatshouldbeOUT(B1)?
§ AnexpressionEis“verybusy”atapointPifEisevaluatedonallpathsfromPtoEXIT(andthereisnodefiniConofanoperandofEbetweenPandsuchanevaluaCon)
§ MustconsiderallpathsstarCngatP 33
...
… …
B1
B2 B3
TransferfuncNon
34
...
… …
B1
B2 B3
§ GivenIN(Bi)§ OUT(B)=∩Bi,BiissuccessorofBinCFGIN(Bi)
FindingIN(B)andOUT(B)
§ Nbasicblocks,2×NsetsIN/OUT§ Systemwith2×Nunknowns
§ SolvebyiteraCngunClafixedpointisfound
§ HowtostartiteraNon?SafeassumpConIN[EXIT]=∅Nothingisverybusyattheend
§ IN(B)=U§ U setofallexpressionsinprogram§ ForallB≠EXIT
35
CompuNngverybusyexpressions
IN[EXIT]=∅IniCalizeIN[B]=Ufor∀B≠EXITwhile(changestoanyIN(B)){for(eachbasicblockB≠EXIT){ OUT(B)=∩Bi,BiissuccessorofBinCFGIN(Bi)
IN(B)=genB∪(OUT(B)–killB)}}
36
Comments
§ CompilermustmovecodetobenefitfromverybusyexpressioninformaNon:codehoisNng
38
tmp5 = j * 4
tmp6 = &A + tmp5
if (…) {
*tmp6 = 0
} else {
*tmp6 = 1
}
…
if (…) {
tmp1 = j * 4
tmp2 = &A + tmp1
*tmp2 = 0
} else {
tmp3 = j * 4
tmp4 = &A + tmp3
*tmp4 = 1
}
Comments
§ ThereexistsanapproachtocodemoNonthatdealswithallkindsofcodemoNon§ Loopinvariantremoval§ Commonsub-expressioneliminaCon§ VerybusyexpressionhoisCng§ …
together(andalsodealswithotheropNmizaNons)andthereforecodehoisNng(ofbusyexpressionsinisolaNon)isnotemployedinmoderncompilers.
39
9.8Dataflowproblems
40
Forward Backward
∪
∩
ReachingdefiniCons
Availableexpressions
Livevariables
Verybusyexpressions
§ Summaryfordataflowproblems§ ComputetwosetsforeachbasicblockB
§ SoluCon=OUT(B)/IN(B)§ Context=IN(B)/OUT(B)
§ Twosetstocapturelocaleffects(local_new,local_cut)§ DefineadirecCon
§ ReachingdefiniCons,availableexpressions:Forward§ Ancestor:predecessor
§ Livevariables,verybusyexpressions:Backward§ Ancestor:successor
§ InitSoluCon(ENTRY)/SoluCon(EXIT)§ InitremainingSoluConsets§ Definea“meetoperator”⟗
§ ReachingdefiniCons,livevariables:∪
§ Availableexpressions,verybusyexpressions:∩
§ IterateoverbasicblocksBContext(B)=⟗Bi,BiisancestorofBinCFGSoluCon(Bi) SoluCon(B)=local_newB∪(Context(B)–local_cutB) 41
CompilerimplementaNon
§ FrameworkwithabstractfuncNonstoallowspecificaNonof§ IniCalizaConoflocal_new,local_cut§ DirecCon§ Meet(confluence)operator§ IniCalINandOUTsets§ TransferfuncCon(dependsondirecCon)
§ OUT=(IN–local_cut)∪local_gen§ IN=(OUT–local_cut)∪local_gen
§ UsetheframeworktoinstanNatespecificdataflowanalyses
42
43
Classhierarchy
9.9CodetransformaNons
§ CompilerusesglobaldataflowinformaNontoimplementcodetransformaNons
§ Coveredonlybrieflyinthisclass
44
9.9.1Constantfolding
§ Need:constantpropagaNoninformaNonasdiscussedin9.1§ OrreachingdefiniConsasdiscussedin9.2
§ TransformaNon:ifbothoperandsareconstant,computevalueincompiler§ AwenCon:carefulifthecompilerdoesnotrunontargetsystem
(“cross-compiler”)§ Mustmakesurecompilerproducesresultthatwouldhavebeen
obtainedatrunCme
§ TransformaNonmaycreatenewopportuniNes
45
9.9.2DeadassignmenteliminaNon
§ Need:livevariableanalysis§ Deadassignment:targetofstoreisnotlive
§ TransformaNon:removeuselessassignmentstatement§ AssumpCon:ReuseofavailableexpressionsCedto(designated
temporary)variables
§ TransformaNonmayrenderotherstatementsdead
46
9.9.3DeadcodeeliminaNon
§ Need:constantpropagaNoninformaNon,reachingdefiniNons
§ Deadcode:unreachablecode§ Forwell-structuredprograms:if-thenorif-then-elsestatementswith
condiConexpressionsthatcanbeevaluatedatcompileCme
§ TransformaNon:removeunreachablecode§ Mayrendervariablesdead
47
9.9.4CopypropagaNon
§ VarioustransformaNonsintroducecopies
x = a + b
if (..) {
z = a + b
}
y = a + b
48
x = a + b
t = x
if (..) {
z = t
}
y = t
CopypropagaNon
§ Maywanttoeliminatethecopies§ Replacetbyx
x = a + b
if (..) {
z = a + b
}
y = a + b
§ DeadassignmenteliminaNontakescareoft=x
49
x = a + b
t = x
if (..) {
z = x
}
y = x
CopypropagaNon
§ Mayalsohavebeneficialeffectsonregisterallocator
§ GivencopystmtS: t = x
§ CompilercansubsNtutexfortatpointPif1. DefiniConSistheonlydefiniConoftthatreachesP2. OneverypathfromStoPtherearenoassignmentstox
§ ApathmaygothroughPmulCpleCmesbutnotgothroughSasecondCmeandsCllmustsaCsfythiscondiCon
§ CondiNon(1)iseasilycheckedgivenreachingdefiniNons
50
Newdataflowproblem:“reachingcopystatements”§ ForeachbasicblockB
§ genB={copy-stmt|copy-stmta=bappearsinBandthereisnosubsequentdefiniConofbinB}
§ killB={copy-stmt|forthecopy-stmta=bthereisadefiniConofaorbinB(andcopy-stmtdoesnotappeara_erthesedefiniConsinB)}
§ Notethatdifferentassignments(copystatements)a=bkilleachother
§ TransferfuncNon§ IN(B):SetofcopiesS:a=bsuchthateverypathtoPbefore_BcontainsS
andthereisnodefiniConofbsubsequenttothelastoccurrenceofS§ OUT(B):…toPa_er_B…
51
TransferfuncNon
§ OUT(ENTRY)=∅§ OUT(B)=U
§ U setofallcopystatementsinprogram§ ForallB≠ENTRY
§ IN(B)=∩Bi,BiispredecessorofBinCFGOUT(Bi)
§ OUT(B)=genB∪(IN(B)–killB)
52
Findingreachingcopystatements
OUT[ENTRY]=∅IniCalizeOUT[B]=U for∀B≠ENTRY
while(changestoanyOUT(B)){for(eachbasicblockB≠ENTRY){
IN(B)=∩Bi,BiispredecessorofBinCFGOUT(Bi) OUT(B)=genB∪(IN(B)–killB)}}
53
54
S1: x = y
S2: y =
ExampleB1
B2S3: x = z B3
S4: … = x B4
S4: … = x B5
55
S1: x = y
S2: y =
ExampleB1
B2S3: x = z B3
S4: … = x B4
S4: … = x B5
gen={S1:x=y}kill={S3:x=z}
gen={S3:x=z}kill={S1:x=y}
gen={}kill={S1:x=y}
Example
§ IN(B2)=IN(B3)=OUT(B1)={S1:x=y}§ OUT(B2)=∅§ OUT(B3)=IN(B4)=OUT(B4)={S3:x=z}
§ IN(B5)=OUT(B2)∩OUT(B4)=∅
Pleasenotethatfor“reachingdefiniNons”,thedefiniNonofxinS1“reaches”B5(viaB2)
56
9.10“…mustbeconservaNve”
§ PointersnotanissueforJavaLi–mustbecarefuliflanguageallowsaddressestobetaken§ Riskofaliases
§ Arrays–don’tincludethemindataflowcomputaNon§ NoefforttounderstandmodificaConofindividualarrayelements
57
MethodinvocaNon
§ Java(andJavaLi)allowonlyvalueparameters*and*thereisnotwaytogetareferencetoalocalvariable§ Treatactualparameteras“uses”ofavariableresp.evaluaConofan
expression
§ Otherlanguagessupportpointers(andmayhaveglobalvariables)ret = foo (p1, p2, …, pn)
§ Variableretisdefined,p1,p2,…,pnareused§ Whatismodifiedbyfoo?
§ Anyparameterpi?§ LocaConsreachableviapi?§ Globals?
§ Mustmakeworst-caseassumpConintheabsenceofbewerinformaCon 58
ConservaNsm
int a, *b;
d1: a = 3;
d2: *b = ….
P:….
§ ForreachingdefiniNons,d1reachesP§ Can’tbesurethat*bwritesa
§ ForconstantpropagaNon,(a=3)isfalseatP§ *bmightdestroyvalueofa
59