aoptx86.pas 765 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  126. function PrePeepholeOptSxx(var p : tai) : boolean;
  127. function PrePeepholeOptIMUL(var p : tai) : boolean;
  128. function PrePeepholeOptAND(var p : tai) : boolean;
  129. function OptPass1Test(var p: tai): boolean;
  130. function OptPass1Add(var p: tai): boolean;
  131. function OptPass1AND(var p : tai) : boolean;
  132. function OptPass1CMOVcc(var p: tai): Boolean;
  133. function OptPass1_V_MOVAP(var p : tai) : boolean;
  134. function OptPass1VOP(var p : tai) : boolean;
  135. function OptPass1MOV(var p : tai) : boolean;
  136. function OptPass1MOVD(var p : tai) : boolean;
  137. function OptPass1Movx(var p : tai) : boolean;
  138. function OptPass1MOVXX(var p : tai) : boolean;
  139. function OptPass1OP(var p : tai) : boolean;
  140. function OptPass1LEA(var p : tai) : boolean;
  141. function OptPass1Sub(var p : tai) : boolean;
  142. function OptPass1SHLSAL(var p : tai) : boolean;
  143. function OptPass1SHR(var p : tai) : boolean;
  144. function OptPass1FSTP(var p : tai) : boolean;
  145. function OptPass1FLD(var p : tai) : boolean;
  146. function OptPass1Cmp(var p : tai) : boolean;
  147. function OptPass1PXor(var p : tai) : boolean;
  148. function OptPass1VPXor(var p: tai): boolean;
  149. function OptPass1Imul(var p : tai) : boolean;
  150. function OptPass1Jcc(var p : tai) : boolean;
  151. function OptPass1SHXX(var p: tai): boolean;
  152. function OptPass1VMOVDQ(var p: tai): Boolean;
  153. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  154. function OptPass1STCCLC(var p: tai): Boolean;
  155. function OptPass2STCCLC(var p: tai): Boolean;
  156. function OptPass2CMOVcc(var p: tai): Boolean;
  157. function OptPass2Movx(var p : tai): Boolean;
  158. function OptPass2MOV(var p : tai) : boolean;
  159. function OptPass2Imul(var p : tai) : boolean;
  160. function OptPass2Jmp(var p : tai) : boolean;
  161. function OptPass2Jcc(var p : tai) : boolean;
  162. function OptPass2Lea(var p: tai): Boolean;
  163. function OptPass2SUB(var p: tai): Boolean;
  164. function OptPass2ADD(var p : tai): Boolean;
  165. function OptPass2SETcc(var p : tai) : boolean;
  166. function OptPass2Cmp(var p: tai): Boolean;
  167. function OptPass2Test(var p: tai): Boolean;
  168. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  169. function PostPeepholeOptMov(var p : tai) : Boolean;
  170. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  171. function PostPeepholeOptXor(var p : tai) : Boolean;
  172. function PostPeepholeOptAnd(var p : tai) : boolean;
  173. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  174. function PostPeepholeOptCmp(var p : tai) : Boolean;
  175. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  176. function PostPeepholeOptCall(var p : tai) : Boolean;
  177. function PostPeepholeOptLea(var p : tai) : Boolean;
  178. function PostPeepholeOptPush(var p: tai): Boolean;
  179. function PostPeepholeOptShr(var p : tai) : boolean;
  180. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  181. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  182. function PostPeepholeOptRET(var p: tai): Boolean;
  183. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  184. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  185. function TrySwapMovOp(var p, hp1: tai): Boolean;
  186. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  187. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  188. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  189. { Processor-dependent reference optimisation }
  190. class procedure OptimizeRefs(var p: taicpu); static;
  191. end;
  192. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  194. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  195. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  196. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  197. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  198. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  199. {$if max_operands>2}
  200. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  201. {$endif max_operands>2}
  202. function RefsEqual(const r1, r2: treference): boolean;
  203. { Like RefsEqual, but doesn't compare the offsets }
  204. function RefsAlmostEqual(const r1, r2: treference): boolean;
  205. { Note that Result is set to True if the references COULD overlap but the
  206. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  207. might still overlap because %reg2 could be equal to %reg1-4 }
  208. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  209. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  210. { returns true, if ref is a reference using only the registers passed as base and index
  211. and having an offset }
  212. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  213. implementation
  214. uses
  215. cutils,verbose,
  216. systems,
  217. globals,
  218. cpuinfo,
  219. procinfo,
  220. paramgr,
  221. aasmbase,
  222. aoptbase,aoptutils,
  223. symconst,symsym,
  224. cgx86,
  225. itcpugas;
  226. {$ifndef 8086}
  227. const
  228. MAX_CMOV_INSTRUCTIONS = 4;
  229. MAX_CMOV_REGISTERS = 8;
  230. type
  231. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  232. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  233. tsProcessed);
  234. { For OptPass2Jcc }
  235. TCMOVTracking = object
  236. private
  237. CMOVScore, ConstCount: LongInt;
  238. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  239. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  240. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  241. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  242. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  243. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  244. fOptimizer: TX86AsmOptimizer;
  245. fLabel: TAsmSymbol;
  246. fInsertionPoint,
  247. fCondition,
  248. fInitialJump,
  249. fFirstMovBlock,
  250. fFirstMovBlockStop,
  251. fSecondJump,
  252. fThirdJump,
  253. fSecondMovBlock,
  254. fSecondMovBlockStop,
  255. fMidLabel,
  256. fEndLabel,
  257. fAllocationRange: tai;
  258. fState: TCMovTrackingState;
  259. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  260. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  261. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  262. public
  263. RegisterTracking: TAllUsedRegs;
  264. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  265. destructor Done;
  266. procedure Process(out new_p: tai);
  267. property State: TCMovTrackingState read fState;
  268. end;
  269. PCMOVTracking = ^TCMOVTracking;
  270. {$endif 8086}
  271. {$ifdef DEBUG_AOPTCPU}
  272. const
  273. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  274. {$else DEBUG_AOPTCPU}
  275. { Empty strings help the optimizer to remove string concatenations that won't
  276. ever appear to the user on release builds. [Kit] }
  277. const
  278. SPeepholeOptimization = '';
  279. {$endif DEBUG_AOPTCPU}
  280. LIST_STEP_SIZE = 4;
  281. type
  282. TJumpTrackingItem = class(TLinkedListItem)
  283. private
  284. FSymbol: TAsmSymbol;
  285. FRefs: LongInt;
  286. public
  287. constructor Create(ASymbol: TAsmSymbol);
  288. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  289. property Symbol: TAsmSymbol read FSymbol;
  290. property Refs: LongInt read FRefs;
  291. end;
  292. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  293. begin
  294. inherited Create;
  295. FSymbol := ASymbol;
  296. FRefs := 0;
  297. end;
  298. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  299. begin
  300. Inc(FRefs);
  301. end;
  302. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  303. begin
  304. result :=
  305. (instr.typ = ait_instruction) and
  306. (taicpu(instr).opcode = op) and
  307. ((opsize = []) or (taicpu(instr).opsize in opsize));
  308. end;
  309. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  310. begin
  311. result :=
  312. (instr.typ = ait_instruction) and
  313. ((taicpu(instr).opcode = op1) or
  314. (taicpu(instr).opcode = op2)
  315. ) and
  316. ((opsize = []) or (taicpu(instr).opsize in opsize));
  317. end;
  318. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  319. begin
  320. result :=
  321. (instr.typ = ait_instruction) and
  322. ((taicpu(instr).opcode = op1) or
  323. (taicpu(instr).opcode = op2) or
  324. (taicpu(instr).opcode = op3)
  325. ) and
  326. ((opsize = []) or (taicpu(instr).opsize in opsize));
  327. end;
  328. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  329. const opsize : topsizes) : boolean;
  330. var
  331. op : TAsmOp;
  332. begin
  333. result:=false;
  334. if (instr.typ <> ait_instruction) or
  335. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  336. exit;
  337. for op in ops do
  338. begin
  339. if taicpu(instr).opcode = op then
  340. begin
  341. result:=true;
  342. exit;
  343. end;
  344. end;
  345. end;
  346. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  347. begin
  348. result := (oper.typ = top_reg) and (oper.reg = reg);
  349. end;
  350. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  351. begin
  352. result := (oper.typ = top_const) and (oper.val = a);
  353. end;
  354. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  355. begin
  356. result := oper1.typ = oper2.typ;
  357. if result then
  358. case oper1.typ of
  359. top_const:
  360. Result:=oper1.val = oper2.val;
  361. top_reg:
  362. Result:=oper1.reg = oper2.reg;
  363. top_ref:
  364. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  365. else
  366. internalerror(2013102801);
  367. end
  368. end;
  369. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  370. begin
  371. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  372. if result then
  373. case oper1.typ of
  374. top_const:
  375. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  376. top_reg:
  377. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  378. top_ref:
  379. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  380. else
  381. internalerror(2020052401);
  382. end
  383. end;
  384. function RefsEqual(const r1, r2: treference): boolean;
  385. begin
  386. RefsEqual :=
  387. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  388. (r1.relsymbol = r2.relsymbol) and
  389. (r1.segment = r2.segment) and (r1.base = r2.base) and
  390. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  391. (r1.offset = r2.offset) and
  392. (r1.volatility + r2.volatility = []);
  393. end;
  394. function RefsAlmostEqual(const r1, r2: treference): boolean;
  395. begin
  396. RefsAlmostEqual :=
  397. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  398. (r1.relsymbol = r2.relsymbol) and
  399. (r1.segment = r2.segment) and (r1.base = r2.base) and
  400. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  401. { Don't compare the offsets }
  402. (r1.volatility + r2.volatility = []);
  403. end;
  404. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  405. begin
  406. if (r1.symbol<>r2.symbol) then
  407. { If the index registers are different, there's a chance one could
  408. be set so it equals the other symbol }
  409. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  410. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  411. (r1.relsymbol = r2.relsymbol) and
  412. (r1.segment = r2.segment) and (r1.base = r2.base) and
  413. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  414. (r1.volatility + r2.volatility = []) then
  415. { In this case, it all depends on the offsets }
  416. Exit(abs(r1.offset - r2.offset) < Range);
  417. { There's a chance things MIGHT overlap, so take no chances }
  418. Result := True;
  419. end;
  420. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  421. begin
  422. Result:=(ref.offset=0) and
  423. (ref.scalefactor in [0,1]) and
  424. (ref.segment=NR_NO) and
  425. (ref.symbol=nil) and
  426. (ref.relsymbol=nil) and
  427. ((base=NR_INVALID) or
  428. (ref.base=base)) and
  429. ((index=NR_INVALID) or
  430. (ref.index=index)) and
  431. (ref.volatility=[]);
  432. end;
  433. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  434. begin
  435. Result:=(ref.scalefactor in [0,1]) and
  436. (ref.segment=NR_NO) and
  437. (ref.symbol=nil) and
  438. (ref.relsymbol=nil) and
  439. ((base=NR_INVALID) or
  440. (ref.base=base)) and
  441. ((index=NR_INVALID) or
  442. (ref.index=index)) and
  443. (ref.volatility=[]);
  444. end;
  445. function InstrReadsFlags(p: tai): boolean;
  446. begin
  447. InstrReadsFlags := true;
  448. case p.typ of
  449. ait_instruction:
  450. if InsProp[taicpu(p).opcode].Ch*
  451. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  452. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  453. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  454. exit;
  455. ait_label:
  456. exit;
  457. else
  458. ;
  459. end;
  460. InstrReadsFlags := false;
  461. end;
  462. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  463. begin
  464. Next:=Current;
  465. repeat
  466. Result:=GetNextInstruction(Next,Next);
  467. until not (Result) or
  468. not(cs_opt_level3 in current_settings.optimizerswitches) or
  469. (Next.typ<>ait_instruction) or
  470. RegInInstruction(reg,Next) or
  471. is_calljmp(taicpu(Next).opcode);
  472. end;
  473. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  474. var
  475. GetNextResult: Boolean;
  476. begin
  477. Result:=0;
  478. Next:=Current;
  479. repeat
  480. GetNextResult := GetNextInstruction(Next,Next);
  481. if GetNextResult then
  482. Inc(Result)
  483. else
  484. { Must return zero upon hitting the end of the linked list without a match }
  485. Result := 0;
  486. until not (GetNextResult) or
  487. not(cs_opt_level3 in current_settings.optimizerswitches) or
  488. (Next.typ<>ait_instruction) or
  489. RegInInstruction(reg,Next) or
  490. is_calljmp(taicpu(Next).opcode);
  491. end;
  492. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  493. procedure TrackJump(Symbol: TAsmSymbol);
  494. var
  495. Search: TJumpTrackingItem;
  496. begin
  497. { See if an entry already exists in our jump tracking list
  498. (faster to search backwards due to the higher chance of
  499. matching destinations) }
  500. Search := TJumpTrackingItem(JumpTracking.Last);
  501. while Assigned(Search) do
  502. begin
  503. if Search.Symbol = Symbol then
  504. begin
  505. { Found it - remove it so it can be pushed to the front }
  506. JumpTracking.Remove(Search);
  507. Break;
  508. end;
  509. Search := TJumpTrackingItem(Search.Previous);
  510. end;
  511. if not Assigned(Search) then
  512. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  513. JumpTracking.Concat(Search);
  514. Search.IncRefs;
  515. end;
  516. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  517. var
  518. Search: TJumpTrackingItem;
  519. begin
  520. Result := False;
  521. { See if this label appears in the tracking list }
  522. Search := TJumpTrackingItem(JumpTracking.Last);
  523. while Assigned(Search) do
  524. begin
  525. if Search.Symbol = Symbol then
  526. begin
  527. { Found it - let's see what we can discover }
  528. if Search.Symbol.getrefs = Search.Refs then
  529. begin
  530. { Success - all the references are accounted for }
  531. JumpTracking.Remove(Search);
  532. Search.Free;
  533. { It is logically impossible for CrossJump to be false here
  534. because we must have run into a conditional jump for
  535. this label at some point }
  536. if not CrossJump then
  537. InternalError(2022041710);
  538. if JumpTracking.First = nil then
  539. { Tracking list is now empty - no more cross jumps }
  540. CrossJump := False;
  541. Result := True;
  542. Exit;
  543. end;
  544. { If the references don't match, it's possible to enter
  545. this label through other means, so drop out }
  546. Exit;
  547. end;
  548. Search := TJumpTrackingItem(Search.Previous);
  549. end;
  550. end;
  551. var
  552. Next_Label: tai;
  553. begin
  554. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  555. Next := Current;
  556. repeat
  557. Result := GetNextInstruction(Next,Next);
  558. if not Result then
  559. Break;
  560. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  561. if is_calljmpuncondret(taicpu(Next).opcode) then
  562. begin
  563. if (taicpu(Next).opcode = A_JMP) and
  564. { Remove dead code now to save time }
  565. RemoveDeadCodeAfterJump(taicpu(Next)) then
  566. { A jump was removed, but not the current instruction, and
  567. Result doesn't necessarily translate into an optimisation
  568. routine's Result, so use the "Force New Iteration" flag so
  569. mark a new pass }
  570. Include(OptsToCheck, aoc_ForceNewIteration);
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if IsJumpToLabel(taicpu(Next)) and
  582. GetNextInstruction(Next, Next_Label) then
  583. begin
  584. { If we have JMP .lbl, and the label after it has all of its
  585. references tracked, then this is probably an if-else style of
  586. block and we can keep tracking. If the label for this jump
  587. then appears later and is fully tracked, then it's the end
  588. of the if-else blocks and the code paths converge (thus
  589. marking the end of the cross-jump) }
  590. if (Next_Label.typ = ait_label) then
  591. begin
  592. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  593. begin
  594. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  595. Next := Next_Label;
  596. { CrossJump gets set to false by LabelAccountedFor if the
  597. list is completely emptied (as it indicates that all
  598. code paths have converged). We could avoid this nuance
  599. by moving the TrackJump call to before the
  600. LabelAccountedFor call, but this is slower in situations
  601. where LabelAccountedFor would return False due to the
  602. creation of a new object that is not used and destroyed
  603. soon after. }
  604. CrossJump := True;
  605. Continue;
  606. end;
  607. end
  608. else if (Next_Label.typ <> ait_marker) then
  609. { We just did a RemoveDeadCodeAfterJump, so either we find
  610. a label, the end of the procedure or some kind of marker}
  611. InternalError(2022041720);
  612. end;
  613. Result := False;
  614. Exit;
  615. end
  616. else
  617. begin
  618. if not Assigned(JumpTracking) then
  619. begin
  620. { Cross-label optimisations often causes other optimisations
  621. to perform worse because they're not given the chance to
  622. optimise locally. In this case, don't do the cross-label
  623. optimisations yet, but flag them as a potential possibility
  624. for the next iteration of Pass 1 }
  625. if not NotFirstIteration then
  626. Include(OptsToCheck, aoc_ForceNewIteration);
  627. end
  628. else if IsJumpToLabel(taicpu(Next)) then
  629. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  630. else
  631. { Conditional jumps should always be a jump to label }
  632. InternalError(2022041701);
  633. CrossJump := True;
  634. Continue;
  635. end;
  636. if Next.typ = ait_label then
  637. begin
  638. if not Assigned(JumpTracking) then
  639. begin
  640. { Cross-label optimisations often causes other optimisations
  641. to perform worse because they're not given the chance to
  642. optimise locally. In this case, don't do the cross-label
  643. optimisations yet, but flag them as a potential possibility
  644. for the next iteration of Pass 1 }
  645. if not NotFirstIteration then
  646. Include(OptsToCheck, aoc_ForceNewIteration);
  647. end
  648. else if LabelAccountedFor(tai_label(Next).labsym) then
  649. Continue;
  650. { If we reach here, we're at a label that hasn't been seen before
  651. (or JumpTracking was nil) }
  652. Break;
  653. end;
  654. until not Result or
  655. not (cs_opt_level3 in current_settings.optimizerswitches) or
  656. not (Next.typ in [ait_label, ait_instruction]) or
  657. RegInInstruction(reg,Next);
  658. end;
  659. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  660. begin
  661. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  662. begin
  663. Result:=GetNextInstruction(Current,Next);
  664. exit;
  665. end;
  666. Next:=tai(Current.Next);
  667. Result:=false;
  668. while assigned(Next) do
  669. begin
  670. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  671. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  672. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  673. exit
  674. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  675. begin
  676. Result:=true;
  677. exit;
  678. end;
  679. Next:=tai(Next.Next);
  680. end;
  681. end;
  682. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  683. begin
  684. Result:=RegReadByInstruction(reg,hp);
  685. end;
  686. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  687. var
  688. p: taicpu;
  689. opcount: longint;
  690. begin
  691. RegReadByInstruction := false;
  692. if hp.typ <> ait_instruction then
  693. exit;
  694. p := taicpu(hp);
  695. case p.opcode of
  696. A_CALL:
  697. regreadbyinstruction := true;
  698. A_IMUL:
  699. case p.ops of
  700. 1:
  701. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  702. (
  703. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  704. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  705. );
  706. 2,3:
  707. regReadByInstruction :=
  708. reginop(reg,p.oper[0]^) or
  709. reginop(reg,p.oper[1]^);
  710. else
  711. InternalError(2019112801);
  712. end;
  713. A_MUL:
  714. begin
  715. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  716. (
  717. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  718. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  719. );
  720. end;
  721. A_IDIV,A_DIV:
  722. begin
  723. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  724. (
  725. (getregtype(reg)=R_INTREGISTER) and
  726. (
  727. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  728. )
  729. );
  730. end;
  731. else
  732. begin
  733. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  734. begin
  735. RegReadByInstruction := false;
  736. exit;
  737. end;
  738. for opcount := 0 to p.ops-1 do
  739. if (p.oper[opCount]^.typ = top_ref) and
  740. RegInRef(reg,p.oper[opcount]^.ref^) then
  741. begin
  742. RegReadByInstruction := true;
  743. exit
  744. end;
  745. { special handling for SSE MOVSD }
  746. if (p.opcode=A_MOVSD) and (p.ops>0) then
  747. begin
  748. if p.ops<>2 then
  749. internalerror(2017042702);
  750. regReadByInstruction := reginop(reg,p.oper[0]^) or
  751. (
  752. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  753. );
  754. exit;
  755. end;
  756. with insprop[p.opcode] do
  757. begin
  758. case getregtype(reg) of
  759. R_INTREGISTER:
  760. begin
  761. case getsupreg(reg) of
  762. RS_EAX:
  763. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  764. begin
  765. RegReadByInstruction := true;
  766. exit
  767. end;
  768. RS_ECX:
  769. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  770. begin
  771. RegReadByInstruction := true;
  772. exit
  773. end;
  774. RS_EDX:
  775. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  776. begin
  777. RegReadByInstruction := true;
  778. exit
  779. end;
  780. RS_EBX:
  781. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  782. begin
  783. RegReadByInstruction := true;
  784. exit
  785. end;
  786. RS_ESP:
  787. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  788. begin
  789. RegReadByInstruction := true;
  790. exit
  791. end;
  792. RS_EBP:
  793. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  794. begin
  795. RegReadByInstruction := true;
  796. exit
  797. end;
  798. RS_ESI:
  799. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  800. begin
  801. RegReadByInstruction := true;
  802. exit
  803. end;
  804. RS_EDI:
  805. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  806. begin
  807. RegReadByInstruction := true;
  808. exit
  809. end;
  810. end;
  811. end;
  812. R_MMREGISTER:
  813. begin
  814. case getsupreg(reg) of
  815. RS_XMM0:
  816. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  817. begin
  818. RegReadByInstruction := true;
  819. exit
  820. end;
  821. end;
  822. end;
  823. else
  824. ;
  825. end;
  826. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  827. begin
  828. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  829. begin
  830. case p.condition of
  831. C_A,C_NBE, { CF=0 and ZF=0 }
  832. C_BE,C_NA: { CF=1 or ZF=1 }
  833. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  834. C_AE,C_NB,C_NC, { CF=0 }
  835. C_B,C_NAE,C_C: { CF=1 }
  836. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  837. C_NE,C_NZ, { ZF=0 }
  838. C_E,C_Z: { ZF=1 }
  839. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  840. C_G,C_NLE, { ZF=0 and SF=OF }
  841. C_LE,C_NG: { ZF=1 or SF<>OF }
  842. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  843. C_GE,C_NL, { SF=OF }
  844. C_L,C_NGE: { SF<>OF }
  845. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  846. C_NO, { OF=0 }
  847. C_O: { OF=1 }
  848. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  849. C_NP,C_PO, { PF=0 }
  850. C_P,C_PE: { PF=1 }
  851. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  852. C_NS, { SF=0 }
  853. C_S: { SF=1 }
  854. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  855. else
  856. internalerror(2017042701);
  857. end;
  858. if RegReadByInstruction then
  859. exit;
  860. end;
  861. case getsubreg(reg) of
  862. R_SUBW,R_SUBD,R_SUBQ:
  863. RegReadByInstruction :=
  864. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  865. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  866. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  867. R_SUBFLAGCARRY:
  868. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  869. R_SUBFLAGPARITY:
  870. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  871. R_SUBFLAGAUXILIARY:
  872. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  873. R_SUBFLAGZERO:
  874. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  875. R_SUBFLAGSIGN:
  876. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  877. R_SUBFLAGOVERFLOW:
  878. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGINTERRUPT:
  880. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. R_SUBFLAGDIRECTION:
  882. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  883. else
  884. internalerror(2017042601);
  885. end;
  886. exit;
  887. end;
  888. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  889. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  890. (p.oper[0]^.reg=p.oper[1]^.reg) then
  891. exit;
  892. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  893. begin
  894. RegReadByInstruction := true;
  895. exit
  896. end;
  897. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  898. begin
  899. RegReadByInstruction := true;
  900. exit
  901. end;
  902. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  903. begin
  904. RegReadByInstruction := true;
  905. exit
  906. end;
  907. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  908. begin
  909. RegReadByInstruction := true;
  910. exit
  911. end;
  912. end;
  913. end;
  914. end;
  915. end;
  916. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  917. begin
  918. result:=false;
  919. if p1.typ<>ait_instruction then
  920. exit;
  921. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  922. exit(true);
  923. if (getregtype(reg)=R_INTREGISTER) and
  924. { change information for xmm movsd are not correct }
  925. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  926. begin
  927. { Handle instructions that behave differently depending on the size and operand count }
  928. case taicpu(p1).opcode of
  929. A_MUL, A_DIV, A_IDIV:
  930. if taicpu(p1).opsize = S_B then
  931. Result := (getsupreg(Reg) = RS_EAX)
  932. else
  933. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  934. A_IMUL:
  935. if taicpu(p1).ops = 1 then
  936. begin
  937. if taicpu(p1).opsize = S_B then
  938. Result := (getsupreg(Reg) = RS_EAX)
  939. else
  940. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  941. end;
  942. { If ops are greater than 1, call inherited method }
  943. else
  944. case getsupreg(reg) of
  945. { RS_EAX = RS_RAX on x86-64 }
  946. RS_EAX:
  947. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  948. RS_ECX:
  949. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  950. RS_EDX:
  951. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  952. RS_EBX:
  953. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  954. RS_ESP:
  955. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  956. RS_EBP:
  957. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_ESI:
  959. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. RS_EDI:
  961. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  962. else
  963. ;
  964. end;
  965. end;
  966. if result then
  967. exit;
  968. end
  969. else if getregtype(reg)=R_MMREGISTER then
  970. begin
  971. case getsupreg(reg) of
  972. RS_XMM0:
  973. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. else
  975. ;
  976. end;
  977. if result then
  978. exit;
  979. end
  980. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  981. begin
  982. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  983. exit(true);
  984. case getsubreg(reg) of
  985. R_SUBFLAGCARRY:
  986. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  987. R_SUBFLAGPARITY:
  988. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  989. R_SUBFLAGAUXILIARY:
  990. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  991. R_SUBFLAGZERO:
  992. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  993. R_SUBFLAGSIGN:
  994. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  995. R_SUBFLAGOVERFLOW:
  996. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGINTERRUPT:
  998. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBFLAGDIRECTION:
  1000. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1001. R_SUBW,R_SUBD,R_SUBQ:
  1002. { Everything except the direction bits }
  1003. Result:=
  1004. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1005. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1006. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1007. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1008. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1009. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1010. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1011. else
  1012. ;
  1013. end;
  1014. if result then
  1015. exit;
  1016. end
  1017. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1018. exit(true);
  1019. Result:=inherited RegInInstruction(Reg, p1);
  1020. end;
  1021. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1022. const
  1023. WriteOps: array[0..3] of set of TInsChange =
  1024. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1025. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1026. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1027. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1028. var
  1029. OperIdx: Integer;
  1030. begin
  1031. Result := False;
  1032. if p1.typ <> ait_instruction then
  1033. exit;
  1034. with insprop[taicpu(p1).opcode] do
  1035. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1036. begin
  1037. case getsubreg(reg) of
  1038. R_SUBW,R_SUBD,R_SUBQ:
  1039. Result :=
  1040. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1041. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1042. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1043. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1044. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1045. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1046. R_SUBFLAGCARRY:
  1047. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1048. R_SUBFLAGPARITY:
  1049. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1050. R_SUBFLAGAUXILIARY:
  1051. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1052. R_SUBFLAGZERO:
  1053. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1054. R_SUBFLAGSIGN:
  1055. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGOVERFLOW:
  1057. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGINTERRUPT:
  1059. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. R_SUBFLAGDIRECTION:
  1061. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1062. else
  1063. internalerror(2017042602);
  1064. end;
  1065. exit;
  1066. end;
  1067. case taicpu(p1).opcode of
  1068. A_CALL:
  1069. { We could potentially set Result to False if the register in
  1070. question is non-volatile for the subroutine's calling convention,
  1071. but this would require detecting the calling convention in use and
  1072. also assuming that the routine doesn't contain malformed assembly
  1073. language, for example... so it could only be done under -O4 as it
  1074. would be considered a side-effect. [Kit] }
  1075. Result := True;
  1076. A_MOVSD:
  1077. { special handling for SSE MOVSD }
  1078. if (taicpu(p1).ops>0) then
  1079. begin
  1080. if taicpu(p1).ops<>2 then
  1081. internalerror(2017042703);
  1082. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1083. end;
  1084. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1085. so fix it here (FK)
  1086. }
  1087. A_VMOVSS,
  1088. A_VMOVSD:
  1089. begin
  1090. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1091. exit;
  1092. end;
  1093. A_MUL, A_DIV, A_IDIV:
  1094. begin
  1095. if taicpu(p1).opsize = S_B then
  1096. Result := (getsupreg(Reg) = RS_EAX)
  1097. else
  1098. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1099. end;
  1100. A_IMUL:
  1101. begin
  1102. if taicpu(p1).ops = 1 then
  1103. begin
  1104. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1105. end
  1106. else
  1107. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1108. Exit;
  1109. end;
  1110. else
  1111. ;
  1112. end;
  1113. if Result then
  1114. exit;
  1115. with insprop[taicpu(p1).opcode] do
  1116. begin
  1117. if getregtype(reg)=R_INTREGISTER then
  1118. begin
  1119. case getsupreg(reg) of
  1120. RS_EAX:
  1121. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1122. begin
  1123. Result := True;
  1124. exit
  1125. end;
  1126. RS_ECX:
  1127. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1128. begin
  1129. Result := True;
  1130. exit
  1131. end;
  1132. RS_EDX:
  1133. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1134. begin
  1135. Result := True;
  1136. exit
  1137. end;
  1138. RS_EBX:
  1139. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1140. begin
  1141. Result := True;
  1142. exit
  1143. end;
  1144. RS_ESP:
  1145. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1146. begin
  1147. Result := True;
  1148. exit
  1149. end;
  1150. RS_EBP:
  1151. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1152. begin
  1153. Result := True;
  1154. exit
  1155. end;
  1156. RS_ESI:
  1157. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1158. begin
  1159. Result := True;
  1160. exit
  1161. end;
  1162. RS_EDI:
  1163. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1164. begin
  1165. Result := True;
  1166. exit
  1167. end;
  1168. end;
  1169. end;
  1170. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1171. if (WriteOps[OperIdx]*Ch<>[]) and
  1172. { The register doesn't get modified inside a reference }
  1173. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1174. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1175. begin
  1176. Result := true;
  1177. exit
  1178. end;
  1179. end;
  1180. end;
  1181. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1182. const
  1183. WriteOps: array[0..3] of set of TInsChange =
  1184. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1185. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1186. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1187. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1188. var
  1189. X: Integer;
  1190. CurrentP1Size: asizeint;
  1191. begin
  1192. Result := (
  1193. (Ref.base <> NR_NO) and
  1194. {$ifdef x86_64}
  1195. (Ref.base <> NR_RIP) and
  1196. {$endif x86_64}
  1197. RegModifiedBetween(Ref.base, p1, p2)
  1198. ) or
  1199. (
  1200. (Ref.index <> NR_NO) and
  1201. (Ref.index <> Ref.base) and
  1202. RegModifiedBetween(Ref.index, p1, p2)
  1203. );
  1204. { Now check to see if the memory itself is written to }
  1205. if not Result then
  1206. begin
  1207. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1208. if p1.typ = ait_instruction then
  1209. begin
  1210. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1211. with insprop[taicpu(p1).opcode] do
  1212. for X := 0 to taicpu(p1).ops - 1 do
  1213. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1214. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1215. { Catch any potential overlaps }
  1216. (
  1217. (RefSize = 0) or
  1218. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1219. ) and
  1220. (
  1221. (CurrentP1Size = 0) or
  1222. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1223. ) and
  1224. { Reference is used, but does the instruction write to it? }
  1225. (
  1226. (Ch_All in Ch) or
  1227. ((WriteOps[X] * Ch) <> [])
  1228. ) then
  1229. begin
  1230. Result := True;
  1231. Break;
  1232. end;
  1233. end;
  1234. end;
  1235. end;
  1236. {$ifdef DEBUG_AOPTCPU}
  1237. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1238. begin
  1239. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1240. end;
  1241. function debug_tostr(i: tcgint): string; inline;
  1242. begin
  1243. Result := tostr(i);
  1244. end;
  1245. function debug_hexstr(i: tcgint): string;
  1246. begin
  1247. Result := '0x';
  1248. case i of
  1249. 0..$FF:
  1250. Result := Result + hexstr(i, 2);
  1251. $100..$FFFF:
  1252. Result := Result + hexstr(i, 4);
  1253. $10000..$FFFFFF:
  1254. Result := Result + hexstr(i, 6);
  1255. $1000000..$FFFFFFFF:
  1256. Result := Result + hexstr(i, 8);
  1257. else
  1258. Result := Result + hexstr(i, 16);
  1259. end;
  1260. end;
  1261. function debug_regname(r: TRegister): string; inline;
  1262. begin
  1263. Result := '%' + std_regname(r);
  1264. end;
  1265. { Debug output function - creates a string representation of an operator }
  1266. function debug_operstr(oper: TOper): string;
  1267. begin
  1268. case oper.typ of
  1269. top_const:
  1270. Result := '$' + debug_tostr(oper.val);
  1271. top_reg:
  1272. Result := debug_regname(oper.reg);
  1273. top_ref:
  1274. begin
  1275. if oper.ref^.offset <> 0 then
  1276. Result := debug_tostr(oper.ref^.offset) + '('
  1277. else
  1278. Result := '(';
  1279. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1280. begin
  1281. Result := Result + debug_regname(oper.ref^.base);
  1282. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1283. Result := Result + ',' + debug_regname(oper.ref^.index);
  1284. end
  1285. else
  1286. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1287. Result := Result + debug_regname(oper.ref^.index);
  1288. if (oper.ref^.scalefactor > 1) then
  1289. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1290. else
  1291. Result := Result + ')';
  1292. end;
  1293. else
  1294. Result := '[UNKNOWN]';
  1295. end;
  1296. end;
  1297. function debug_op2str(opcode: tasmop): string; inline;
  1298. begin
  1299. Result := std_op2str[opcode];
  1300. end;
  1301. function debug_opsize2str(opsize: topsize): string; inline;
  1302. begin
  1303. Result := gas_opsize2str[opsize];
  1304. end;
  1305. {$else DEBUG_AOPTCPU}
  1306. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1307. begin
  1308. end;
  1309. function debug_tostr(i: tcgint): string; inline;
  1310. begin
  1311. Result := '';
  1312. end;
  1313. function debug_hexstr(i: tcgint): string; inline;
  1314. begin
  1315. Result := '';
  1316. end;
  1317. function debug_regname(r: TRegister): string; inline;
  1318. begin
  1319. Result := '';
  1320. end;
  1321. function debug_operstr(oper: TOper): string; inline;
  1322. begin
  1323. Result := '';
  1324. end;
  1325. function debug_op2str(opcode: tasmop): string; inline;
  1326. begin
  1327. Result := '';
  1328. end;
  1329. function debug_opsize2str(opsize: topsize): string; inline;
  1330. begin
  1331. Result := '';
  1332. end;
  1333. {$endif DEBUG_AOPTCPU}
  1334. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1335. begin
  1336. {$ifdef x86_64}
  1337. { Always fine on x86-64 }
  1338. Result := True;
  1339. {$else x86_64}
  1340. Result :=
  1341. {$ifdef i8086}
  1342. (current_settings.cputype >= cpu_386) and
  1343. {$endif i8086}
  1344. (
  1345. { Always accept if optimising for size }
  1346. (cs_opt_size in current_settings.optimizerswitches) or
  1347. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1348. (current_settings.optimizecputype >= cpu_Pentium2)
  1349. );
  1350. {$endif x86_64}
  1351. end;
  1352. { Attempts to allocate a volatile integer register for use between p and hp,
  1353. using AUsedRegs for the current register usage information. Returns NR_NO
  1354. if no free register could be found }
  1355. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1356. var
  1357. RegSet: TCPURegisterSet;
  1358. CurrentSuperReg: Integer;
  1359. CurrentReg: TRegister;
  1360. Currentp: tai;
  1361. Breakout: Boolean;
  1362. begin
  1363. Result := NR_NO;
  1364. RegSet :=
  1365. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1366. current_procinfo.saved_regs_int;
  1367. (*
  1368. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1369. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1370. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1371. *)
  1372. for CurrentSuperReg in RegSet do
  1373. begin
  1374. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1375. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1376. {$if defined(i386) or defined(i8086)}
  1377. { If the target size is 8-bit, make sure we can actually encode it }
  1378. and (
  1379. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1380. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1381. )
  1382. {$endif i386 or i8086}
  1383. then
  1384. begin
  1385. Currentp := p;
  1386. Breakout := False;
  1387. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1388. begin
  1389. case Currentp.typ of
  1390. ait_instruction:
  1391. begin
  1392. if RegInInstruction(CurrentReg, Currentp) then
  1393. begin
  1394. Breakout := True;
  1395. Break;
  1396. end;
  1397. { Cannot allocate across an unconditional jump }
  1398. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1399. Exit;
  1400. end;
  1401. ait_marker:
  1402. { Don't try anything more if a marker is hit }
  1403. Exit;
  1404. ait_regalloc:
  1405. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1406. begin
  1407. Breakout := True;
  1408. Break;
  1409. end;
  1410. else
  1411. ;
  1412. end;
  1413. end;
  1414. if Breakout then
  1415. { Try the next register }
  1416. Continue;
  1417. { We have a free register available }
  1418. Result := CurrentReg;
  1419. if not DontAlloc then
  1420. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1421. Exit;
  1422. end;
  1423. end;
  1424. end;
  1425. { Attempts to allocate a volatile MM register for use between p and hp,
  1426. using AUsedRegs for the current register usage information. Returns NR_NO
  1427. if no free register could be found }
  1428. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1429. var
  1430. RegSet: TCPURegisterSet;
  1431. CurrentSuperReg: Integer;
  1432. CurrentReg: TRegister;
  1433. Currentp: tai;
  1434. Breakout: Boolean;
  1435. begin
  1436. Result := NR_NO;
  1437. RegSet :=
  1438. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1439. current_procinfo.saved_regs_mm;
  1440. for CurrentSuperReg in RegSet do
  1441. begin
  1442. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1443. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1444. begin
  1445. Currentp := p;
  1446. Breakout := False;
  1447. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1448. begin
  1449. case Currentp.typ of
  1450. ait_instruction:
  1451. begin
  1452. if RegInInstruction(CurrentReg, Currentp) then
  1453. begin
  1454. Breakout := True;
  1455. Break;
  1456. end;
  1457. { Cannot allocate across an unconditional jump }
  1458. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1459. Exit;
  1460. end;
  1461. ait_marker:
  1462. { Don't try anything more if a marker is hit }
  1463. Exit;
  1464. ait_regalloc:
  1465. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1466. begin
  1467. Breakout := True;
  1468. Break;
  1469. end;
  1470. else
  1471. ;
  1472. end;
  1473. end;
  1474. if Breakout then
  1475. { Try the next register }
  1476. Continue;
  1477. { We have a free register available }
  1478. Result := CurrentReg;
  1479. if not DontAlloc then
  1480. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1481. Exit;
  1482. end;
  1483. end;
  1484. end;
  1485. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1486. begin
  1487. if not SuperRegistersEqual(reg1,reg2) then
  1488. exit(false);
  1489. if getregtype(reg1)<>R_INTREGISTER then
  1490. exit(true); {because SuperRegisterEqual is true}
  1491. case getsubreg(reg1) of
  1492. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1493. higher, it preserves the high bits, so the new value depends on
  1494. reg2's previous value. In other words, it is equivalent to doing:
  1495. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1496. R_SUBL:
  1497. exit(getsubreg(reg2)=R_SUBL);
  1498. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1499. higher, it actually does a:
  1500. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1501. R_SUBH:
  1502. exit(getsubreg(reg2)=R_SUBH);
  1503. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1504. bits of reg2:
  1505. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1506. R_SUBW:
  1507. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1508. { a write to R_SUBD always overwrites every other subregister,
  1509. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1510. R_SUBD,
  1511. R_SUBQ:
  1512. exit(true);
  1513. else
  1514. internalerror(2017042801);
  1515. end;
  1516. end;
  1517. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1518. begin
  1519. if not SuperRegistersEqual(reg1,reg2) then
  1520. exit(false);
  1521. if getregtype(reg1)<>R_INTREGISTER then
  1522. exit(true); {because SuperRegisterEqual is true}
  1523. case getsubreg(reg1) of
  1524. R_SUBL:
  1525. exit(getsubreg(reg2)<>R_SUBH);
  1526. R_SUBH:
  1527. exit(getsubreg(reg2)<>R_SUBL);
  1528. R_SUBW,
  1529. R_SUBD,
  1530. R_SUBQ:
  1531. exit(true);
  1532. else
  1533. internalerror(2017042802);
  1534. end;
  1535. end;
  1536. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1537. var
  1538. hp1 : tai;
  1539. l : TCGInt;
  1540. begin
  1541. result:=false;
  1542. if not(GetNextInstruction(p, hp1)) then
  1543. exit;
  1544. { changes the code sequence
  1545. shr/sar const1, x
  1546. shl const2, x
  1547. to
  1548. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1549. if (taicpu(p).oper[0]^.typ = top_const) and
  1550. MatchInstruction(hp1,A_SHL,[]) and
  1551. (taicpu(hp1).oper[0]^.typ = top_const) and
  1552. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1553. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1554. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1555. begin
  1556. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1557. not(cs_opt_size in current_settings.optimizerswitches)
  1558. {$ifdef x86_64}
  1559. and (
  1560. (taicpu(p).opsize <> S_Q) or
  1561. { 64-bit AND can only store signed 32-bit immediates }
  1562. (taicpu(p).oper[0]^.val < 32)
  1563. )
  1564. {$endif x86_64}
  1565. then
  1566. begin
  1567. { shr/sar const1, %reg
  1568. shl const2, %reg
  1569. with const1 > const2 }
  1570. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1571. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1572. taicpu(hp1).opcode := A_AND;
  1573. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1574. case taicpu(p).opsize Of
  1575. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1576. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1577. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1578. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1579. else
  1580. Internalerror(2017050703)
  1581. end;
  1582. end
  1583. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1584. not(cs_opt_size in current_settings.optimizerswitches)
  1585. {$ifdef x86_64}
  1586. and (
  1587. (taicpu(p).opsize <> S_Q) or
  1588. { 64-bit AND can only store signed 32-bit immediates }
  1589. (taicpu(p).oper[0]^.val < 32)
  1590. )
  1591. {$endif x86_64}
  1592. then
  1593. begin
  1594. { shr/sar const1, %reg
  1595. shl const2, %reg
  1596. with const1 < const2 }
  1597. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1598. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1599. taicpu(p).opcode := A_AND;
  1600. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1601. case taicpu(p).opsize Of
  1602. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1603. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1604. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1605. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1606. else
  1607. Internalerror(2017050702)
  1608. end;
  1609. end
  1610. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1611. {$ifdef x86_64}
  1612. and (
  1613. (taicpu(p).opsize <> S_Q) or
  1614. { 64-bit AND can only store signed 32-bit immediates }
  1615. (taicpu(p).oper[0]^.val < 32)
  1616. )
  1617. {$endif x86_64}
  1618. then
  1619. begin
  1620. { shr/sar const1, %reg
  1621. shl const2, %reg
  1622. with const1 = const2 }
  1623. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1624. taicpu(p).opcode := A_AND;
  1625. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1626. case taicpu(p).opsize Of
  1627. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1628. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1629. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1630. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1631. else
  1632. Internalerror(2017050701)
  1633. end;
  1634. RemoveInstruction(hp1);
  1635. end;
  1636. end;
  1637. end;
  1638. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1639. var
  1640. opsize : topsize;
  1641. hp1, hp2 : tai;
  1642. tmpref : treference;
  1643. ShiftValue : Cardinal;
  1644. BaseValue : TCGInt;
  1645. begin
  1646. result:=false;
  1647. opsize:=taicpu(p).opsize;
  1648. { changes certain "imul const, %reg"'s to lea sequences }
  1649. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1650. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1651. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1652. if (taicpu(p).oper[0]^.val = 1) then
  1653. if (taicpu(p).ops = 2) then
  1654. { remove "imul $1, reg" }
  1655. begin
  1656. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1657. Result := RemoveCurrentP(p);
  1658. end
  1659. else
  1660. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1661. begin
  1662. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1663. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1664. asml.InsertAfter(hp1, p);
  1665. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1666. RemoveCurrentP(p, hp1);
  1667. Result := True;
  1668. end
  1669. else if ((taicpu(p).ops <= 2) or
  1670. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1671. not(cs_opt_size in current_settings.optimizerswitches) and
  1672. (not(GetNextInstruction(p, hp1)) or
  1673. not((tai(hp1).typ = ait_instruction) and
  1674. ((taicpu(hp1).opcode=A_Jcc) and
  1675. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1676. begin
  1677. {
  1678. imul X, reg1, reg2 to
  1679. lea (reg1,reg1,Y), reg2
  1680. shl ZZ,reg2
  1681. imul XX, reg1 to
  1682. lea (reg1,reg1,YY), reg1
  1683. shl ZZ,reg2
  1684. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1685. it does not exist as a separate optimization target in FPC though.
  1686. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1687. at most two zeros
  1688. }
  1689. reference_reset(tmpref,1,[]);
  1690. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1691. begin
  1692. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1693. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1694. TmpRef.base := taicpu(p).oper[1]^.reg;
  1695. TmpRef.index := taicpu(p).oper[1]^.reg;
  1696. if not(BaseValue in [3,5,9]) then
  1697. Internalerror(2018110101);
  1698. TmpRef.ScaleFactor := BaseValue-1;
  1699. if (taicpu(p).ops = 2) then
  1700. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1701. else
  1702. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1703. AsmL.InsertAfter(hp1,p);
  1704. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1705. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1706. RemoveCurrentP(p, hp1);
  1707. if ShiftValue>0 then
  1708. begin
  1709. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1710. AsmL.InsertAfter(hp2,hp1);
  1711. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1712. end;
  1713. Result := True;
  1714. end;
  1715. end;
  1716. end;
  1717. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1718. begin
  1719. Result := False;
  1720. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1721. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1722. begin
  1723. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1724. taicpu(p).opcode := A_MOV;
  1725. Result := True;
  1726. end;
  1727. end;
  1728. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1729. var
  1730. p: taicpu absolute hp; { Implicit typecast }
  1731. i: Integer;
  1732. begin
  1733. Result := False;
  1734. if not assigned(hp) or
  1735. (hp.typ <> ait_instruction) then
  1736. Exit;
  1737. Prefetch(insprop[p.opcode]);
  1738. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1739. with insprop[p.opcode] do
  1740. begin
  1741. case getsubreg(reg) of
  1742. R_SUBW,R_SUBD,R_SUBQ:
  1743. Result:=
  1744. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1745. uncommon flags are checked first }
  1746. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1747. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1748. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1749. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1750. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1751. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1752. R_SUBFLAGCARRY:
  1753. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1754. R_SUBFLAGPARITY:
  1755. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1756. R_SUBFLAGAUXILIARY:
  1757. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1758. R_SUBFLAGZERO:
  1759. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1760. R_SUBFLAGSIGN:
  1761. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1762. R_SUBFLAGOVERFLOW:
  1763. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1764. R_SUBFLAGINTERRUPT:
  1765. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1766. R_SUBFLAGDIRECTION:
  1767. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1768. else
  1769. internalerror(2017050501);
  1770. end;
  1771. exit;
  1772. end;
  1773. { Handle special cases first }
  1774. case p.opcode of
  1775. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1776. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1777. begin
  1778. Result :=
  1779. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1780. (p.oper[1]^.typ = top_reg) and
  1781. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1782. (
  1783. (p.oper[0]^.typ = top_const) or
  1784. (
  1785. (p.oper[0]^.typ = top_reg) and
  1786. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1787. ) or (
  1788. (p.oper[0]^.typ = top_ref) and
  1789. not RegInRef(reg,p.oper[0]^.ref^)
  1790. )
  1791. );
  1792. end;
  1793. A_MUL, A_IMUL:
  1794. Result :=
  1795. (
  1796. (p.ops=3) and { IMUL only }
  1797. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1798. (
  1799. (
  1800. (p.oper[1]^.typ=top_reg) and
  1801. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1802. ) or (
  1803. (p.oper[1]^.typ=top_ref) and
  1804. not RegInRef(reg,p.oper[1]^.ref^)
  1805. )
  1806. )
  1807. ) or (
  1808. (
  1809. (p.ops=1) and
  1810. (
  1811. (
  1812. (
  1813. (p.oper[0]^.typ=top_reg) and
  1814. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1815. )
  1816. ) or (
  1817. (p.oper[0]^.typ=top_ref) and
  1818. not RegInRef(reg,p.oper[0]^.ref^)
  1819. )
  1820. ) and (
  1821. (
  1822. (p.opsize=S_B) and
  1823. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1824. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1825. ) or (
  1826. (p.opsize=S_W) and
  1827. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1828. ) or (
  1829. (p.opsize=S_L) and
  1830. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1831. {$ifdef x86_64}
  1832. ) or (
  1833. (p.opsize=S_Q) and
  1834. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1835. {$endif x86_64}
  1836. )
  1837. )
  1838. )
  1839. );
  1840. A_CBW:
  1841. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1842. {$ifndef x86_64}
  1843. A_LDS:
  1844. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1845. A_LES:
  1846. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1847. {$endif not x86_64}
  1848. A_LFS:
  1849. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1850. A_LGS:
  1851. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1852. A_LSS:
  1853. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1854. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1855. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1856. A_LODSB:
  1857. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1858. A_LODSW:
  1859. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1860. {$ifdef x86_64}
  1861. A_LODSQ:
  1862. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1863. {$endif x86_64}
  1864. A_LODSD:
  1865. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1866. A_FSTSW, A_FNSTSW:
  1867. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1868. else
  1869. begin
  1870. with insprop[p.opcode] do
  1871. begin
  1872. if (
  1873. { xor %reg,%reg etc. is classed as a new value }
  1874. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1875. MatchOpType(p, top_reg, top_reg) and
  1876. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1877. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1878. ) then
  1879. begin
  1880. Result := True;
  1881. Exit;
  1882. end;
  1883. { Make sure the entire register is overwritten }
  1884. if (getregtype(reg) = R_INTREGISTER) then
  1885. begin
  1886. if (p.ops > 0) then
  1887. begin
  1888. if RegInOp(reg, p.oper[0]^) then
  1889. begin
  1890. if (p.oper[0]^.typ = top_ref) then
  1891. begin
  1892. if RegInRef(reg, p.oper[0]^.ref^) then
  1893. begin
  1894. Result := False;
  1895. Exit;
  1896. end;
  1897. end
  1898. else if (p.oper[0]^.typ = top_reg) then
  1899. begin
  1900. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1901. begin
  1902. Result := False;
  1903. Exit;
  1904. end
  1905. else if ([Ch_WOp1]*Ch<>[]) then
  1906. begin
  1907. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1908. Result := True
  1909. else
  1910. begin
  1911. Result := False;
  1912. Exit;
  1913. end;
  1914. end;
  1915. end;
  1916. end;
  1917. if (p.ops > 1) then
  1918. begin
  1919. if RegInOp(reg, p.oper[1]^) then
  1920. begin
  1921. if (p.oper[1]^.typ = top_ref) then
  1922. begin
  1923. if RegInRef(reg, p.oper[1]^.ref^) then
  1924. begin
  1925. Result := False;
  1926. Exit;
  1927. end;
  1928. end
  1929. else if (p.oper[1]^.typ = top_reg) then
  1930. begin
  1931. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1932. begin
  1933. Result := False;
  1934. Exit;
  1935. end
  1936. else if ([Ch_WOp2]*Ch<>[]) then
  1937. begin
  1938. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1939. Result := True
  1940. else
  1941. begin
  1942. Result := False;
  1943. Exit;
  1944. end;
  1945. end;
  1946. end;
  1947. end;
  1948. if (p.ops > 2) then
  1949. begin
  1950. if RegInOp(reg, p.oper[2]^) then
  1951. begin
  1952. if (p.oper[2]^.typ = top_ref) then
  1953. begin
  1954. if RegInRef(reg, p.oper[2]^.ref^) then
  1955. begin
  1956. Result := False;
  1957. Exit;
  1958. end;
  1959. end
  1960. else if (p.oper[2]^.typ = top_reg) then
  1961. begin
  1962. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1963. begin
  1964. Result := False;
  1965. Exit;
  1966. end
  1967. else if ([Ch_WOp3]*Ch<>[]) then
  1968. begin
  1969. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1970. Result := True
  1971. else
  1972. begin
  1973. Result := False;
  1974. Exit;
  1975. end;
  1976. end;
  1977. end;
  1978. end;
  1979. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1980. begin
  1981. if (p.oper[3]^.typ = top_ref) then
  1982. begin
  1983. if RegInRef(reg, p.oper[3]^.ref^) then
  1984. begin
  1985. Result := False;
  1986. Exit;
  1987. end;
  1988. end
  1989. else if (p.oper[3]^.typ = top_reg) then
  1990. begin
  1991. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1992. begin
  1993. Result := False;
  1994. Exit;
  1995. end
  1996. else if ([Ch_WOp4]*Ch<>[]) then
  1997. begin
  1998. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1999. Result := True
  2000. else
  2001. begin
  2002. Result := False;
  2003. Exit;
  2004. end;
  2005. end;
  2006. end;
  2007. end;
  2008. end;
  2009. end;
  2010. end;
  2011. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2012. case getsupreg(reg) of
  2013. RS_EAX:
  2014. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2015. begin
  2016. Result := True;
  2017. Exit;
  2018. end;
  2019. RS_ECX:
  2020. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2021. begin
  2022. Result := True;
  2023. Exit;
  2024. end;
  2025. RS_EDX:
  2026. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2027. begin
  2028. Result := True;
  2029. Exit;
  2030. end;
  2031. RS_EBX:
  2032. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2033. begin
  2034. Result := True;
  2035. Exit;
  2036. end;
  2037. RS_ESP:
  2038. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2039. begin
  2040. Result := True;
  2041. Exit;
  2042. end;
  2043. RS_EBP:
  2044. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2045. begin
  2046. Result := True;
  2047. Exit;
  2048. end;
  2049. RS_ESI:
  2050. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2051. begin
  2052. Result := True;
  2053. Exit;
  2054. end;
  2055. RS_EDI:
  2056. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2057. begin
  2058. Result := True;
  2059. Exit;
  2060. end;
  2061. else
  2062. ;
  2063. end;
  2064. end;
  2065. end;
  2066. end;
  2067. end;
  2068. end;
  2069. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2070. var
  2071. hp2,hp3 : tai;
  2072. begin
  2073. { some x86-64 issue a NOP before the real exit code }
  2074. if MatchInstruction(p,A_NOP,[]) then
  2075. GetNextInstruction(p,p);
  2076. result:=assigned(p) and (p.typ=ait_instruction) and
  2077. ((taicpu(p).opcode = A_RET) or
  2078. ((taicpu(p).opcode=A_LEAVE) and
  2079. GetNextInstruction(p,hp2) and
  2080. MatchInstruction(hp2,A_RET,[S_NO])
  2081. ) or
  2082. (((taicpu(p).opcode=A_LEA) and
  2083. MatchOpType(taicpu(p),top_ref,top_reg) and
  2084. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2085. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2086. ) and
  2087. GetNextInstruction(p,hp2) and
  2088. MatchInstruction(hp2,A_RET,[S_NO])
  2089. ) or
  2090. ((((taicpu(p).opcode=A_MOV) and
  2091. MatchOpType(taicpu(p),top_reg,top_reg) and
  2092. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2093. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2094. ((taicpu(p).opcode=A_LEA) and
  2095. MatchOpType(taicpu(p),top_ref,top_reg) and
  2096. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2097. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2098. )
  2099. ) and
  2100. GetNextInstruction(p,hp2) and
  2101. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2102. MatchOpType(taicpu(hp2),top_reg) and
  2103. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2104. GetNextInstruction(hp2,hp3) and
  2105. MatchInstruction(hp3,A_RET,[S_NO])
  2106. )
  2107. );
  2108. end;
  2109. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2110. begin
  2111. isFoldableArithOp := False;
  2112. case hp1.opcode of
  2113. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2114. isFoldableArithOp :=
  2115. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2116. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2117. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2118. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2119. (taicpu(hp1).oper[1]^.reg = reg);
  2120. A_INC,A_DEC,A_NEG,A_NOT:
  2121. isFoldableArithOp :=
  2122. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2123. (taicpu(hp1).oper[0]^.reg = reg);
  2124. else
  2125. ;
  2126. end;
  2127. end;
  2128. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2129. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2130. var
  2131. hp2: tai;
  2132. begin
  2133. hp2 := p;
  2134. repeat
  2135. hp2 := tai(hp2.previous);
  2136. if assigned(hp2) and
  2137. (hp2.typ = ait_regalloc) and
  2138. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2139. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2140. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2141. begin
  2142. RemoveInstruction(hp2);
  2143. break;
  2144. end;
  2145. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2146. end;
  2147. begin
  2148. case current_procinfo.procdef.returndef.typ of
  2149. arraydef,recorddef,pointerdef,
  2150. stringdef,enumdef,procdef,objectdef,errordef,
  2151. filedef,setdef,procvardef,
  2152. classrefdef,forwarddef:
  2153. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2154. orddef:
  2155. if current_procinfo.procdef.returndef.size <> 0 then
  2156. begin
  2157. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2158. { for int64/qword }
  2159. if current_procinfo.procdef.returndef.size = 8 then
  2160. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2161. end;
  2162. else
  2163. ;
  2164. end;
  2165. end;
  2166. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2167. var
  2168. hp1: tai;
  2169. operswap: poper;
  2170. begin
  2171. Result := False;
  2172. { Optimise:
  2173. cmov(c) %reg1,%reg2
  2174. mov %reg2,%reg1
  2175. (%reg2 dealloc.)
  2176. To:
  2177. cmov(~c) %reg2,%reg1
  2178. }
  2179. if (taicpu(p).oper[0]^.typ = top_reg) then
  2180. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2181. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2182. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2183. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2184. begin
  2185. TransferUsedRegs(TmpUsedRegs);
  2186. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2187. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2188. begin
  2189. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2190. { Save time by swapping the pointers (they're both registers, so
  2191. we don't need to worry about reference counts) }
  2192. operswap := taicpu(p).oper[0];
  2193. taicpu(p).oper[0] := taicpu(p).oper[1];
  2194. taicpu(p).oper[1] := operswap;
  2195. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2196. RemoveInstruction(hp1);
  2197. { It's still a CMOV, so we can look further ahead }
  2198. Include(OptsToCheck, aoc_ForceNewIteration);
  2199. { But first, let's see if this will get optimised again
  2200. (probably won't happen, but best to be sure) }
  2201. Continue;
  2202. end;
  2203. Break;
  2204. end;
  2205. end;
  2206. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2207. var
  2208. hp1,hp2 : tai;
  2209. begin
  2210. result:=false;
  2211. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2212. begin
  2213. { vmova* reg1,reg1
  2214. =>
  2215. <nop> }
  2216. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2217. begin
  2218. RemoveCurrentP(p);
  2219. result:=true;
  2220. exit;
  2221. end;
  2222. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2223. (hp1.typ = ait_instruction) and
  2224. (
  2225. { Under -O2 and below, the instructions are always adjacent }
  2226. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2227. (taicpu(hp1).ops <= 1) or
  2228. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2229. { If reg1 = reg3, reg1 must not be modified in between }
  2230. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2231. ) then
  2232. begin
  2233. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2234. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2235. begin
  2236. { vmova* reg1,reg2
  2237. ...
  2238. vmova* reg2,reg3
  2239. dealloc reg2
  2240. =>
  2241. vmova* reg1,reg3 }
  2242. TransferUsedRegs(TmpUsedRegs);
  2243. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2244. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2245. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2246. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2247. begin
  2248. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2249. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2250. TransferUsedRegs(TmpUsedRegs);
  2251. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2252. RemoveInstruction(hp1);
  2253. result:=true;
  2254. exit;
  2255. end;
  2256. { special case:
  2257. vmova* reg1,<op>
  2258. ...
  2259. vmova* <op>,reg1
  2260. =>
  2261. vmova* reg1,<op> }
  2262. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2263. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2264. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2265. ) then
  2266. begin
  2267. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2268. RemoveInstruction(hp1);
  2269. result:=true;
  2270. exit;
  2271. end
  2272. end
  2273. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2274. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2275. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2276. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2277. ) and
  2278. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2279. begin
  2280. { vmova* reg1,reg2
  2281. ...
  2282. vmovs* reg2,<op>
  2283. dealloc reg2
  2284. =>
  2285. vmovs* reg1,<op> }
  2286. TransferUsedRegs(TmpUsedRegs);
  2287. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2288. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2289. begin
  2290. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2291. taicpu(p).opcode:=taicpu(hp1).opcode;
  2292. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2293. TransferUsedRegs(TmpUsedRegs);
  2294. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2295. RemoveInstruction(hp1);
  2296. result:=true;
  2297. exit;
  2298. end
  2299. end;
  2300. if MatchInstruction(hp1,[A_VFMADDPD,
  2301. A_VFMADD132PD,
  2302. A_VFMADD132PS,
  2303. A_VFMADD132SD,
  2304. A_VFMADD132SS,
  2305. A_VFMADD213PD,
  2306. A_VFMADD213PS,
  2307. A_VFMADD213SD,
  2308. A_VFMADD213SS,
  2309. A_VFMADD231PD,
  2310. A_VFMADD231PS,
  2311. A_VFMADD231SD,
  2312. A_VFMADD231SS,
  2313. A_VFMADDSUB132PD,
  2314. A_VFMADDSUB132PS,
  2315. A_VFMADDSUB213PD,
  2316. A_VFMADDSUB213PS,
  2317. A_VFMADDSUB231PD,
  2318. A_VFMADDSUB231PS,
  2319. A_VFMSUB132PD,
  2320. A_VFMSUB132PS,
  2321. A_VFMSUB132SD,
  2322. A_VFMSUB132SS,
  2323. A_VFMSUB213PD,
  2324. A_VFMSUB213PS,
  2325. A_VFMSUB213SD,
  2326. A_VFMSUB213SS,
  2327. A_VFMSUB231PD,
  2328. A_VFMSUB231PS,
  2329. A_VFMSUB231SD,
  2330. A_VFMSUB231SS,
  2331. A_VFMSUBADD132PD,
  2332. A_VFMSUBADD132PS,
  2333. A_VFMSUBADD213PD,
  2334. A_VFMSUBADD213PS,
  2335. A_VFMSUBADD231PD,
  2336. A_VFMSUBADD231PS,
  2337. A_VFNMADD132PD,
  2338. A_VFNMADD132PS,
  2339. A_VFNMADD132SD,
  2340. A_VFNMADD132SS,
  2341. A_VFNMADD213PD,
  2342. A_VFNMADD213PS,
  2343. A_VFNMADD213SD,
  2344. A_VFNMADD213SS,
  2345. A_VFNMADD231PD,
  2346. A_VFNMADD231PS,
  2347. A_VFNMADD231SD,
  2348. A_VFNMADD231SS,
  2349. A_VFNMSUB132PD,
  2350. A_VFNMSUB132PS,
  2351. A_VFNMSUB132SD,
  2352. A_VFNMSUB132SS,
  2353. A_VFNMSUB213PD,
  2354. A_VFNMSUB213PS,
  2355. A_VFNMSUB213SD,
  2356. A_VFNMSUB213SS,
  2357. A_VFNMSUB231PD,
  2358. A_VFNMSUB231PS,
  2359. A_VFNMSUB231SD,
  2360. A_VFNMSUB231SS],[S_NO]) and
  2361. { we mix single and double opperations here because we assume that the compiler
  2362. generates vmovapd only after double operations and vmovaps only after single operations }
  2363. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2364. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2365. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2366. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2367. begin
  2368. TransferUsedRegs(TmpUsedRegs);
  2369. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2370. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2371. begin
  2372. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2373. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2374. RemoveCurrentP(p)
  2375. else
  2376. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2377. RemoveInstruction(hp2);
  2378. end;
  2379. end
  2380. else if (hp1.typ = ait_instruction) and
  2381. (((taicpu(p).opcode=A_MOVAPS) and
  2382. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2383. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2384. ((taicpu(p).opcode=A_MOVAPD) and
  2385. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2386. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2387. ) and
  2388. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2389. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2390. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2391. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2392. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2393. { change
  2394. movapX reg,reg2
  2395. addsX/subsX/... reg3, reg2
  2396. movapX reg2,reg
  2397. to
  2398. addsX/subsX/... reg3,reg
  2399. }
  2400. begin
  2401. TransferUsedRegs(TmpUsedRegs);
  2402. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2403. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2404. begin
  2405. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2406. debug_op2str(taicpu(p).opcode)+' '+
  2407. debug_op2str(taicpu(hp1).opcode)+' '+
  2408. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2409. { we cannot eliminate the first move if
  2410. the operations uses the same register for source and dest }
  2411. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2412. { Remember that hp1 is not necessarily the immediate
  2413. next instruction }
  2414. RemoveCurrentP(p);
  2415. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2416. RemoveInstruction(hp2);
  2417. result:=true;
  2418. end;
  2419. end
  2420. else if (hp1.typ = ait_instruction) and
  2421. (((taicpu(p).opcode=A_VMOVAPD) and
  2422. (taicpu(hp1).opcode=A_VCOMISD)) or
  2423. ((taicpu(p).opcode=A_VMOVAPS) and
  2424. ((taicpu(hp1).opcode=A_VCOMISS))
  2425. )
  2426. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2427. { change
  2428. movapX reg,reg1
  2429. vcomisX reg1,reg1
  2430. to
  2431. vcomisX reg,reg
  2432. }
  2433. begin
  2434. TransferUsedRegs(TmpUsedRegs);
  2435. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2436. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2437. begin
  2438. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2439. debug_op2str(taicpu(p).opcode)+' '+
  2440. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2441. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2442. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2443. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2444. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2445. RemoveCurrentP(p);
  2446. result:=true;
  2447. exit;
  2448. end;
  2449. end
  2450. end;
  2451. end;
  2452. end;
  2453. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2454. var
  2455. hp1 : tai;
  2456. begin
  2457. result:=false;
  2458. { replace
  2459. V<Op>X %mreg1,%mreg2,%mreg3
  2460. VMovX %mreg3,%mreg4
  2461. dealloc %mreg3
  2462. by
  2463. V<Op>X %mreg1,%mreg2,%mreg4
  2464. ?
  2465. }
  2466. if GetNextInstruction(p,hp1) and
  2467. { we mix single and double operations here because we assume that the compiler
  2468. generates vmovapd only after double operations and vmovaps only after single operations }
  2469. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2470. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2471. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2472. begin
  2473. TransferUsedRegs(TmpUsedRegs);
  2474. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2475. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2476. begin
  2477. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2478. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2479. RemoveInstruction(hp1);
  2480. result:=true;
  2481. end;
  2482. end;
  2483. end;
  2484. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2485. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2486. begin
  2487. Result := False;
  2488. { For safety reasons, only check for exact register matches }
  2489. { Check base register }
  2490. if (ref.base = AOldReg) then
  2491. begin
  2492. ref.base := ANewReg;
  2493. Result := True;
  2494. end;
  2495. { Check index register }
  2496. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2497. begin
  2498. ref.index := ANewReg;
  2499. Result := True;
  2500. end;
  2501. end;
  2502. { Replaces all references to AOldReg in an operand to ANewReg }
  2503. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2504. var
  2505. OldSupReg, NewSupReg: TSuperRegister;
  2506. OldSubReg, NewSubReg: TSubRegister;
  2507. OldRegType: TRegisterType;
  2508. ThisOper: POper;
  2509. begin
  2510. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2511. Result := False;
  2512. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2513. InternalError(2020011801);
  2514. OldSupReg := getsupreg(AOldReg);
  2515. OldSubReg := getsubreg(AOldReg);
  2516. OldRegType := getregtype(AOldReg);
  2517. NewSupReg := getsupreg(ANewReg);
  2518. NewSubReg := getsubreg(ANewReg);
  2519. if OldRegType <> getregtype(ANewReg) then
  2520. InternalError(2020011802);
  2521. if OldSubReg <> NewSubReg then
  2522. InternalError(2020011803);
  2523. case ThisOper^.typ of
  2524. top_reg:
  2525. if (
  2526. (ThisOper^.reg = AOldReg) or
  2527. (
  2528. (OldRegType = R_INTREGISTER) and
  2529. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2530. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2531. (
  2532. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2533. {$ifndef x86_64}
  2534. and (
  2535. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2536. don't have an 8-bit representation }
  2537. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2538. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2539. )
  2540. {$endif x86_64}
  2541. )
  2542. )
  2543. ) then
  2544. begin
  2545. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2546. Result := True;
  2547. end;
  2548. top_ref:
  2549. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2550. Result := True;
  2551. else
  2552. ;
  2553. end;
  2554. end;
  2555. { Replaces all references to AOldReg in an instruction to ANewReg }
  2556. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2557. const
  2558. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2559. var
  2560. OperIdx: Integer;
  2561. begin
  2562. Result := False;
  2563. for OperIdx := 0 to p.ops - 1 do
  2564. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2565. begin
  2566. { The shift and rotate instructions can only use CL }
  2567. if not (
  2568. (OperIdx = 0) and
  2569. { This second condition just helps to avoid unnecessarily
  2570. calling MatchInstruction for 10 different opcodes }
  2571. (p.oper[0]^.reg = NR_CL) and
  2572. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2573. ) then
  2574. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2575. end
  2576. else if p.oper[OperIdx]^.typ = top_ref then
  2577. { It's okay to replace registers in references that get written to }
  2578. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2579. end;
  2580. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2581. begin
  2582. Result :=
  2583. (ref^.index = NR_NO) and
  2584. (
  2585. {$ifdef x86_64}
  2586. (
  2587. (ref^.base = NR_RIP) and
  2588. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2589. ) or
  2590. {$endif x86_64}
  2591. (ref^.refaddr = addr_full) or
  2592. (ref^.base = NR_STACK_POINTER_REG) or
  2593. (ref^.base = current_procinfo.framepointer)
  2594. );
  2595. end;
  2596. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2597. var
  2598. l: asizeint;
  2599. begin
  2600. Result := False;
  2601. { Should have been checked previously }
  2602. if p.opcode <> A_LEA then
  2603. InternalError(2020072501);
  2604. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2605. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2606. not(cs_opt_size in current_settings.optimizerswitches) then
  2607. exit;
  2608. with p.oper[0]^.ref^ do
  2609. begin
  2610. if (base <> p.oper[1]^.reg) or
  2611. (index <> NR_NO) or
  2612. assigned(symbol) then
  2613. exit;
  2614. l:=offset;
  2615. if (l=1) and UseIncDec then
  2616. begin
  2617. p.opcode:=A_INC;
  2618. p.loadreg(0,p.oper[1]^.reg);
  2619. p.ops:=1;
  2620. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2621. end
  2622. else if (l=-1) and UseIncDec then
  2623. begin
  2624. p.opcode:=A_DEC;
  2625. p.loadreg(0,p.oper[1]^.reg);
  2626. p.ops:=1;
  2627. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2628. end
  2629. else
  2630. begin
  2631. if (l<0) and (l<>-2147483648) then
  2632. begin
  2633. p.opcode:=A_SUB;
  2634. p.loadConst(0,-l);
  2635. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2636. end
  2637. else
  2638. begin
  2639. p.opcode:=A_ADD;
  2640. p.loadConst(0,l);
  2641. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2642. end;
  2643. end;
  2644. end;
  2645. Result := True;
  2646. end;
  2647. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2648. var
  2649. CurrentReg, ReplaceReg: TRegister;
  2650. begin
  2651. Result := False;
  2652. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2653. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2654. case hp.opcode of
  2655. A_FSTSW, A_FNSTSW,
  2656. A_IN, A_INS, A_OUT, A_OUTS,
  2657. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2658. { These routines have explicit operands, but they are restricted in
  2659. what they can be (e.g. IN and OUT can only read from AL, AX or
  2660. EAX. }
  2661. Exit;
  2662. A_IMUL:
  2663. begin
  2664. { The 1-operand version writes to implicit registers
  2665. The 2-operand version reads from the first operator, and reads
  2666. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2667. the 3-operand version reads from a register that it doesn't write to
  2668. }
  2669. case hp.ops of
  2670. 1:
  2671. if (
  2672. (
  2673. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2674. ) or
  2675. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2676. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2677. begin
  2678. Result := True;
  2679. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2680. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2681. end;
  2682. 2:
  2683. { Only modify the first parameter }
  2684. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2685. begin
  2686. Result := True;
  2687. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2688. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2689. end;
  2690. 3:
  2691. { Only modify the second parameter }
  2692. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2693. begin
  2694. Result := True;
  2695. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2696. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2697. end;
  2698. else
  2699. InternalError(2020012901);
  2700. end;
  2701. end;
  2702. else
  2703. if (hp.ops > 0) and
  2704. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2705. begin
  2706. Result := True;
  2707. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2708. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2709. end;
  2710. end;
  2711. end;
  2712. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2713. var
  2714. hp2, hp_regalloc: tai;
  2715. p_SourceReg, p_TargetReg: TRegister;
  2716. begin
  2717. Result := False;
  2718. { Backward optimisation. If we have:
  2719. func. %reg1,%reg2
  2720. mov %reg2,%reg3
  2721. (dealloc %reg2)
  2722. Change to:
  2723. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2724. Perform similar optimisations with 1, 3 and 4-operand instructions
  2725. that only have one output.
  2726. }
  2727. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2728. begin
  2729. p_SourceReg := taicpu(p).oper[0]^.reg;
  2730. p_TargetReg := taicpu(p).oper[1]^.reg;
  2731. TransferUsedRegs(TmpUsedRegs);
  2732. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2733. GetLastInstruction(p, hp2) and
  2734. (hp2.typ = ait_instruction) and
  2735. { Have to make sure it's an instruction that only reads from
  2736. the first operands and only writes (not reads or modifies) to
  2737. the last one; in essence, a pure function such as BSR, POPCNT
  2738. or ANDN }
  2739. (
  2740. (
  2741. (taicpu(hp2).ops = 1) and
  2742. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2743. ) or
  2744. (
  2745. (taicpu(hp2).ops = 2) and
  2746. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2747. ) or
  2748. (
  2749. (taicpu(hp2).ops = 3) and
  2750. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2751. ) or
  2752. (
  2753. (taicpu(hp2).ops = 4) and
  2754. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2755. )
  2756. ) and
  2757. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2758. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2759. begin
  2760. case taicpu(hp2).opcode of
  2761. A_FSTSW, A_FNSTSW,
  2762. A_IN, A_INS, A_OUT, A_OUTS,
  2763. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2764. { These routines have explicit operands, but they are restricted in
  2765. what they can be (e.g. IN and OUT can only read from AL, AX or
  2766. EAX. }
  2767. ;
  2768. else
  2769. begin
  2770. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2771. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2772. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2773. if Assigned(hp_regalloc) then
  2774. begin
  2775. Asml.Remove(hp_regalloc);
  2776. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2777. begin
  2778. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2779. hp_regalloc.Free;
  2780. end
  2781. else
  2782. { If the register is not explicitly deallocated, it's
  2783. being reused, so move the allocation to after func. }
  2784. AsmL.InsertAfter(hp_regalloc, hp2);
  2785. end;
  2786. if not RegInInstruction(p_TargetReg, hp2) then
  2787. begin
  2788. TransferUsedRegs(TmpUsedRegs);
  2789. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2790. end;
  2791. { Actually make the changes }
  2792. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2793. RemoveCurrentp(p, hp1);
  2794. { If the Func was another MOV instruction, we might get
  2795. "mov %reg,%reg" that doesn't get removed in Pass 2
  2796. otherwise, so deal with it here (also do something
  2797. similar with lea (%reg),%reg}
  2798. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2799. begin
  2800. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2801. if p = hp2 then
  2802. RemoveCurrentp(p)
  2803. else
  2804. RemoveInstruction(hp2);
  2805. end;
  2806. Result := True;
  2807. Exit;
  2808. end;
  2809. end;
  2810. end;
  2811. end;
  2812. end;
  2813. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2814. begin
  2815. Result := False;
  2816. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2817. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2818. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2819. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2820. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2821. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2822. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2823. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2824. begin
  2825. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2826. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2827. Result := True;
  2828. Include(OptsToCheck, aoc_ForceNewIteration);
  2829. end;
  2830. end;
  2831. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2832. var
  2833. hp1, hp2, hp3, hp4: tai;
  2834. DoOptimisation, TempBool: Boolean;
  2835. {$ifdef x86_64}
  2836. NewConst: TCGInt;
  2837. {$endif x86_64}
  2838. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2839. begin
  2840. if taicpu(hp1).opcode = signed_movop then
  2841. begin
  2842. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2843. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2844. end
  2845. else
  2846. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2847. end;
  2848. function TryConstMerge(var p1, p2: tai): Boolean;
  2849. var
  2850. ThisRef: TReference;
  2851. begin
  2852. Result := False;
  2853. ThisRef := taicpu(p2).oper[1]^.ref^;
  2854. { Only permit writes to the stack, since we can guarantee alignment with that }
  2855. if (ThisRef.index = NR_NO) and
  2856. (
  2857. (ThisRef.base = NR_STACK_POINTER_REG) or
  2858. (ThisRef.base = current_procinfo.framepointer)
  2859. ) then
  2860. begin
  2861. case taicpu(p).opsize of
  2862. S_B:
  2863. begin
  2864. { Word writes must be on a 2-byte boundary }
  2865. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2866. begin
  2867. { Reduce offset of second reference to see if it is sequential with the first }
  2868. Dec(ThisRef.offset, 1);
  2869. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2870. begin
  2871. { Make sure the constants aren't represented as a
  2872. negative number, as these won't merge properly }
  2873. taicpu(p1).opsize := S_W;
  2874. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2875. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2876. RemoveInstruction(p2);
  2877. Result := True;
  2878. end;
  2879. end;
  2880. end;
  2881. S_W:
  2882. begin
  2883. { Longword writes must be on a 4-byte boundary }
  2884. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2885. begin
  2886. { Reduce offset of second reference to see if it is sequential with the first }
  2887. Dec(ThisRef.offset, 2);
  2888. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2889. begin
  2890. { Make sure the constants aren't represented as a
  2891. negative number, as these won't merge properly }
  2892. taicpu(p1).opsize := S_L;
  2893. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2894. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2895. RemoveInstruction(p2);
  2896. Result := True;
  2897. end;
  2898. end;
  2899. end;
  2900. {$ifdef x86_64}
  2901. S_L:
  2902. begin
  2903. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2904. see if the constants can be encoded this way. }
  2905. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2906. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2907. { Quadword writes must be on an 8-byte boundary }
  2908. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2909. begin
  2910. { Reduce offset of second reference to see if it is sequential with the first }
  2911. Dec(ThisRef.offset, 4);
  2912. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2913. begin
  2914. { Make sure the constants aren't represented as a
  2915. negative number, as these won't merge properly }
  2916. taicpu(p1).opsize := S_Q;
  2917. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2918. taicpu(p1).oper[0]^.val := NewConst;
  2919. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2920. RemoveInstruction(p2);
  2921. Result := True;
  2922. end;
  2923. end;
  2924. end;
  2925. {$endif x86_64}
  2926. else
  2927. ;
  2928. end;
  2929. end;
  2930. end;
  2931. var
  2932. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2933. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2934. NewSize: topsize; NewOffset: asizeint;
  2935. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2936. SourceRef, TargetRef: TReference;
  2937. MovAligned, MovUnaligned: TAsmOp;
  2938. ThisRef: TReference;
  2939. JumpTracking: TLinkedList;
  2940. begin
  2941. Result:=false;
  2942. { remove mov reg1,reg1? }
  2943. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2944. then
  2945. begin
  2946. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2947. { take care of the register (de)allocs following p }
  2948. RemoveCurrentP(p);
  2949. Result := True;
  2950. exit;
  2951. end;
  2952. { Prevent compiler warnings }
  2953. p_SourceReg := NR_NO;
  2954. p_TargetReg := NR_NO;
  2955. if taicpu(p).oper[1]^.typ = top_reg then
  2956. begin
  2957. { Saves on a large number of dereferences }
  2958. p_TargetReg := taicpu(p).oper[1]^.reg;
  2959. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2960. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2961. else
  2962. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2963. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2964. while True do
  2965. begin
  2966. if (taicpu(hp1).opcode = A_AND) and
  2967. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2968. begin
  2969. { A change has occurred, just not in p }
  2970. Include(OptsToCheck, aoc_ForceNewIteration);
  2971. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2972. begin
  2973. case taicpu(p).opsize of
  2974. S_L:
  2975. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2976. begin
  2977. { Optimize out:
  2978. mov x, %reg
  2979. and ffffffffh, %reg
  2980. }
  2981. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2982. RemoveInstruction(hp1);
  2983. Result:=true;
  2984. exit;
  2985. end;
  2986. S_Q: { TODO: Confirm if this is even possible }
  2987. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2988. begin
  2989. { Optimize out:
  2990. mov x, %reg
  2991. and ffffffffffffffffh, %reg
  2992. }
  2993. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2994. RemoveInstruction(hp1);
  2995. Result:=true;
  2996. exit;
  2997. end;
  2998. else
  2999. ;
  3000. end;
  3001. if (
  3002. { Make sure that if a reference is used, its registers
  3003. are not modified in between }
  3004. (
  3005. (taicpu(p).oper[0]^.typ = top_reg) and
  3006. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3007. ) or
  3008. (
  3009. (taicpu(p).oper[0]^.typ = top_ref) and
  3010. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3011. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3012. )
  3013. ) and
  3014. GetNextInstruction(hp1,hp2) and
  3015. MatchInstruction(hp2,A_TEST,[]) and
  3016. (
  3017. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3018. (
  3019. { If the register being tested is smaller than the one
  3020. that received a bitwise AND, permit it if the constant
  3021. fits into the smaller size }
  3022. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3023. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3024. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3025. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3026. (
  3027. (
  3028. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3029. (taicpu(hp1).oper[0]^.val <= $FF)
  3030. ) or
  3031. (
  3032. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3033. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3034. {$ifdef x86_64}
  3035. ) or
  3036. (
  3037. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3038. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3039. {$endif x86_64}
  3040. )
  3041. )
  3042. )
  3043. ) and
  3044. (
  3045. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3046. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3047. ) and
  3048. GetNextInstruction(hp2,hp3) and
  3049. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3050. (taicpu(hp3).condition in [C_E,C_NE]) then
  3051. begin
  3052. TransferUsedRegs(TmpUsedRegs);
  3053. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3054. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3055. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3056. begin
  3057. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3058. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3059. taicpu(hp1).opcode:=A_TEST;
  3060. { Shrink the TEST instruction down to the smallest possible size }
  3061. case taicpu(hp1).oper[0]^.val of
  3062. 0..255:
  3063. if (taicpu(hp1).opsize <> S_B)
  3064. {$ifndef x86_64}
  3065. and (
  3066. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3067. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3068. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3069. )
  3070. {$endif x86_64}
  3071. then
  3072. begin
  3073. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3074. { Only print debug message if the TEST instruction
  3075. is a different size before and after }
  3076. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3077. taicpu(hp1).opsize := S_B;
  3078. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3079. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3080. end;
  3081. 256..65535:
  3082. if (taicpu(hp1).opsize <> S_W) then
  3083. begin
  3084. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3085. { Only print debug message if the TEST instruction
  3086. is a different size before and after }
  3087. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3088. taicpu(hp1).opsize := S_W;
  3089. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3090. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3091. end;
  3092. {$ifdef x86_64}
  3093. 65536..$7FFFFFFF:
  3094. if (taicpu(hp1).opsize <> S_L) then
  3095. begin
  3096. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3097. { Only print debug message if the TEST instruction
  3098. is a different size before and after }
  3099. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3100. taicpu(hp1).opsize := S_L;
  3101. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3102. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3103. end;
  3104. {$endif x86_64}
  3105. else
  3106. ;
  3107. end;
  3108. RemoveInstruction(hp2);
  3109. RemoveCurrentP(p);
  3110. Result:=true;
  3111. exit;
  3112. end;
  3113. end;
  3114. end;
  3115. if IsMOVZXAcceptable and
  3116. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3117. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3118. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3119. then
  3120. begin
  3121. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3122. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3123. case taicpu(p).opsize of
  3124. S_B:
  3125. if (taicpu(hp1).oper[0]^.val = $ff) then
  3126. begin
  3127. { Convert:
  3128. movb x, %regl movb x, %regl
  3129. andw ffh, %regw andl ffh, %regd
  3130. To:
  3131. movzbw x, %regd movzbl x, %regd
  3132. (Identical registers, just different sizes)
  3133. }
  3134. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3135. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3136. case taicpu(hp1).opsize of
  3137. S_W: NewSize := S_BW;
  3138. S_L: NewSize := S_BL;
  3139. {$ifdef x86_64}
  3140. S_Q: NewSize := S_BQ;
  3141. {$endif x86_64}
  3142. else
  3143. InternalError(2018011510);
  3144. end;
  3145. end
  3146. else
  3147. NewSize := S_NO;
  3148. S_W:
  3149. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3150. begin
  3151. { Convert:
  3152. movw x, %regw
  3153. andl ffffh, %regd
  3154. To:
  3155. movzwl x, %regd
  3156. (Identical registers, just different sizes)
  3157. }
  3158. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3159. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3160. case taicpu(hp1).opsize of
  3161. S_L: NewSize := S_WL;
  3162. {$ifdef x86_64}
  3163. S_Q: NewSize := S_WQ;
  3164. {$endif x86_64}
  3165. else
  3166. InternalError(2018011511);
  3167. end;
  3168. end
  3169. else
  3170. NewSize := S_NO;
  3171. else
  3172. NewSize := S_NO;
  3173. end;
  3174. if NewSize <> S_NO then
  3175. begin
  3176. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3177. { The actual optimization }
  3178. taicpu(p).opcode := A_MOVZX;
  3179. taicpu(p).changeopsize(NewSize);
  3180. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3181. { Make sure we deal with any reference counts that were increased }
  3182. if taicpu(hp1).oper[1]^.typ = top_ref then
  3183. begin
  3184. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3185. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3186. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3187. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3188. end;
  3189. { Safeguard if "and" is followed by a conditional command }
  3190. TransferUsedRegs(TmpUsedRegs);
  3191. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3192. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3193. begin
  3194. { At this point, the "and" command is effectively equivalent to
  3195. "test %reg,%reg". This will be handled separately by the
  3196. Peephole Optimizer. [Kit] }
  3197. DebugMsg(SPeepholeOptimization + PreMessage +
  3198. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3199. end
  3200. else
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3203. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3204. RemoveInstruction(hp1);
  3205. end;
  3206. Result := True;
  3207. Exit;
  3208. { Go through DeepMOVOpt again (jump to "while True do") }
  3209. Continue;
  3210. end;
  3211. end;
  3212. end;
  3213. if taicpu(p).oper[0]^.typ = top_reg then
  3214. begin
  3215. p_SourceReg := taicpu(p).oper[0]^.reg;
  3216. { Look for:
  3217. mov %reg1,%reg2
  3218. ??? %reg2,r/m
  3219. Change to:
  3220. mov %reg1,%reg2
  3221. ??? %reg1,r/m
  3222. }
  3223. if RegReadByInstruction(p_TargetReg, hp1) and
  3224. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3225. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3226. begin
  3227. { A change has occurred, just not in p }
  3228. Include(OptsToCheck, aoc_ForceNewIteration);
  3229. TransferUsedRegs(TmpUsedRegs);
  3230. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3231. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3232. { Just in case something didn't get modified (e.g. an
  3233. implicit register) }
  3234. not RegReadByInstruction(p_TargetReg, hp1) then
  3235. begin
  3236. { We can remove the original MOV }
  3237. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3238. RemoveCurrentP(p);
  3239. { UsedRegs got updated by RemoveCurrentp }
  3240. Result := True;
  3241. Exit;
  3242. end;
  3243. { If we know a MOV instruction has become a null operation, we might as well
  3244. get rid of it now to save time. }
  3245. if (taicpu(hp1).opcode = A_MOV) and
  3246. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3247. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3248. { Just being a register is enough to confirm it's a null operation }
  3249. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3250. begin
  3251. Result := True;
  3252. { Speed-up to reduce a pipeline stall... if we had something like...
  3253. movl %eax,%edx
  3254. movw %dx,%ax
  3255. ... the second instruction would change to movw %ax,%ax, but
  3256. given that it is now %ax that's active rather than %eax,
  3257. penalties might occur due to a partial register write, so instead,
  3258. change it to a MOVZX instruction when optimising for speed.
  3259. }
  3260. if not (cs_opt_size in current_settings.optimizerswitches) and
  3261. IsMOVZXAcceptable and
  3262. (taicpu(hp1).opsize < taicpu(p).opsize)
  3263. {$ifdef x86_64}
  3264. { operations already implicitly set the upper 64 bits to zero }
  3265. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3266. {$endif x86_64}
  3267. then
  3268. begin
  3269. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3270. case taicpu(p).opsize of
  3271. S_W:
  3272. if taicpu(hp1).opsize = S_B then
  3273. taicpu(hp1).opsize := S_BL
  3274. else
  3275. InternalError(2020012911);
  3276. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3277. case taicpu(hp1).opsize of
  3278. S_B:
  3279. taicpu(hp1).opsize := S_BL;
  3280. S_W:
  3281. taicpu(hp1).opsize := S_WL;
  3282. else
  3283. InternalError(2020012912);
  3284. end;
  3285. else
  3286. InternalError(2020012910);
  3287. end;
  3288. taicpu(hp1).opcode := A_MOVZX;
  3289. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3290. end
  3291. else
  3292. begin
  3293. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3294. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3295. RemoveInstruction(hp1);
  3296. { The instruction after what was hp1 is now the immediate next instruction,
  3297. so we can continue to make optimisations if it's present }
  3298. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3299. Exit;
  3300. hp1 := hp2;
  3301. end;
  3302. end;
  3303. end;
  3304. {$ifdef x86_64}
  3305. { Change:
  3306. movl %reg1l,%reg2l
  3307. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3308. To:
  3309. movl %reg1l,%reg2l
  3310. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3311. If %reg1 = %reg3, convert to:
  3312. movl %reg1l,%reg2l
  3313. andl %reg1l,%reg1l
  3314. }
  3315. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3316. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3317. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3318. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3319. begin
  3320. TransferUsedRegs(TmpUsedRegs);
  3321. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3322. taicpu(hp1).opsize := S_L;
  3323. taicpu(hp1).loadreg(0, p_SourceReg);
  3324. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3325. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3326. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3327. begin
  3328. { %reg1 = %reg3 }
  3329. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3330. taicpu(hp1).opcode := A_AND;
  3331. end
  3332. else
  3333. begin
  3334. { %reg1 <> %reg3 }
  3335. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3336. end;
  3337. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3338. begin
  3339. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3340. RemoveCurrentP(p);
  3341. Result := True;
  3342. Exit;
  3343. end
  3344. else
  3345. begin
  3346. { Initial instruction wasn't actually changed }
  3347. Include(OptsToCheck, aoc_ForceNewIteration);
  3348. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3349. appears below since %reg1 has technically changed }
  3350. if taicpu(hp1).opcode = A_AND then
  3351. Exit;
  3352. end;
  3353. end;
  3354. {$endif x86_64}
  3355. end
  3356. else if taicpu(p).oper[0]^.typ = top_const then
  3357. begin
  3358. if (taicpu(hp1).opcode = A_OR) and
  3359. (taicpu(p).oper[1]^.typ = top_reg) and
  3360. MatchOperand(taicpu(p).oper[0]^, 0) and
  3361. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3362. begin
  3363. { mov 0, %reg
  3364. or ###,%reg
  3365. Change to (only if the flags are not used):
  3366. mov ###,%reg
  3367. }
  3368. TransferUsedRegs(TmpUsedRegs);
  3369. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3370. DoOptimisation := True;
  3371. { Even if the flags are used, we might be able to do the optimisation
  3372. if the conditions are predictable }
  3373. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3374. begin
  3375. { Only perform if ### = %reg (the same register) or equal to 0,
  3376. so %reg is guaranteed to still have a value of zero }
  3377. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3378. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3379. begin
  3380. hp2 := hp1;
  3381. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3382. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3383. GetNextInstruction(hp2, hp3) do
  3384. begin
  3385. { Don't continue modifying if the flags state is getting changed }
  3386. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3387. Break;
  3388. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3389. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3390. begin
  3391. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3392. begin
  3393. { Condition is always true }
  3394. case taicpu(hp3).opcode of
  3395. A_Jcc:
  3396. begin
  3397. { Check for jump shortcuts before we destroy the condition }
  3398. hp4 := hp3;
  3399. DoJumpOptimizations(hp3, TempBool);
  3400. { Make sure hp3 hasn't changed }
  3401. if (hp4 = hp3) then
  3402. begin
  3403. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3404. MakeUnconditional(taicpu(hp3));
  3405. end;
  3406. Result := True;
  3407. end;
  3408. A_CMOVcc:
  3409. begin
  3410. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3411. taicpu(hp3).opcode := A_MOV;
  3412. taicpu(hp3).condition := C_None;
  3413. Result := True;
  3414. end;
  3415. A_SETcc:
  3416. begin
  3417. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3418. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3419. taicpu(hp3).opcode := A_MOV;
  3420. taicpu(hp3).ops := 2;
  3421. taicpu(hp3).condition := C_None;
  3422. taicpu(hp3).opsize := S_B;
  3423. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3424. taicpu(hp3).loadconst(0, 1);
  3425. Result := True;
  3426. end;
  3427. else
  3428. InternalError(2021090701);
  3429. end;
  3430. end
  3431. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3432. begin
  3433. { Condition is always false }
  3434. case taicpu(hp3).opcode of
  3435. A_Jcc:
  3436. begin
  3437. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3438. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3439. RemoveInstruction(hp3);
  3440. Result := True;
  3441. { Since hp3 was deleted, hp2 must not be updated }
  3442. Continue;
  3443. end;
  3444. A_CMOVcc:
  3445. begin
  3446. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3447. RemoveInstruction(hp3);
  3448. Result := True;
  3449. { Since hp3 was deleted, hp2 must not be updated }
  3450. Continue;
  3451. end;
  3452. A_SETcc:
  3453. begin
  3454. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3455. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3456. taicpu(hp3).opcode := A_MOV;
  3457. taicpu(hp3).ops := 2;
  3458. taicpu(hp3).condition := C_None;
  3459. taicpu(hp3).opsize := S_B;
  3460. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3461. taicpu(hp3).loadconst(0, 0);
  3462. Result := True;
  3463. end;
  3464. else
  3465. InternalError(2021090702);
  3466. end;
  3467. end
  3468. else
  3469. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3470. DoOptimisation := False;
  3471. end;
  3472. hp2 := hp3;
  3473. end;
  3474. if DoOptimisation then
  3475. begin
  3476. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3477. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3478. { Flags are still in use - don't optimise }
  3479. DoOptimisation := False;
  3480. end;
  3481. end
  3482. else
  3483. DoOptimisation := False;
  3484. end;
  3485. if DoOptimisation then
  3486. begin
  3487. {$ifdef x86_64}
  3488. { OR only supports 32-bit sign-extended constants for 64-bit
  3489. instructions, so compensate for this if the constant is
  3490. encoded as a value greater than or equal to 2^31 }
  3491. if (taicpu(hp1).opsize = S_Q) and
  3492. (taicpu(hp1).oper[0]^.typ = top_const) and
  3493. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3494. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3495. {$endif x86_64}
  3496. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3497. taicpu(hp1).opcode := A_MOV;
  3498. RemoveCurrentP(p);
  3499. Result := True;
  3500. Exit;
  3501. end;
  3502. end;
  3503. end
  3504. else if
  3505. { oper[0] is a reference }
  3506. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3507. begin
  3508. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3509. begin
  3510. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3511. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3512. ) or
  3513. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3514. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3515. )
  3516. ) and
  3517. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3518. { mov ref,reg1
  3519. lea (reg1,reg2),reg2
  3520. to
  3521. add ref,reg2 }
  3522. begin
  3523. TransferUsedRegs(TmpUsedRegs);
  3524. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3525. { If the flags register is in use, don't change the instruction to an
  3526. ADD otherwise this will scramble the flags. [Kit] }
  3527. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3528. { reg1 may not be used afterwards }
  3529. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3530. begin
  3531. Taicpu(hp1).opcode:=A_ADD;
  3532. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3533. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3534. RemoveCurrentp(p);
  3535. result:=true;
  3536. exit;
  3537. end;
  3538. end;
  3539. { If the LEA instruction can be converted into an arithmetic instruction,
  3540. it may be possible to then fold it in the next optimisation. }
  3541. if ConvertLEA(taicpu(hp1)) then
  3542. Include(OptsToCheck, aoc_ForceNewIteration);
  3543. end;
  3544. {
  3545. mov ref,reg0
  3546. <op> reg0,reg1
  3547. dealloc reg0
  3548. to
  3549. <op> ref,reg1
  3550. }
  3551. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3552. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3553. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3554. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3555. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3556. begin
  3557. TransferUsedRegs(TmpUsedRegs);
  3558. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3559. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3560. begin
  3561. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3562. { loadref increases the reference count, so decrement it again }
  3563. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3564. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3565. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3566. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3567. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3568. { See if we can remove the allocation of reg0 }
  3569. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3570. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3571. RemoveCurrentp(p);
  3572. Result:=true;
  3573. exit;
  3574. end;
  3575. end;
  3576. end;
  3577. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3578. overwrites the original destination register. e.g.
  3579. movl ###,%reg2d
  3580. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3581. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3582. }
  3583. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3584. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3585. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3586. begin
  3587. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3588. begin
  3589. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3590. case taicpu(p).oper[0]^.typ of
  3591. top_const:
  3592. { We have something like:
  3593. movb $x, %regb
  3594. movzbl %regb,%regd
  3595. Change to:
  3596. movl $x, %regd
  3597. }
  3598. begin
  3599. case taicpu(hp1).opsize of
  3600. S_BW:
  3601. begin
  3602. convert_mov_value(A_MOVSX, $FF);
  3603. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3604. taicpu(p).opsize := S_W;
  3605. end;
  3606. S_BL:
  3607. begin
  3608. convert_mov_value(A_MOVSX, $FF);
  3609. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3610. taicpu(p).opsize := S_L;
  3611. end;
  3612. S_WL:
  3613. begin
  3614. convert_mov_value(A_MOVSX, $FFFF);
  3615. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3616. taicpu(p).opsize := S_L;
  3617. end;
  3618. {$ifdef x86_64}
  3619. S_BQ:
  3620. begin
  3621. convert_mov_value(A_MOVSX, $FF);
  3622. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3623. taicpu(p).opsize := S_Q;
  3624. end;
  3625. S_WQ:
  3626. begin
  3627. convert_mov_value(A_MOVSX, $FFFF);
  3628. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3629. taicpu(p).opsize := S_Q;
  3630. end;
  3631. S_LQ:
  3632. begin
  3633. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3634. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3635. taicpu(p).opsize := S_Q;
  3636. end;
  3637. {$endif x86_64}
  3638. else
  3639. { If hp1 was a MOV instruction, it should have been
  3640. optimised already }
  3641. InternalError(2020021001);
  3642. end;
  3643. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3644. RemoveInstruction(hp1);
  3645. Result := True;
  3646. Exit;
  3647. end;
  3648. top_ref:
  3649. begin
  3650. { We have something like:
  3651. movb mem, %regb
  3652. movzbl %regb,%regd
  3653. Change to:
  3654. movzbl mem, %regd
  3655. }
  3656. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3657. begin
  3658. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3659. taicpu(p).opcode := taicpu(hp1).opcode;
  3660. taicpu(p).opsize := taicpu(hp1).opsize;
  3661. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3662. RemoveInstruction(hp1);
  3663. Result := True;
  3664. Exit;
  3665. end;
  3666. end;
  3667. else
  3668. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3669. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3670. Exit;
  3671. end;
  3672. end
  3673. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3674. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3675. optimised }
  3676. else
  3677. begin
  3678. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3679. RemoveCurrentP(p);
  3680. Result := True;
  3681. Exit;
  3682. end;
  3683. end;
  3684. if (taicpu(hp1).opcode = A_MOV) and
  3685. (
  3686. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3687. {$ifdef x86_64}
  3688. or (
  3689. { Permit zero extension from 32- to 64-bit when writing
  3690. a constant (it will be checked to see if it fits into
  3691. a signed 32-bit integer) }
  3692. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3693. (
  3694. { Valid situations... writing an unsigned 32-bit
  3695. immediate, or the destination is a 64-bit register }
  3696. (taicpu(p).oper[0]^.typ = top_const) or
  3697. (taicpu(hp1).oper[1]^.typ = top_reg)
  3698. ) and
  3699. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3700. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3701. )
  3702. {$endif x86_64}
  3703. ) then
  3704. begin
  3705. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3706. TransferUsedRegs(TmpUsedRegs);
  3707. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3708. { we have
  3709. mov x, %treg
  3710. mov %treg, y
  3711. }
  3712. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3713. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3714. begin
  3715. { we've got
  3716. mov x, %treg
  3717. mov %treg, y
  3718. with %treg is not used after }
  3719. case taicpu(p).oper[0]^.typ Of
  3720. { top_reg is covered by DeepMOVOpt }
  3721. top_const:
  3722. begin
  3723. { change
  3724. mov const, %treg
  3725. mov %treg, y
  3726. to
  3727. mov const, y
  3728. }
  3729. {$ifdef x86_64}
  3730. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3731. (
  3732. { For 32-to-64-bit zero-extension, the immediate
  3733. must be between 0 and 2^31 - 1}
  3734. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3735. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3736. ) or
  3737. (
  3738. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3739. (
  3740. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3741. )
  3742. ) then
  3743. {$endif x86_64}
  3744. begin
  3745. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3746. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3747. RemoveCurrentP(p);
  3748. Result := True;
  3749. Exit;
  3750. end;
  3751. end;
  3752. top_ref:
  3753. case taicpu(hp1).oper[1]^.typ of
  3754. top_reg:
  3755. { change
  3756. mov mem, %treg
  3757. mov %treg, %reg
  3758. to
  3759. mov mem, %reg"
  3760. }
  3761. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3762. begin
  3763. {$ifdef x86_64}
  3764. { If zero extending from 32-bit to 64-bit,
  3765. we have to make sure the replaced
  3766. register is the right size }
  3767. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3768. {$else}
  3769. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3770. {$endif x86_64}
  3771. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3772. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3773. RemoveInstruction(hp1);
  3774. Result := True;
  3775. Exit;
  3776. end
  3777. else if
  3778. { Make sure that if a reference is used, its
  3779. registers are not modified in between }
  3780. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3781. begin
  3782. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3783. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3784. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3785. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3786. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3787. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3788. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3789. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3790. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3791. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3792. RemoveCurrentP(p);
  3793. Result := True;
  3794. Exit;
  3795. end;
  3796. top_ref:
  3797. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3798. begin
  3799. {$ifdef x86_64}
  3800. { Look for the following to simplify:
  3801. mov x(mem1), %reg
  3802. mov %reg, y(mem2)
  3803. mov x+8(mem1), %reg
  3804. mov %reg, y+8(mem2)
  3805. Change to:
  3806. movdqu x(mem1), %xmmreg
  3807. movdqu %xmmreg, y(mem2)
  3808. ...but only as long as the memory blocks don't overlap
  3809. }
  3810. SourceRef := taicpu(p).oper[0]^.ref^;
  3811. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3812. if (taicpu(p).opsize = S_Q) and
  3813. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3814. GetNextInstruction(hp1, hp2) and
  3815. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3816. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3817. begin
  3818. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3819. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3820. Inc(SourceRef.offset, 8);
  3821. if UseAVX then
  3822. begin
  3823. MovAligned := A_VMOVDQA;
  3824. MovUnaligned := A_VMOVDQU;
  3825. end
  3826. else
  3827. begin
  3828. MovAligned := A_MOVDQA;
  3829. MovUnaligned := A_MOVDQU;
  3830. end;
  3831. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3832. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3833. begin
  3834. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3835. Inc(TargetRef.offset, 8);
  3836. if GetNextInstruction(hp2, hp3) and
  3837. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3838. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3839. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3840. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3841. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3842. begin
  3843. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3844. if NewMMReg <> NR_NO then
  3845. begin
  3846. { Remember that the offsets are 8 ahead }
  3847. if ((SourceRef.offset mod 16) = 8) and
  3848. (
  3849. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3850. (SourceRef.base = current_procinfo.framepointer) or
  3851. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3852. ) then
  3853. taicpu(p).opcode := MovAligned
  3854. else
  3855. taicpu(p).opcode := MovUnaligned;
  3856. taicpu(p).opsize := S_XMM;
  3857. taicpu(p).oper[1]^.reg := NewMMReg;
  3858. if ((TargetRef.offset mod 16) = 8) and
  3859. (
  3860. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3861. (TargetRef.base = current_procinfo.framepointer) or
  3862. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3863. ) then
  3864. taicpu(hp1).opcode := MovAligned
  3865. else
  3866. taicpu(hp1).opcode := MovUnaligned;
  3867. taicpu(hp1).opsize := S_XMM;
  3868. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3869. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3870. RemoveInstruction(hp2);
  3871. RemoveInstruction(hp3);
  3872. Result := True;
  3873. Exit;
  3874. end;
  3875. end;
  3876. end
  3877. else
  3878. begin
  3879. { See if the next references are 8 less rather than 8 greater }
  3880. Dec(SourceRef.offset, 16); { -8 the other way }
  3881. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3882. begin
  3883. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3884. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3885. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3886. GetNextInstruction(hp2, hp3) and
  3887. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3888. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3889. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3890. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3891. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3892. begin
  3893. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3894. if NewMMReg <> NR_NO then
  3895. begin
  3896. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3897. if ((SourceRef.offset mod 16) = 0) and
  3898. (
  3899. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3900. (SourceRef.base = current_procinfo.framepointer) or
  3901. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3902. ) then
  3903. taicpu(hp2).opcode := MovAligned
  3904. else
  3905. taicpu(hp2).opcode := MovUnaligned;
  3906. taicpu(hp2).opsize := S_XMM;
  3907. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3908. if ((TargetRef.offset mod 16) = 0) and
  3909. (
  3910. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3911. (TargetRef.base = current_procinfo.framepointer) or
  3912. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3913. ) then
  3914. taicpu(hp3).opcode := MovAligned
  3915. else
  3916. taicpu(hp3).opcode := MovUnaligned;
  3917. taicpu(hp3).opsize := S_XMM;
  3918. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3919. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3920. RemoveInstruction(hp1);
  3921. RemoveCurrentP(p);
  3922. Result := True;
  3923. Exit;
  3924. end;
  3925. end;
  3926. end;
  3927. end;
  3928. end;
  3929. {$endif x86_64}
  3930. end;
  3931. else
  3932. { The write target should be a reg or a ref }
  3933. InternalError(2021091601);
  3934. end;
  3935. else
  3936. ;
  3937. end;
  3938. end
  3939. else if (taicpu(p).oper[0]^.typ = top_const) and
  3940. { %treg is used afterwards, but all eventualities other
  3941. than the first MOV instruction being a constant are
  3942. covered by DeepMOVOpt, so only check for that }
  3943. (
  3944. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3945. not (cs_opt_size in current_settings.optimizerswitches) or
  3946. (taicpu(hp1).opsize = S_B)
  3947. ) and
  3948. (
  3949. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3950. (
  3951. { For 32-to-64-bit zero-extension, the immediate
  3952. must be between 0 and 2^31 - 1}
  3953. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3954. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3955. ) or
  3956. (
  3957. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3958. (
  3959. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3960. )
  3961. )
  3962. ) then
  3963. begin
  3964. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3965. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3966. Include(OptsToCheck, aoc_ForceNewIteration);
  3967. end;
  3968. end;
  3969. Break;
  3970. end;
  3971. end;
  3972. if taicpu(p).oper[0]^.typ = top_reg then
  3973. begin
  3974. { oper[1] is a reference }
  3975. { Saves on a large number of dereferences }
  3976. p_SourceReg := taicpu(p).oper[0]^.reg;
  3977. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3978. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3979. else
  3980. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3981. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3982. begin
  3983. if taicpu(p).oper[1]^.typ = top_reg then
  3984. begin
  3985. p_TargetReg := taicpu(p).oper[1]^.reg;
  3986. { Change:
  3987. movl %reg1,%reg2
  3988. ...
  3989. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3990. ...
  3991. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3992. To:
  3993. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3994. ...
  3995. movl x(%reg1),%reg1
  3996. ...
  3997. movl %reg1,%regX
  3998. }
  3999. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4000. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4001. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4002. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4003. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4004. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4005. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4006. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4007. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4008. begin
  4009. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4010. if RegInRef(p_TargetReg, SourceRef) and
  4011. { If %reg1 also appears in the second reference, then it will
  4012. not refer to the same memory block as the first reference }
  4013. not RegInRef(p_SourceReg, SourceRef) then
  4014. begin
  4015. { Check to see if the references match if %reg2 is changed to %reg1 }
  4016. if SourceRef.base = p_TargetReg then
  4017. SourceRef.base := p_SourceReg;
  4018. if SourceRef.index = p_TargetReg then
  4019. SourceRef.index := p_SourceReg;
  4020. { RefsEqual also checks to ensure both references are non-volatile }
  4021. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4022. begin
  4023. taicpu(hp2).loadreg(0, p_SourceReg);
  4024. TransferUsedRegs(TmpUsedRegs);
  4025. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4026. { Make sure the register is allocated between these instructions
  4027. even though it doesn't change value, since it may cause
  4028. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4029. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4030. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4031. Result := True;
  4032. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4035. RemoveCurrentP(p);
  4036. Exit;
  4037. end
  4038. else
  4039. begin
  4040. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4041. begin
  4042. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4043. RemoveCurrentP(p);
  4044. Exit;
  4045. end;
  4046. end;
  4047. { If we reach this point, p and hp1 weren't actually modified,
  4048. so we can do a bit more work on this pass }
  4049. end;
  4050. end;
  4051. end;
  4052. end;
  4053. end;
  4054. end;
  4055. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4056. { All the next optimisations require a next instruction }
  4057. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4058. Exit;
  4059. { Change:
  4060. movl/q (ref), %reg
  4061. movd/q %reg, %xmm0
  4062. (dealloc %reg)
  4063. To:
  4064. movd/q (ref), %xmm0
  4065. }
  4066. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4067. MatchInstruction(hp1,[A_MOVD,A_VMOVD{$ifdef x86_64},A_MOVQ,A_VMOVQ{$endif x86_64}],[]) and
  4068. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  4069. (taicpu(hp1).oper[1]^.typ=top_reg) and
  4070. (GetRegType(taicpu(hp1).oper[1]^.reg)=R_MMREGISTER) then
  4071. begin
  4072. TransferUsedRegs(TmpUsedRegs);
  4073. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4074. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  4075. begin
  4076. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  4077. { loadref increases the reference count, so decrement it again }
  4078. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  4079. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  4080. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  4081. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  4082. DebugMsg(SPeepholeOptimization+'Merged MOV and (V)MOVD/(V)MOVQ to eliminate intermediate register (MovMovD/Q2MovD/Q)',p);
  4083. RemoveCurrentP(p,hp1);
  4084. Result:=True;
  4085. Exit;
  4086. end;
  4087. end;
  4088. { Next instruction is also a MOV ? }
  4089. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4090. begin
  4091. if MatchOpType(taicpu(p), top_const, top_ref) and
  4092. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4093. TryConstMerge(p, hp1) then
  4094. begin
  4095. Result := True;
  4096. { In case we have four byte writes in a row, check for 2 more
  4097. right now so we don't have to wait for another iteration of
  4098. pass 1
  4099. }
  4100. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4101. case taicpu(p).opsize of
  4102. S_W:
  4103. begin
  4104. if GetNextInstruction(p, hp1) and
  4105. MatchInstruction(hp1, A_MOV, [S_B]) and
  4106. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4107. GetNextInstruction(hp1, hp2) and
  4108. MatchInstruction(hp2, A_MOV, [S_B]) and
  4109. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4110. { Try to merge the two bytes }
  4111. TryConstMerge(hp1, hp2) then
  4112. { Now try to merge the two words (hp2 will get deleted) }
  4113. TryConstMerge(p, hp1);
  4114. end;
  4115. S_L:
  4116. begin
  4117. { Though this only really benefits x86_64 and not i386, it
  4118. gets a potential optimisation done faster and hence
  4119. reduces the number of times OptPass1MOV is entered }
  4120. if GetNextInstruction(p, hp1) and
  4121. MatchInstruction(hp1, A_MOV, [S_W]) and
  4122. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4123. GetNextInstruction(hp1, hp2) and
  4124. MatchInstruction(hp2, A_MOV, [S_W]) and
  4125. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4126. { Try to merge the two words }
  4127. TryConstMerge(hp1, hp2) then
  4128. { This will always fail on i386, so don't bother
  4129. calling it unless we're doing x86_64 }
  4130. {$ifdef x86_64}
  4131. { Now try to merge the two longwords (hp2 will get deleted) }
  4132. TryConstMerge(p, hp1)
  4133. {$endif x86_64}
  4134. ;
  4135. end;
  4136. else
  4137. ;
  4138. end;
  4139. Exit;
  4140. end;
  4141. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4142. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4143. { mov reg1, mem1 or mov mem1, reg1
  4144. mov mem2, reg2 mov reg2, mem2}
  4145. begin
  4146. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4147. { mov reg1, mem1 or mov mem1, reg1
  4148. mov mem2, reg1 mov reg2, mem1}
  4149. begin
  4150. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4151. { Removes the second statement from
  4152. mov reg1, mem1/reg2
  4153. mov mem1/reg2, reg1 }
  4154. begin
  4155. if taicpu(p).oper[0]^.typ=top_reg then
  4156. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4157. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4158. RemoveInstruction(hp1);
  4159. Result:=true;
  4160. if (taicpu(p).oper[1]^.typ = top_reg) then
  4161. begin
  4162. TransferUsedRegs(TmpUsedRegs);
  4163. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, p, TmpUsedRegs) then
  4164. begin
  4165. { reg2 is no longer in use }
  4166. DebugMsg(SPeepholeOptimization + 'Mov2Nop 6 done',p);
  4167. RemoveCurrentP(p);
  4168. end;
  4169. end;
  4170. exit;
  4171. end
  4172. else
  4173. begin
  4174. TransferUsedRegs(TmpUsedRegs);
  4175. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4176. if (taicpu(p).oper[1]^.typ = top_ref) and
  4177. { mov reg1, mem1
  4178. mov mem2, reg1 }
  4179. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4180. GetNextInstruction(hp1, hp2) and
  4181. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4182. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4183. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4184. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4185. { change to
  4186. mov reg1, mem1 mov reg1, mem1
  4187. mov mem2, reg1 cmp reg1, mem2
  4188. cmp mem1, reg1
  4189. }
  4190. begin
  4191. RemoveInstruction(hp2);
  4192. taicpu(hp1).opcode := A_CMP;
  4193. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4194. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4195. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4196. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4197. end;
  4198. end;
  4199. end
  4200. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4201. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4202. begin
  4203. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4204. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4205. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4206. end
  4207. else
  4208. begin
  4209. TransferUsedRegs(TmpUsedRegs);
  4210. if GetNextInstruction(hp1, hp2) and
  4211. MatchOpType(taicpu(p),top_ref,top_reg) and
  4212. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4213. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4214. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4215. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4216. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4217. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4218. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4219. { mov mem1, %reg1
  4220. mov %reg1, mem2
  4221. mov mem2, reg2
  4222. to:
  4223. mov mem1, reg2
  4224. mov reg2, mem2}
  4225. begin
  4226. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4227. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4228. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4229. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4230. RemoveInstruction(hp2);
  4231. Result := True;
  4232. end
  4233. {$ifdef i386}
  4234. { this is enabled for i386 only, as the rules to create the reg sets below
  4235. are too complicated for x86-64, so this makes this code too error prone
  4236. on x86-64
  4237. }
  4238. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4239. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4240. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4241. { mov mem1, reg1 mov mem1, reg1
  4242. mov reg1, mem2 mov reg1, mem2
  4243. mov mem2, reg2 mov mem2, reg1
  4244. to: to:
  4245. mov mem1, reg1 mov mem1, reg1
  4246. mov mem1, reg2 mov reg1, mem2
  4247. mov reg1, mem2
  4248. or (if mem1 depends on reg1
  4249. and/or if mem2 depends on reg2)
  4250. to:
  4251. mov mem1, reg1
  4252. mov reg1, mem2
  4253. mov reg1, reg2
  4254. }
  4255. begin
  4256. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4257. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4258. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4259. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4260. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4261. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4262. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4263. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4264. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4265. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4266. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4267. end
  4268. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4269. begin
  4270. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4271. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4272. end
  4273. else
  4274. begin
  4275. RemoveInstruction(hp2);
  4276. end
  4277. {$endif i386}
  4278. ;
  4279. end;
  4280. end
  4281. { movl [mem1],reg1
  4282. movl [mem1],reg2
  4283. to
  4284. movl [mem1],reg1
  4285. movl reg1,reg2
  4286. }
  4287. else if not CheckMovMov2MovMov2(p, hp1) and
  4288. { movl const1,[mem1]
  4289. movl [mem1],reg1
  4290. to
  4291. movl const1,reg1
  4292. movl reg1,[mem1]
  4293. }
  4294. MatchOpType(Taicpu(p),top_const,top_ref) and
  4295. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4296. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4297. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4298. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4299. begin
  4300. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4301. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4302. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4303. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4304. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4305. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4306. Result:=true;
  4307. exit;
  4308. end;
  4309. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4310. end;
  4311. { search further than the next instruction for a mov (as long as it's not a jump) }
  4312. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4313. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4314. (taicpu(p).oper[1]^.typ = top_reg) and
  4315. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4316. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4317. begin
  4318. { we work with hp2 here, so hp1 can be still used later on when
  4319. checking for GetNextInstruction_p }
  4320. hp3 := hp1;
  4321. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4322. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4323. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4324. TransferUsedRegs(TmpUsedRegs);
  4325. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4326. if NotFirstIteration then
  4327. JumpTracking := TLinkedList.Create
  4328. else
  4329. JumpTracking := nil;
  4330. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4331. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4332. (hp2.typ=ait_instruction) do
  4333. begin
  4334. case taicpu(hp2).opcode of
  4335. A_POP:
  4336. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4337. begin
  4338. if not CrossJump and
  4339. not RegUsedBetween(p_TargetReg, p, hp2) then
  4340. begin
  4341. { We can remove the original MOV since the register
  4342. wasn't used between it and its popping from the stack }
  4343. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4344. RemoveCurrentp(p, hp1);
  4345. Result := True;
  4346. JumpTracking.Free;
  4347. Exit;
  4348. end;
  4349. { Can't go any further }
  4350. Break;
  4351. end;
  4352. A_MOV:
  4353. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4354. ((taicpu(p).oper[0]^.typ=top_const) or
  4355. ((taicpu(p).oper[0]^.typ=top_reg) and
  4356. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4357. )
  4358. ) then
  4359. begin
  4360. { we have
  4361. mov x, %treg
  4362. mov %treg, y
  4363. }
  4364. { We don't need to call UpdateUsedRegs for every instruction between
  4365. p and hp2 because the register we're concerned about will not
  4366. become deallocated (otherwise GetNextInstructionUsingReg would
  4367. have stopped at an earlier instruction). [Kit] }
  4368. TempRegUsed :=
  4369. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4370. RegReadByInstruction(p_TargetReg, hp3) or
  4371. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4372. case taicpu(p).oper[0]^.typ Of
  4373. top_reg:
  4374. begin
  4375. { change
  4376. mov %reg, %treg
  4377. mov %treg, y
  4378. to
  4379. mov %reg, y
  4380. }
  4381. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4382. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4383. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4384. begin
  4385. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4386. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4387. if TempRegUsed then
  4388. begin
  4389. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4390. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4391. { Set the start of the next GetNextInstructionUsingRegCond search
  4392. to start at the entry right before hp2 (which is about to be removed) }
  4393. hp3 := tai(hp2.Previous);
  4394. RemoveInstruction(hp2);
  4395. Include(OptsToCheck, aoc_ForceNewIteration);
  4396. { See if there's more we can optimise }
  4397. Continue;
  4398. end
  4399. else
  4400. begin
  4401. RemoveInstruction(hp2);
  4402. { We can remove the original MOV too }
  4403. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4404. RemoveCurrentP(p, hp1);
  4405. Result:=true;
  4406. JumpTracking.Free;
  4407. Exit;
  4408. end;
  4409. end
  4410. else
  4411. begin
  4412. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4413. taicpu(hp2).loadReg(0, p_SourceReg);
  4414. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4415. { Check to see if the register also appears in the reference }
  4416. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4417. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4418. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4419. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4420. begin
  4421. { Don't remove the first instruction if the temporary register is in use }
  4422. if not TempRegUsed then
  4423. begin
  4424. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4425. RemoveCurrentP(p, hp1);
  4426. Result:=true;
  4427. JumpTracking.Free;
  4428. Exit;
  4429. end;
  4430. { No need to set Result to True here. If there's another instruction later
  4431. on that can be optimised, it will be detected when the main Pass 1 loop
  4432. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4433. hp3 := hp2;
  4434. Continue;
  4435. end;
  4436. end;
  4437. end;
  4438. top_const:
  4439. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4440. begin
  4441. { change
  4442. mov const, %treg
  4443. mov %treg, y
  4444. to
  4445. mov const, y
  4446. }
  4447. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4448. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4449. begin
  4450. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4451. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4452. if TempRegUsed then
  4453. begin
  4454. { Don't remove the first instruction if the temporary register is in use }
  4455. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4456. { No need to set Result to True. If there's another instruction later on
  4457. that can be optimised, it will be detected when the main Pass 1 loop
  4458. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4459. end
  4460. else
  4461. begin
  4462. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4463. RemoveCurrentP(p, hp1);
  4464. Result:=true;
  4465. Exit;
  4466. end;
  4467. end;
  4468. end;
  4469. else
  4470. Internalerror(2019103001);
  4471. end;
  4472. end
  4473. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4474. begin
  4475. if not CrossJump and
  4476. not RegUsedBetween(p_TargetReg, p, hp2) and
  4477. not RegReadByInstruction(p_TargetReg, hp2) then
  4478. begin
  4479. { Register is not used before it is overwritten }
  4480. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4481. RemoveCurrentp(p, hp1);
  4482. Result := True;
  4483. Exit;
  4484. end;
  4485. if (taicpu(p).oper[0]^.typ = top_const) and
  4486. (taicpu(hp2).oper[0]^.typ = top_const) then
  4487. begin
  4488. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4489. begin
  4490. { Same value - register hasn't changed }
  4491. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4492. RemoveInstruction(hp2);
  4493. Include(OptsToCheck, aoc_ForceNewIteration);
  4494. { See if there's more we can optimise }
  4495. Continue;
  4496. end;
  4497. end;
  4498. {$ifdef x86_64}
  4499. end
  4500. { Change:
  4501. movl %reg1l,%reg2l
  4502. ...
  4503. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4504. To:
  4505. movl %reg1l,%reg2l
  4506. ...
  4507. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4508. If %reg1 = %reg3, convert to:
  4509. movl %reg1l,%reg2l
  4510. ...
  4511. andl %reg1l,%reg1l
  4512. }
  4513. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4514. (taicpu(p).oper[0]^.typ = top_reg) and
  4515. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4516. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4517. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4518. begin
  4519. TempRegUsed :=
  4520. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4521. RegReadByInstruction(p_TargetReg, hp3) or
  4522. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4523. taicpu(hp2).opsize := S_L;
  4524. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4525. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4526. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4527. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4528. begin
  4529. { %reg1 = %reg3 }
  4530. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4531. taicpu(hp2).opcode := A_AND;
  4532. end
  4533. else
  4534. begin
  4535. { %reg1 <> %reg3 }
  4536. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4537. end;
  4538. if not TempRegUsed then
  4539. begin
  4540. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4541. RemoveCurrentP(p, hp1);
  4542. Result := True;
  4543. Exit;
  4544. end
  4545. else
  4546. begin
  4547. { Initial instruction wasn't actually changed }
  4548. Include(OptsToCheck, aoc_ForceNewIteration);
  4549. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4550. appears below since %reg1 has technically changed }
  4551. if taicpu(hp2).opcode = A_AND then
  4552. Break;
  4553. end;
  4554. {$endif x86_64}
  4555. end
  4556. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4557. GetNextInstruction(hp2, hp4) and
  4558. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4559. { Optimise the following first:
  4560. movl [mem1],reg1
  4561. movl [mem1],reg2
  4562. to
  4563. movl [mem1],reg1
  4564. movl reg1,reg2
  4565. If [mem1] contains the target register and reg1 is the
  4566. the source register, this optimisation will get missed
  4567. and produce less efficient code later on.
  4568. }
  4569. if CheckMovMov2MovMov2(hp2, hp4) then
  4570. { Initial instruction wasn't actually changed }
  4571. Include(OptsToCheck, aoc_ForceNewIteration);
  4572. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4573. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4574. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4575. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4576. begin
  4577. {
  4578. Change from:
  4579. mov ###, %reg
  4580. ...
  4581. movs/z %reg,%reg (Same register, just different sizes)
  4582. To:
  4583. movs/z ###, %reg (Longer version)
  4584. ...
  4585. (remove)
  4586. }
  4587. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4588. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4589. { Keep the first instruction as mov if ### is a constant }
  4590. if taicpu(p).oper[0]^.typ = top_const then
  4591. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4592. else
  4593. begin
  4594. taicpu(p).opcode := taicpu(hp2).opcode;
  4595. taicpu(p).opsize := taicpu(hp2).opsize;
  4596. end;
  4597. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4598. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4599. RemoveInstruction(hp2);
  4600. Result := True;
  4601. JumpTracking.Free;
  4602. Exit;
  4603. end;
  4604. else
  4605. { Move down to the if-block below };
  4606. end;
  4607. { Also catches MOV/S/Z instructions that aren't modified }
  4608. if taicpu(p).oper[0]^.typ = top_reg then
  4609. begin
  4610. p_SourceReg := taicpu(p).oper[0]^.reg;
  4611. if
  4612. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4613. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4614. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4615. begin
  4616. Result := True;
  4617. { Just in case something didn't get modified (e.g. an
  4618. implicit register). Also, if it does read from this
  4619. register, then there's no longer an advantage to
  4620. changing the register on subsequent instructions.}
  4621. if not RegReadByInstruction(p_TargetReg, hp2) then
  4622. begin
  4623. { If a conditional jump was crossed, do not delete
  4624. the original MOV no matter what }
  4625. if not CrossJump and
  4626. { RegEndOfLife returns True if the register is
  4627. deallocated before the next instruction or has
  4628. been loaded with a new value }
  4629. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4630. begin
  4631. { We can remove the original MOV }
  4632. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4633. RemoveCurrentp(p, hp1);
  4634. JumpTracking.Free;
  4635. Result := True;
  4636. Exit;
  4637. end;
  4638. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4639. begin
  4640. { See if there's more we can optimise }
  4641. hp3 := hp2;
  4642. Continue;
  4643. end;
  4644. end;
  4645. end;
  4646. end;
  4647. { Break out of the while loop under normal circumstances }
  4648. Break;
  4649. end;
  4650. JumpTracking.Free;
  4651. end;
  4652. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4653. (taicpu(p).oper[1]^.typ = top_reg) and
  4654. (taicpu(p).opsize = S_L) and
  4655. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4656. (hp2.typ = ait_instruction) and
  4657. (taicpu(hp2).opcode = A_AND) and
  4658. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4659. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4660. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4661. ) then
  4662. begin
  4663. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4664. begin
  4665. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4666. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4667. begin
  4668. { Optimize out:
  4669. mov x, %reg
  4670. and ffffffffh, %reg
  4671. }
  4672. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4673. RemoveInstruction(hp2);
  4674. Result:=true;
  4675. exit;
  4676. end;
  4677. end;
  4678. end;
  4679. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4680. x >= RetOffset) as it doesn't do anything (it writes either to a
  4681. parameter or to the temporary storage room for the function
  4682. result)
  4683. }
  4684. if IsExitCode(hp1) and
  4685. (taicpu(p).oper[1]^.typ = top_ref) and
  4686. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4687. (
  4688. (
  4689. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4690. not (
  4691. assigned(current_procinfo.procdef.funcretsym) and
  4692. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4693. )
  4694. ) or
  4695. { Also discard writes to the stack that are below the base pointer,
  4696. as this is temporary storage rather than a function result on the
  4697. stack, say. }
  4698. (
  4699. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4700. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4701. )
  4702. ) then
  4703. begin
  4704. RemoveCurrentp(p, hp1);
  4705. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4706. RemoveLastDeallocForFuncRes(p);
  4707. Result:=true;
  4708. exit;
  4709. end;
  4710. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4711. begin
  4712. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4713. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4714. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4715. begin
  4716. { change
  4717. mov reg1, mem1
  4718. test/cmp x, mem1
  4719. to
  4720. mov reg1, mem1
  4721. test/cmp x, reg1
  4722. }
  4723. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4724. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4725. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4726. Result := True;
  4727. Exit;
  4728. end;
  4729. if DoMovCmpMemOpt(p, hp1) then
  4730. begin
  4731. Result := True;
  4732. Exit;
  4733. end;
  4734. end;
  4735. if (taicpu(p).oper[1]^.typ = top_reg) and
  4736. (hp1.typ = ait_instruction) and
  4737. GetNextInstruction(hp1, hp2) and
  4738. MatchInstruction(hp2,A_MOV,[]) and
  4739. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4740. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4741. (
  4742. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4743. {$ifdef x86_64}
  4744. or
  4745. (
  4746. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4747. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4748. )
  4749. {$endif x86_64}
  4750. ) then
  4751. begin
  4752. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4753. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4754. { change movsX/movzX reg/ref, reg2
  4755. add/sub/or/... reg3/$const, reg2
  4756. mov reg2 reg/ref
  4757. dealloc reg2
  4758. to
  4759. add/sub/or/... reg3/$const, reg/ref }
  4760. begin
  4761. TransferUsedRegs(TmpUsedRegs);
  4762. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4763. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4764. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4765. begin
  4766. { by example:
  4767. movswl %si,%eax movswl %si,%eax p
  4768. decl %eax addl %edx,%eax hp1
  4769. movw %ax,%si movw %ax,%si hp2
  4770. ->
  4771. movswl %si,%eax movswl %si,%eax p
  4772. decw %eax addw %edx,%eax hp1
  4773. movw %ax,%si movw %ax,%si hp2
  4774. }
  4775. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4776. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4777. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4778. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4779. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4780. {
  4781. ->
  4782. movswl %si,%eax movswl %si,%eax p
  4783. decw %si addw %dx,%si hp1
  4784. movw %ax,%si movw %ax,%si hp2
  4785. }
  4786. case taicpu(hp1).ops of
  4787. 1:
  4788. begin
  4789. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4790. if taicpu(hp1).oper[0]^.typ=top_reg then
  4791. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4792. end;
  4793. 2:
  4794. begin
  4795. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4796. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4797. (taicpu(hp1).opcode<>A_SHL) and
  4798. (taicpu(hp1).opcode<>A_SHR) and
  4799. (taicpu(hp1).opcode<>A_SAR) then
  4800. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4801. end;
  4802. else
  4803. internalerror(2008042701);
  4804. end;
  4805. {
  4806. ->
  4807. decw %si addw %dx,%si p
  4808. }
  4809. RemoveInstruction(hp2);
  4810. RemoveCurrentP(p, hp1);
  4811. Result:=True;
  4812. Exit;
  4813. end;
  4814. end;
  4815. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4816. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4817. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4818. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4819. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4820. ) and
  4821. { if ref contains a symbol, we cannot change its size to a smaller size }
  4822. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4823. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4824. )
  4825. {$ifdef i386}
  4826. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4827. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4828. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4829. {$endif i386}
  4830. then
  4831. { change movsX/movzX reg/ref, reg2
  4832. add/sub/or/... regX/$const, reg2
  4833. mov reg2, reg3
  4834. dealloc reg2
  4835. to
  4836. movsX/movzX reg/ref, reg3
  4837. add/sub/or/... reg3/$const, reg3
  4838. }
  4839. begin
  4840. TransferUsedRegs(TmpUsedRegs);
  4841. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4842. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4843. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4844. begin
  4845. { by example:
  4846. movswl %si,%eax movswl %si,%eax p
  4847. decl %eax addl %edx,%eax hp1
  4848. movw %ax,%si movw %ax,%si hp2
  4849. ->
  4850. movswl %si,%eax movswl %si,%eax p
  4851. decw %eax addw %edx,%eax hp1
  4852. movw %ax,%si movw %ax,%si hp2
  4853. }
  4854. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4855. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4856. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4857. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4858. { limit size of constants as well to avoid assembler errors, but
  4859. check opsize to avoid overflow when left shifting the 1 }
  4860. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4861. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4862. {$ifdef x86_64}
  4863. { Be careful of, for example:
  4864. movl %reg1,%reg2
  4865. addl %reg3,%reg2
  4866. movq %reg2,%reg4
  4867. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4868. }
  4869. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4870. begin
  4871. taicpu(hp2).changeopsize(S_L);
  4872. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4873. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4874. end;
  4875. {$endif x86_64}
  4876. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4877. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4878. if taicpu(p).oper[0]^.typ=top_reg then
  4879. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4880. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4881. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4882. {
  4883. ->
  4884. movswl %si,%eax movswl %si,%eax p
  4885. decw %si addw %dx,%si hp1
  4886. movw %ax,%si movw %ax,%si hp2
  4887. }
  4888. case taicpu(hp1).ops of
  4889. 1:
  4890. begin
  4891. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4892. if taicpu(hp1).oper[0]^.typ=top_reg then
  4893. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4894. end;
  4895. 2:
  4896. begin
  4897. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4898. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4899. (taicpu(hp1).opcode<>A_SHL) and
  4900. (taicpu(hp1).opcode<>A_SHR) and
  4901. (taicpu(hp1).opcode<>A_SAR) then
  4902. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4903. end;
  4904. else
  4905. internalerror(2018111801);
  4906. end;
  4907. {
  4908. ->
  4909. decw %si addw %dx,%si p
  4910. }
  4911. RemoveInstruction(hp2);
  4912. end;
  4913. end;
  4914. end;
  4915. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4916. GetNextInstruction(hp1, hp2) and
  4917. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4918. MatchOperand(Taicpu(p).oper[0]^,0) and
  4919. (Taicpu(p).oper[1]^.typ = top_reg) and
  4920. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4921. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4922. { mov reg1,0
  4923. bts reg1,operand1 --> mov reg1,operand2
  4924. or reg1,operand2 bts reg1,operand1}
  4925. begin
  4926. Taicpu(hp2).opcode:=A_MOV;
  4927. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4928. asml.remove(hp1);
  4929. insertllitem(hp2,hp2.next,hp1);
  4930. RemoveCurrentp(p, hp1);
  4931. Result:=true;
  4932. exit;
  4933. end;
  4934. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4935. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4936. GetNextInstruction(hp1, hp2) and
  4937. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4938. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4939. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4940. { change
  4941. mov reg1,reg2
  4942. sub reg3,reg2
  4943. cmp reg3,reg1
  4944. into
  4945. mov reg1,reg2
  4946. sub reg3,reg2
  4947. }
  4948. begin
  4949. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4950. RemoveInstruction(hp2);
  4951. Result:=true;
  4952. exit;
  4953. end;
  4954. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4955. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4956. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4957. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4958. begin
  4959. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4960. {$ifdef x86_64}
  4961. { Convert:
  4962. movq x(ref),%reg64
  4963. shrq y,%reg64
  4964. To:
  4965. movl x+4(ref),%reg32
  4966. shrl y-32,%reg32 (Remove if y = 32)
  4967. }
  4968. if (taicpu(p).opsize = S_Q) and
  4969. (taicpu(hp1).opcode = A_SHR) and
  4970. (taicpu(hp1).oper[0]^.val >= 32) then
  4971. begin
  4972. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4973. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4974. { Convert to 32-bit }
  4975. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4976. taicpu(p).opsize := S_L;
  4977. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4978. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4979. if (taicpu(hp1).oper[0]^.val = 32) then
  4980. begin
  4981. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4982. RemoveInstruction(hp1);
  4983. end
  4984. else
  4985. begin
  4986. { This will potentially open up more arithmetic operations since
  4987. the peephole optimizer now has a big hint that only the lower
  4988. 32 bits are currently in use (and opcodes are smaller in size) }
  4989. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4990. taicpu(hp1).opsize := S_L;
  4991. Dec(taicpu(hp1).oper[0]^.val, 32);
  4992. DebugMsg(SPeepholeOptimization + PreMessage +
  4993. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4994. end;
  4995. Result := True;
  4996. Exit;
  4997. end;
  4998. {$endif x86_64}
  4999. { Convert:
  5000. movl x(ref),%reg
  5001. shrl $24,%reg
  5002. To:
  5003. movzbl x+3(ref),%reg
  5004. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  5005. Also accept sar instead of shr, but convert to movsx instead of movzx
  5006. }
  5007. if taicpu(hp1).opcode = A_SHR then
  5008. MovUnaligned := A_MOVZX
  5009. else
  5010. MovUnaligned := A_MOVSX;
  5011. NewSize := S_NO;
  5012. NewOffset := 0;
  5013. case taicpu(p).opsize of
  5014. S_B:
  5015. { No valid combinations };
  5016. S_W:
  5017. if (taicpu(hp1).oper[0]^.val = 8) then
  5018. begin
  5019. NewSize := S_BW;
  5020. NewOffset := 1;
  5021. end;
  5022. S_L:
  5023. case taicpu(hp1).oper[0]^.val of
  5024. 16:
  5025. begin
  5026. NewSize := S_WL;
  5027. NewOffset := 2;
  5028. end;
  5029. 24:
  5030. begin
  5031. NewSize := S_BL;
  5032. NewOffset := 3;
  5033. end;
  5034. else
  5035. ;
  5036. end;
  5037. {$ifdef x86_64}
  5038. S_Q:
  5039. case taicpu(hp1).oper[0]^.val of
  5040. 32:
  5041. begin
  5042. if taicpu(hp1).opcode = A_SAR then
  5043. begin
  5044. { 32-bit to 64-bit is a distinct instruction }
  5045. MovUnaligned := A_MOVSXD;
  5046. NewSize := S_LQ;
  5047. NewOffset := 4;
  5048. end
  5049. else
  5050. { Should have been handled by MovShr2Mov above }
  5051. InternalError(2022081811);
  5052. end;
  5053. 48:
  5054. begin
  5055. NewSize := S_WQ;
  5056. NewOffset := 6;
  5057. end;
  5058. 56:
  5059. begin
  5060. NewSize := S_BQ;
  5061. NewOffset := 7;
  5062. end;
  5063. else
  5064. ;
  5065. end;
  5066. {$endif x86_64}
  5067. else
  5068. InternalError(2022081810);
  5069. end;
  5070. if (NewSize <> S_NO) and
  5071. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5072. begin
  5073. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5074. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5075. debug_op2str(MovUnaligned);
  5076. {$ifdef x86_64}
  5077. if MovUnaligned <> A_MOVSXD then
  5078. { Don't add size suffix for MOVSXD }
  5079. {$endif x86_64}
  5080. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5081. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5082. taicpu(p).opcode := MovUnaligned;
  5083. taicpu(p).opsize := NewSize;
  5084. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5085. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5086. RemoveInstruction(hp1);
  5087. Result := True;
  5088. Exit;
  5089. end;
  5090. end;
  5091. { Backward optimisation shared with OptPass2MOV }
  5092. if FuncMov2Func(p, hp1) then
  5093. begin
  5094. Result := True;
  5095. Exit;
  5096. end;
  5097. end;
  5098. function TX86AsmOptimizer.OptPass1MOVD(var p : tai) : boolean;
  5099. { This function also handles the 64-bit version, MOVQ }
  5100. var
  5101. hp1: tai;
  5102. begin
  5103. Result:=false;
  5104. { Change:
  5105. movd/q %xmm0, %reg
  5106. ...
  5107. movl/q %reg, (ref)
  5108. (dealloc %reg)
  5109. To:
  5110. movd/q %xmm0, (ref)
  5111. }
  5112. if MatchOpType(taicpu(p),top_reg,top_reg) and
  5113. (GetRegType(taicpu(p).oper[0]^.reg)=R_MMREGISTER) and
  5114. (GetRegType(taicpu(p).oper[1]^.reg)=R_INTREGISTER) and
  5115. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  5116. MatchInstruction(hp1, A_MOV, []) and
  5117. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  5118. (taicpu(hp1).oper[1]^.typ=top_ref) and
  5119. not RegInRef(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.ref^) then
  5120. begin
  5121. TransferUsedRegs(TmpUsedRegs);
  5122. UpdateUsedRegsBetween(TmpUsedRegs,p,hp1);
  5123. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  5124. begin
  5125. if (
  5126. { Instructions are always adjacent under -O2 and under }
  5127. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5128. (
  5129. (
  5130. (taicpu(hp1).oper[1]^.ref^.base=NR_NO) or
  5131. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.base,p,hp1)
  5132. ) and
  5133. (
  5134. (taicpu(hp1).oper[1]^.ref^.index=NR_NO) or
  5135. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.index,p,hp1)
  5136. )
  5137. )
  5138. ) then
  5139. begin
  5140. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1a)',p);
  5141. taicpu(p).loadref(1,taicpu(hp1).oper[1]^.ref^);
  5142. { loadref increases the reference count, so decrement it again }
  5143. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5144. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5145. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5146. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5147. RemoveInstruction(hp1);
  5148. Include(OptsToCheck, aoc_ForceNewIteration);
  5149. end
  5150. else if not RegModifiedBetween(taicpu(p).oper[0]^.reg,p,hp1) then
  5151. begin
  5152. { Still possible to optimise if hp1 is converted instead }
  5153. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1b)',hp1);
  5154. { Decrement the reference prior to replacing it }
  5155. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5156. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5157. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5158. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5159. taicpu(hp1).opcode:=taicpu(p).opcode;
  5160. taicpu(hp1).opsize:=taicpu(p).opsize;
  5161. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  5162. TransferUsedRegs(TmpUsedRegs);
  5163. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,TmpUsedRegs);
  5164. RemoveCurrentP(p);
  5165. Result:=True;
  5166. Exit;
  5167. end;
  5168. end;
  5169. end;
  5170. end;
  5171. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5172. var
  5173. hp1 : tai;
  5174. begin
  5175. Result:=false;
  5176. if taicpu(p).ops <> 2 then
  5177. exit;
  5178. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5179. GetNextInstruction(p,hp1) then
  5180. begin
  5181. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5182. (taicpu(hp1).ops = 2) then
  5183. begin
  5184. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5185. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5186. { movXX reg1, mem1 or movXX mem1, reg1
  5187. movXX mem2, reg2 movXX reg2, mem2}
  5188. begin
  5189. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5190. { movXX reg1, mem1 or movXX mem1, reg1
  5191. movXX mem2, reg1 movXX reg2, mem1}
  5192. begin
  5193. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5194. begin
  5195. { Removes the second statement from
  5196. movXX reg1, mem1/reg2
  5197. movXX mem1/reg2, reg1
  5198. }
  5199. if taicpu(p).oper[0]^.typ=top_reg then
  5200. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5201. { Removes the second statement from
  5202. movXX mem1/reg1, reg2
  5203. movXX reg2, mem1/reg1
  5204. }
  5205. if (taicpu(p).oper[1]^.typ=top_reg) and
  5206. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5207. begin
  5208. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5209. RemoveInstruction(hp1);
  5210. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5211. Result:=true;
  5212. exit;
  5213. end
  5214. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5215. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5216. begin
  5217. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5218. RemoveInstruction(hp1);
  5219. Result:=true;
  5220. exit;
  5221. end;
  5222. end
  5223. end;
  5224. end;
  5225. end;
  5226. end;
  5227. end;
  5228. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5229. var
  5230. hp1 : tai;
  5231. begin
  5232. result:=false;
  5233. { replace
  5234. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5235. MovX %mreg2,%mreg1
  5236. dealloc %mreg2
  5237. by
  5238. <Op>X %mreg2,%mreg1
  5239. ?
  5240. }
  5241. if GetNextInstruction(p,hp1) and
  5242. { we mix single and double opperations here because we assume that the compiler
  5243. generates vmovapd only after double operations and vmovaps only after single operations }
  5244. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5245. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5246. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5247. (taicpu(p).oper[0]^.typ=top_reg) then
  5248. begin
  5249. TransferUsedRegs(TmpUsedRegs);
  5250. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5251. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5252. begin
  5253. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5254. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5255. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5256. RemoveInstruction(hp1);
  5257. result:=true;
  5258. end;
  5259. end;
  5260. end;
  5261. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5262. var
  5263. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5264. JumpLabel, JumpLabel_dist: TAsmLabel;
  5265. FirstValue, SecondValue: TCGInt;
  5266. function OptimizeJump(var InputP: tai): Boolean;
  5267. var
  5268. TempBool: Boolean;
  5269. begin
  5270. Result := False;
  5271. TempBool := True;
  5272. if DoJumpOptimizations(InputP, TempBool) or
  5273. not TempBool then
  5274. begin
  5275. Result := True;
  5276. if Assigned(InputP) then
  5277. begin
  5278. { CollapseZeroDistJump will be set to the label or an align
  5279. before it after the jump if it optimises, whether or not
  5280. the label is live or dead }
  5281. if (InputP.typ = ait_align) or
  5282. (
  5283. (InputP.typ = ait_label) and
  5284. not (tai_label(InputP).labsym.is_used)
  5285. ) then
  5286. GetNextInstruction(InputP, InputP);
  5287. end;
  5288. Exit;
  5289. end;
  5290. end;
  5291. begin
  5292. Result := False;
  5293. if (taicpu(p).oper[0]^.typ = top_const) and
  5294. (taicpu(p).oper[0]^.val <> -1) then
  5295. begin
  5296. { Convert unsigned maximum constants to -1 to aid optimisation }
  5297. case taicpu(p).opsize of
  5298. S_B:
  5299. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5300. begin
  5301. taicpu(p).oper[0]^.val := -1;
  5302. Result := True;
  5303. Exit;
  5304. end;
  5305. S_W:
  5306. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5307. begin
  5308. taicpu(p).oper[0]^.val := -1;
  5309. Result := True;
  5310. Exit;
  5311. end;
  5312. S_L:
  5313. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5314. begin
  5315. taicpu(p).oper[0]^.val := -1;
  5316. Result := True;
  5317. Exit;
  5318. end;
  5319. {$ifdef x86_64}
  5320. S_Q:
  5321. { Storing anything greater than $7FFFFFFF is not possible so do
  5322. nothing };
  5323. {$endif x86_64}
  5324. else
  5325. InternalError(2021121001);
  5326. end;
  5327. end;
  5328. if GetNextInstruction(p, hp1) and
  5329. TrySwapMovCmp(p, hp1) then
  5330. begin
  5331. Result := True;
  5332. Exit;
  5333. end;
  5334. p_label := nil;
  5335. JumpLabel := nil;
  5336. if MatchInstruction(hp1, A_Jcc, []) then
  5337. begin
  5338. if OptimizeJump(hp1) then
  5339. begin
  5340. Result := True;
  5341. if Assigned(hp1) then
  5342. begin
  5343. { CollapseZeroDistJump will be set to the label or an align
  5344. before it after the jump if it optimises, whether or not
  5345. the label is live or dead }
  5346. if (hp1.typ = ait_align) or
  5347. (
  5348. (hp1.typ = ait_label) and
  5349. not (tai_label(hp1).labsym.is_used)
  5350. ) then
  5351. GetNextInstruction(hp1, hp1);
  5352. end;
  5353. TransferUsedRegs(TmpUsedRegs);
  5354. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5355. if not Assigned(hp1) or
  5356. (
  5357. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5358. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5359. ) then
  5360. begin
  5361. { No more conditional jumps; conditional statement is no longer required }
  5362. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5363. RemoveCurrentP(p);
  5364. end;
  5365. Exit;
  5366. end;
  5367. if IsJumpToLabel(taicpu(hp1)) then
  5368. begin
  5369. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5370. if Assigned(JumpLabel) then
  5371. p_label := getlabelwithsym(JumpLabel);
  5372. end;
  5373. end;
  5374. { Search for:
  5375. test $x,(reg/ref)
  5376. jne @lbl1
  5377. test $y,(reg/ref) (same register or reference)
  5378. jne @lbl1
  5379. Change to:
  5380. test $(x or y),(reg/ref)
  5381. jne @lbl1
  5382. (Note, this doesn't work with je instead of jne)
  5383. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5384. Also search for:
  5385. test $x,(reg/ref)
  5386. je @lbl1
  5387. ...
  5388. test $y,(reg/ref)
  5389. je/jne @lbl2
  5390. If (x or y) = x, then the second jump is deterministic
  5391. }
  5392. if (
  5393. (
  5394. (taicpu(p).oper[0]^.typ = top_const) or
  5395. (
  5396. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5397. (taicpu(p).oper[0]^.typ = top_reg) and
  5398. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5399. )
  5400. ) and
  5401. MatchInstruction(hp1, A_JCC, [])
  5402. ) then
  5403. begin
  5404. if (taicpu(p).oper[0]^.typ = top_reg) and
  5405. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5406. FirstValue := -1
  5407. else
  5408. FirstValue := taicpu(p).oper[0]^.val;
  5409. { If we have several test/jne's in a row, it might be the case that
  5410. the second label doesn't go to the same location, but the one
  5411. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5412. so accommodate for this with a while loop.
  5413. }
  5414. hp1_last := hp1;
  5415. while (
  5416. (
  5417. (taicpu(p).oper[1]^.typ = top_reg) and
  5418. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5419. ) or GetNextInstruction(hp1_last, p_dist)
  5420. ) and (p_dist.typ = ait_instruction) do
  5421. begin
  5422. if (
  5423. (
  5424. (taicpu(p_dist).opcode = A_TEST) and
  5425. (
  5426. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5427. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5428. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5429. )
  5430. ) or
  5431. (
  5432. { cmp 0,%reg = test %reg,%reg }
  5433. (taicpu(p_dist).opcode = A_CMP) and
  5434. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5435. )
  5436. ) and
  5437. { Make sure the destination operands are actually the same }
  5438. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5439. GetNextInstruction(p_dist, hp1_dist) and
  5440. MatchInstruction(hp1_dist, A_JCC, []) then
  5441. begin
  5442. if OptimizeJump(hp1_dist) then
  5443. begin
  5444. Result := True;
  5445. Exit;
  5446. end;
  5447. if
  5448. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5449. (
  5450. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5451. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5452. ) then
  5453. SecondValue := -1
  5454. else
  5455. SecondValue := taicpu(p_dist).oper[0]^.val;
  5456. { If both of the TEST constants are identical, delete the
  5457. second TEST that is unnecessary (be careful though, just
  5458. in case the flags are modified in between) }
  5459. if (FirstValue = SecondValue) then
  5460. begin
  5461. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5462. begin
  5463. { Since the second jump's condition is a subset of the first, we
  5464. know it will never branch because the first jump dominates it.
  5465. Get it out of the way now rather than wait for the jump
  5466. optimisations for a speed boost. }
  5467. if IsJumpToLabel(taicpu(hp1_dist)) then
  5468. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5469. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5470. RemoveInstruction(hp1_dist);
  5471. Result := True;
  5472. end
  5473. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5474. begin
  5475. { If the inverse of the first condition is a subset of the second,
  5476. the second one will definitely branch if the first one doesn't }
  5477. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5478. { We can remove the TEST instruction too }
  5479. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5480. RemoveInstruction(p_dist);
  5481. MakeUnconditional(taicpu(hp1_dist));
  5482. RemoveDeadCodeAfterJump(hp1_dist);
  5483. { Since the jump is now unconditional, we can't
  5484. continue any further with this particular
  5485. optimisation. The original TEST is still intact
  5486. though, so there might be something else we can
  5487. do }
  5488. Include(OptsToCheck, aoc_ForceNewIteration);
  5489. Break;
  5490. end;
  5491. if Result or
  5492. { If a jump wasn't removed or made unconditional, only
  5493. remove the identical TEST instruction if the flags
  5494. weren't modified }
  5495. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5496. begin
  5497. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5498. RemoveInstruction(p_dist);
  5499. { If the jump was removed or made unconditional, we
  5500. don't need to allocate NR_DEFAULTFLAGS over the
  5501. entire range }
  5502. if not Result then
  5503. begin
  5504. { Mark the flags as 'in use' over the entire range }
  5505. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5506. { Speed gain - continue search from the Jcc instruction }
  5507. hp1_last := hp1_dist;
  5508. { Only the TEST instruction was removed, and the
  5509. original was unchanged, so we can safely do
  5510. another iteration of the while loop }
  5511. Include(OptsToCheck, aoc_ForceNewIteration);
  5512. Continue;
  5513. end;
  5514. Exit;
  5515. end;
  5516. end;
  5517. hp1_last := nil;
  5518. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5519. (
  5520. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5521. { Always adjacent under -O2 and under }
  5522. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5523. (
  5524. GetNextInstruction(hp1, hp1_last) and
  5525. (hp1_last = p_dist)
  5526. )
  5527. ) and
  5528. (
  5529. (
  5530. { Test the following variant:
  5531. test $x,(reg/ref)
  5532. jne @lbl1
  5533. test $y,(reg/ref)
  5534. je @lbl2
  5535. @lbl1:
  5536. Becomes:
  5537. test $(x or y),(reg/ref)
  5538. je @lbl2
  5539. @lbl1: (may become a dead label)
  5540. }
  5541. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5542. GetNextInstruction(hp1_dist, hp1_last) and
  5543. (hp1_last = p_label)
  5544. ) or
  5545. (
  5546. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5547. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5548. then the second jump will never branch, so it can also be
  5549. removed regardless of where it goes }
  5550. (
  5551. (FirstValue = -1) or
  5552. (SecondValue = -1) or
  5553. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5554. )
  5555. )
  5556. ) then
  5557. begin
  5558. { Same jump location... can be a register since nothing's changed }
  5559. { If any of the entries are equivalent to test %reg,%reg, then the
  5560. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5561. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5562. if (hp1_last = p_label) then
  5563. begin
  5564. { Variant }
  5565. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5566. RemoveInstruction(p_dist);
  5567. if Assigned(JumpLabel) then
  5568. JumpLabel.decrefs;
  5569. RemoveInstruction(hp1);
  5570. end
  5571. else
  5572. begin
  5573. { Only remove the second test if no jumps or other conditional instructions follow }
  5574. TransferUsedRegs(TmpUsedRegs);
  5575. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5576. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5577. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5578. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5579. begin
  5580. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5581. RemoveInstruction(p_dist);
  5582. { Remove the first jump, not the second, to keep
  5583. any register deallocations between the second
  5584. TEST/JNE pair in the same place. Aids future
  5585. optimisation. }
  5586. if Assigned(JumpLabel) then
  5587. JumpLabel.decrefs;
  5588. RemoveInstruction(hp1);
  5589. end
  5590. else
  5591. begin
  5592. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5593. if IsJumpToLabel(taicpu(hp1_dist)) then
  5594. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5595. { Remove second jump in this instance }
  5596. RemoveInstruction(hp1_dist);
  5597. end;
  5598. end;
  5599. Result := True;
  5600. Exit;
  5601. end;
  5602. end;
  5603. if { If -O2 and under, it may stop on any old instruction }
  5604. (cs_opt_level3 in current_settings.optimizerswitches) and
  5605. (taicpu(p).oper[1]^.typ = top_reg) and
  5606. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5607. begin
  5608. hp1_last := p_dist;
  5609. Continue;
  5610. end;
  5611. Break;
  5612. end;
  5613. end;
  5614. { Search for:
  5615. test %reg,%reg
  5616. j(c1) @lbl1
  5617. ...
  5618. @lbl:
  5619. test %reg,%reg (same register)
  5620. j(c2) @lbl2
  5621. If c2 is a subset of c1, change to:
  5622. test %reg,%reg
  5623. j(c1) @lbl2
  5624. (@lbl1 may become a dead label as a result)
  5625. }
  5626. if (taicpu(p).oper[1]^.typ = top_reg) and
  5627. (taicpu(p).oper[0]^.typ = top_reg) and
  5628. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5629. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5630. Assigned(p_label) and
  5631. GetNextInstruction(p_label, p_dist) and
  5632. MatchInstruction(p_dist, A_TEST, []) and
  5633. { It's fine if the second test uses smaller sub-registers }
  5634. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5635. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5636. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5637. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5638. GetNextInstruction(p_dist, hp1_dist) and
  5639. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5640. begin
  5641. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5642. if JumpLabel = JumpLabel_dist then
  5643. { This is an infinite loop }
  5644. Exit;
  5645. { Best optimisation when the first condition is a subset (or equal) of the second }
  5646. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5647. begin
  5648. { Any registers used here will already be allocated }
  5649. if Assigned(JumpLabel) then
  5650. JumpLabel.DecRefs;
  5651. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5652. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5653. Result := True;
  5654. Exit;
  5655. end;
  5656. end;
  5657. end;
  5658. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5659. var
  5660. hp1, hp2: tai;
  5661. ActiveReg: TRegister;
  5662. OldOffset: asizeint;
  5663. ThisConst: TCGInt;
  5664. function RegDeallocated: Boolean;
  5665. begin
  5666. TransferUsedRegs(TmpUsedRegs);
  5667. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5668. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5669. end;
  5670. begin
  5671. result:=false;
  5672. hp1 := nil;
  5673. { replace
  5674. addX const,%reg1
  5675. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5676. dealloc %reg1
  5677. by
  5678. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5679. }
  5680. if MatchOpType(taicpu(p),top_const,top_reg) then
  5681. begin
  5682. ActiveReg := taicpu(p).oper[1]^.reg;
  5683. { Ensures the entire register was updated }
  5684. if (taicpu(p).opsize >= S_L) and
  5685. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5686. MatchInstruction(hp1,A_LEA,[]) and
  5687. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5688. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5689. (
  5690. { Cover the case where the register in the reference is also the destination register }
  5691. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5692. (
  5693. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5694. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5695. RegDeallocated
  5696. )
  5697. ) then
  5698. begin
  5699. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5700. {$push}
  5701. {$R-}{$Q-}
  5702. { Explicitly disable overflow checking for these offset calculation
  5703. as those do not matter for the final result }
  5704. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5705. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5706. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5707. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5708. {$pop}
  5709. {$ifdef x86_64}
  5710. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5711. begin
  5712. { Overflow; abort }
  5713. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5714. end
  5715. else
  5716. {$endif x86_64}
  5717. begin
  5718. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5719. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5720. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5721. RemoveCurrentP(p, hp1)
  5722. else
  5723. RemoveCurrentP(p);
  5724. result:=true;
  5725. Exit;
  5726. end;
  5727. end;
  5728. if (
  5729. { Save calling GetNextInstructionUsingReg again }
  5730. Assigned(hp1) or
  5731. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5732. ) and
  5733. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5734. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5735. begin
  5736. { Make sure the flags aren't in use by the second operation }
  5737. TransferUsedRegs(TmpUsedRegs);
  5738. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5739. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5740. begin
  5741. if taicpu(hp1).oper[0]^.typ = top_const then
  5742. begin
  5743. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5744. if taicpu(hp1).opcode = A_ADD then
  5745. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5746. else
  5747. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5748. Result := True;
  5749. { Handle any overflows }
  5750. case taicpu(p).opsize of
  5751. S_B:
  5752. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5753. S_W:
  5754. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5755. S_L:
  5756. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5757. {$ifdef x86_64}
  5758. S_Q:
  5759. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5760. { Overflow; abort }
  5761. Result := False
  5762. else
  5763. taicpu(p).oper[0]^.val := ThisConst;
  5764. {$endif x86_64}
  5765. else
  5766. InternalError(2021102610);
  5767. end;
  5768. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5769. if Result then
  5770. begin
  5771. if (taicpu(p).oper[0]^.val < 0) and
  5772. (
  5773. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5774. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5775. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5776. ) then
  5777. begin
  5778. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5779. taicpu(p).opcode := A_SUB;
  5780. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5781. end
  5782. else
  5783. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5784. RemoveInstruction(hp1);
  5785. end;
  5786. end
  5787. else
  5788. begin
  5789. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5790. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5791. Asml.Remove(p);
  5792. Asml.InsertAfter(p, hp1);
  5793. p := hp1;
  5794. Result := True;
  5795. Exit;
  5796. end;
  5797. end;
  5798. end;
  5799. if DoArithCombineOpt(p) then
  5800. Result:=true;
  5801. end;
  5802. end;
  5803. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5804. var
  5805. hp1, hp2: tai;
  5806. ref: Integer;
  5807. saveref: treference;
  5808. offsetcalc: Int64;
  5809. TempReg: TRegister;
  5810. Multiple: TCGInt;
  5811. Adjacent, IntermediateRegDiscarded: Boolean;
  5812. begin
  5813. Result:=false;
  5814. { play save and throw an error if LEA uses a seg register prefix,
  5815. this is most likely an error somewhere else }
  5816. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5817. internalerror(2022022001);
  5818. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5819. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5820. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5821. (
  5822. { do not mess with leas accessing the stack pointer
  5823. unless it's a null operation }
  5824. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5825. (
  5826. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5827. (taicpu(p).oper[0]^.ref^.offset = 0)
  5828. )
  5829. ) and
  5830. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5831. begin
  5832. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5833. begin
  5834. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5835. begin
  5836. taicpu(p).opcode := A_MOV;
  5837. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5838. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5839. end
  5840. else
  5841. begin
  5842. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5843. RemoveCurrentP(p);
  5844. end;
  5845. Result:=true;
  5846. exit;
  5847. end
  5848. else if (
  5849. { continue to use lea to adjust the stack pointer,
  5850. it is the recommended way, but only if not optimizing for size }
  5851. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5852. (cs_opt_size in current_settings.optimizerswitches)
  5853. ) and
  5854. { If the flags register is in use, don't change the instruction
  5855. to an ADD otherwise this will scramble the flags. [Kit] }
  5856. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5857. ConvertLEA(taicpu(p)) then
  5858. begin
  5859. Result:=true;
  5860. exit;
  5861. end;
  5862. end;
  5863. { Don't optimise if the stack or frame pointer is the destination register }
  5864. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5865. Exit;
  5866. if GetNextInstruction(p,hp1) and
  5867. (hp1.typ=ait_instruction) then
  5868. begin
  5869. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5870. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5871. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5872. begin
  5873. TransferUsedRegs(TmpUsedRegs);
  5874. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5875. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5876. begin
  5877. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5878. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5879. RemoveInstruction(hp1);
  5880. result:=true;
  5881. exit;
  5882. end;
  5883. end;
  5884. { changes
  5885. lea <ref1>, reg1
  5886. <op> ...,<ref. with reg1>,...
  5887. to
  5888. <op> ...,<ref1>,... }
  5889. { find a reference which uses reg1 }
  5890. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  5891. ref:=0
  5892. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  5893. ref:=1
  5894. else
  5895. ref:=-1;
  5896. if (ref<>-1) and
  5897. { reg1 must be either the base or the index }
  5898. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5899. begin
  5900. { reg1 can be removed from the reference }
  5901. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5902. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5903. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5904. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5905. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5906. else
  5907. Internalerror(2019111201);
  5908. { check if the can insert all data of the lea into the second instruction }
  5909. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5910. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5911. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5912. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5913. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5914. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5915. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5916. {$ifdef x86_64}
  5917. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5918. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5919. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5920. )
  5921. {$endif x86_64}
  5922. then
  5923. begin
  5924. { reg1 might not used by the second instruction after it is remove from the reference }
  5925. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5926. begin
  5927. TransferUsedRegs(TmpUsedRegs);
  5928. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5929. { reg1 is not updated so it might not be used afterwards }
  5930. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5931. begin
  5932. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5933. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5934. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5935. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5936. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5937. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5938. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5939. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5940. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5941. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5942. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5943. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5944. RemoveCurrentP(p, hp1);
  5945. result:=true;
  5946. exit;
  5947. end
  5948. end;
  5949. end;
  5950. { recover }
  5951. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5952. end;
  5953. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5954. if Adjacent or
  5955. { Check further ahead (up to 2 instructions ahead for -O2) }
  5956. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5957. begin
  5958. { Check common LEA/LEA conditions }
  5959. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5960. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5961. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5962. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5963. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5964. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5965. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5966. (
  5967. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5968. calling it (since it calls GetNextInstruction) }
  5969. Adjacent or
  5970. (
  5971. (
  5972. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5973. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5974. ) and (
  5975. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5976. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5977. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5978. )
  5979. )
  5980. ) then
  5981. begin
  5982. TransferUsedRegs(TmpUsedRegs);
  5983. hp2 := p;
  5984. repeat
  5985. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5986. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5987. IntermediateRegDiscarded :=
  5988. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5989. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5990. { changes
  5991. lea offset1(regX,scale), reg1
  5992. lea offset2(reg1,reg1), reg2
  5993. to
  5994. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5995. and
  5996. lea offset1(regX,scale1), reg1
  5997. lea offset2(reg1,scale2), reg2
  5998. to
  5999. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  6000. and
  6001. lea offset1(regX,scale1), reg1
  6002. lea offset2(reg3,reg1,scale2), reg2
  6003. to
  6004. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  6005. ... so long as the final scale does not exceed 8
  6006. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  6007. }
  6008. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6009. (
  6010. { Don't optimise if size is a concern and the intermediate register remains in use }
  6011. IntermediateRegDiscarded or
  6012. (
  6013. not (cs_opt_size in current_settings.optimizerswitches) and
  6014. { If the intermediate register is not discarded, it must not
  6015. appear in the first LEA's reference. (Fixes #41166) }
  6016. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6017. )
  6018. ) and
  6019. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6020. (
  6021. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  6022. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6023. ) and (
  6024. (
  6025. { lea (reg1,scale2), reg2 variant }
  6026. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  6027. (
  6028. Adjacent or
  6029. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  6030. ) and
  6031. (
  6032. (
  6033. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  6034. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  6035. ) or (
  6036. { lea (regX,regX), reg1 variant }
  6037. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  6038. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  6039. )
  6040. )
  6041. ) or (
  6042. { lea (reg1,reg1), reg1 variant }
  6043. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6044. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  6045. )
  6046. ) then
  6047. begin
  6048. { Make everything homogeneous to make calculations easier }
  6049. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  6050. begin
  6051. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  6052. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  6053. taicpu(p).oper[0]^.ref^.scalefactor := 2
  6054. else
  6055. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  6056. taicpu(p).oper[0]^.ref^.base := NR_NO;
  6057. end;
  6058. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6059. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6060. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6061. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6062. begin
  6063. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6064. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  6065. begin
  6066. { Put the register to change in the index register }
  6067. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  6068. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  6069. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  6070. end;
  6071. { Change lea (reg,reg) to lea(,reg,2) }
  6072. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  6073. begin
  6074. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  6075. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  6076. end;
  6077. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  6078. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6079. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  6080. { Just to prevent miscalculations }
  6081. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  6082. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  6083. else
  6084. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  6085. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6086. if IntermediateRegDiscarded then
  6087. begin
  6088. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  6089. RemoveCurrentP(p);
  6090. end
  6091. else
  6092. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  6093. result:=true;
  6094. exit;
  6095. end;
  6096. end;
  6097. { changes
  6098. lea offset1(regX), reg1
  6099. lea offset2(reg1), reg2
  6100. to
  6101. lea offset1+offset2(regX), reg2 }
  6102. if (
  6103. { Don't optimise if size is a concern and the intermediate register remains in use }
  6104. IntermediateRegDiscarded or
  6105. (
  6106. not (cs_opt_size in current_settings.optimizerswitches) and
  6107. { If the intermediate register is not discarded, it must not
  6108. appear in the first LEA's reference. (Fixes #41166) }
  6109. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6110. )
  6111. ) and
  6112. (
  6113. (
  6114. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6115. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6116. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6117. ) or (
  6118. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6119. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6120. (
  6121. (
  6122. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6123. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6124. ) or (
  6125. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6126. (
  6127. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6128. (
  6129. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6130. (
  6131. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6132. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6133. )
  6134. )
  6135. )
  6136. )
  6137. )
  6138. )
  6139. ) then
  6140. begin
  6141. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6142. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6143. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6144. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6145. begin
  6146. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6147. begin
  6148. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6149. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6150. { if the register is used as index and base, we have to increase for base as well
  6151. and adapt base }
  6152. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6153. begin
  6154. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6155. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6156. end;
  6157. end
  6158. else
  6159. begin
  6160. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6161. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6162. end;
  6163. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6164. begin
  6165. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6166. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6167. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6168. { Catch the situation where the base = index
  6169. and treat this as *2. The scalefactor of
  6170. p will be 0 or 1 due to the conditional
  6171. checks above. Fixes i40647 }
  6172. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6173. else
  6174. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6175. end;
  6176. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6177. if IntermediateRegDiscarded then
  6178. begin
  6179. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6180. RemoveCurrentP(p);
  6181. end
  6182. else
  6183. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6184. result:=true;
  6185. exit;
  6186. end;
  6187. end;
  6188. end;
  6189. { Change:
  6190. leal/q $x(%reg1),%reg2
  6191. ...
  6192. shll/q $y,%reg2
  6193. To:
  6194. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6195. }
  6196. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6197. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6198. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6199. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6200. (taicpu(hp1).oper[0]^.val <= 3) then
  6201. begin
  6202. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6203. TransferUsedRegs(TmpUsedRegs);
  6204. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6205. if
  6206. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6207. (this works even if scalefactor is zero) }
  6208. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6209. { Ensure offset doesn't go out of bounds }
  6210. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6211. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6212. (
  6213. (
  6214. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6215. (
  6216. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6217. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6218. (
  6219. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6220. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6221. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6222. )
  6223. )
  6224. ) or (
  6225. (
  6226. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6227. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6228. ) and
  6229. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6230. )
  6231. ) then
  6232. begin
  6233. repeat
  6234. with taicpu(p).oper[0]^.ref^ do
  6235. begin
  6236. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6237. if index = base then
  6238. begin
  6239. if Multiple > 4 then
  6240. { Optimisation will no longer work because resultant
  6241. scale factor will exceed 8 }
  6242. Break;
  6243. base := NR_NO;
  6244. scalefactor := 2;
  6245. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6246. end
  6247. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6248. begin
  6249. { Scale factor only works on the index register }
  6250. index := base;
  6251. base := NR_NO;
  6252. end;
  6253. { For safety }
  6254. if scalefactor <= 1 then
  6255. begin
  6256. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6257. scalefactor := Multiple;
  6258. end
  6259. else
  6260. begin
  6261. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6262. scalefactor := scalefactor * Multiple;
  6263. end;
  6264. offset := offset * Multiple;
  6265. end;
  6266. RemoveInstruction(hp1);
  6267. Result := True;
  6268. Exit;
  6269. { This repeat..until loop exists for the benefit of Break }
  6270. until True;
  6271. end;
  6272. end;
  6273. end;
  6274. end;
  6275. end;
  6276. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6277. var
  6278. hp1 : tai;
  6279. SubInstr: Boolean;
  6280. ThisConst: TCGInt;
  6281. const
  6282. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6283. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6284. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6285. begin
  6286. Result := False;
  6287. if taicpu(p).oper[0]^.typ <> top_const then
  6288. { Should have been confirmed before calling }
  6289. InternalError(2021102601);
  6290. SubInstr := (taicpu(p).opcode = A_SUB);
  6291. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6292. GetLastInstruction(p, hp1) and
  6293. (hp1.typ = ait_instruction) and
  6294. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6295. begin
  6296. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6297. { Bad size }
  6298. InternalError(2022042001);
  6299. case taicpu(hp1).opcode Of
  6300. A_INC:
  6301. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6302. begin
  6303. if SubInstr then
  6304. ThisConst := taicpu(p).oper[0]^.val - 1
  6305. else
  6306. ThisConst := taicpu(p).oper[0]^.val + 1;
  6307. end
  6308. else
  6309. Exit;
  6310. A_DEC:
  6311. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6312. begin
  6313. if SubInstr then
  6314. ThisConst := taicpu(p).oper[0]^.val + 1
  6315. else
  6316. ThisConst := taicpu(p).oper[0]^.val - 1;
  6317. end
  6318. else
  6319. Exit;
  6320. A_SUB:
  6321. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6322. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6323. begin
  6324. if SubInstr then
  6325. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6326. else
  6327. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6328. end
  6329. else
  6330. Exit;
  6331. A_ADD:
  6332. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6333. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6334. begin
  6335. if SubInstr then
  6336. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6337. else
  6338. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6339. end
  6340. else
  6341. Exit;
  6342. else
  6343. Exit;
  6344. end;
  6345. { Check that the values are in range }
  6346. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6347. { Overflow; abort }
  6348. Exit;
  6349. if (ThisConst = 0) then
  6350. begin
  6351. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6352. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6353. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6354. RemoveInstruction(hp1);
  6355. hp1 := tai(p.next);
  6356. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6357. if not GetLastInstruction(hp1, p) then
  6358. p := hp1;
  6359. end
  6360. else
  6361. begin
  6362. if taicpu(hp1).opercnt=1 then
  6363. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6364. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6365. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6366. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6367. else
  6368. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6369. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6370. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6371. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6372. RemoveInstruction(hp1);
  6373. taicpu(p).loadconst(0, ThisConst);
  6374. end;
  6375. Result := True;
  6376. end;
  6377. end;
  6378. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6379. begin
  6380. Result := False;
  6381. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6382. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6383. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6384. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6385. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6386. (
  6387. (
  6388. (taicpu(hp1).opcode = A_TEST)
  6389. ) or (
  6390. (taicpu(hp1).opcode = A_CMP) and
  6391. { A sanity check more than anything }
  6392. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6393. )
  6394. ) then
  6395. begin
  6396. { change
  6397. mov mem, %reg
  6398. ...
  6399. cmp/test x, %reg / test %reg,%reg
  6400. (reg deallocated)
  6401. to
  6402. cmp/test x, mem / cmp 0, mem
  6403. }
  6404. TransferUsedRegs(TmpUsedRegs);
  6405. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6406. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6407. begin
  6408. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6409. if (taicpu(hp1).opcode = A_TEST) and
  6410. (
  6411. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6412. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6413. ) then
  6414. begin
  6415. taicpu(hp1).opcode := A_CMP;
  6416. taicpu(hp1).loadconst(0, 0);
  6417. end;
  6418. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6419. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6420. RemoveCurrentP(p);
  6421. if (p <> hp1) then
  6422. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6423. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6424. { Make sure the flags are allocated across the CMP instruction }
  6425. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6426. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6427. Result := True;
  6428. Exit;
  6429. end;
  6430. end;
  6431. end;
  6432. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6433. var
  6434. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6435. ThisReg, SecondReg: TRegister;
  6436. JumpLoc: TAsmLabel;
  6437. NewSize: TOpSize;
  6438. begin
  6439. Result := False;
  6440. {
  6441. Convert:
  6442. j<c> .L1
  6443. .L2:
  6444. mov 1,reg
  6445. jmp .L3 (or ret, although it might not be a RET yet)
  6446. .L1:
  6447. mov 0,reg
  6448. jmp .L3 (or ret)
  6449. ( As long as .L3 <> .L1 or .L2)
  6450. To:
  6451. mov 0,reg
  6452. set<not(c)> reg
  6453. jmp .L3 (or ret)
  6454. .L2:
  6455. mov 1,reg
  6456. jmp .L3 (or ret)
  6457. .L1:
  6458. mov 0,reg
  6459. jmp .L3 (or ret)
  6460. }
  6461. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6462. Exit;
  6463. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6464. if GetNextInstruction(hp_label, hp2) and
  6465. MatchInstruction(hp2,A_MOV,[]) and
  6466. (taicpu(hp2).oper[0]^.typ = top_const) and
  6467. (
  6468. (
  6469. (taicpu(hp2).oper[1]^.typ = top_reg)
  6470. {$ifdef i386}
  6471. { Under i386, ESI, EDI, EBP and ESP
  6472. don't have an 8-bit representation }
  6473. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6474. {$endif i386}
  6475. ) or (
  6476. {$ifdef i386}
  6477. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6478. {$endif i386}
  6479. (taicpu(hp2).opsize = S_B)
  6480. )
  6481. ) and
  6482. GetNextInstruction(hp2, hp3) and
  6483. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6484. (
  6485. (taicpu(hp3).opcode=A_RET) or
  6486. (
  6487. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6488. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6489. )
  6490. ) and
  6491. GetNextInstruction(hp3, hp4) and
  6492. FindLabel(JumpLoc, hp4) and
  6493. (
  6494. not (cs_opt_size in current_settings.optimizerswitches) or
  6495. { If the initial jump is the label's only reference, then it will
  6496. become a dead label if the other conditions are met and hence
  6497. remove at least 2 instructions, including a jump }
  6498. (JumpLoc.getrefs = 1)
  6499. ) and
  6500. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6501. that will be optimised out }
  6502. GetNextInstruction(hp4, hp5) and
  6503. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6504. (taicpu(hp5).oper[0]^.typ = top_const) and
  6505. (
  6506. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6507. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6508. ) and
  6509. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6510. GetNextInstruction(hp5,hp6) and
  6511. (
  6512. not (hp6.typ in [ait_align, ait_label]) or
  6513. SkipLabels(hp6, hp6)
  6514. ) and
  6515. (hp6.typ=ait_instruction) then
  6516. begin
  6517. { First, let's look at the two jumps that are hp3 and hp6 }
  6518. if not
  6519. (
  6520. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6521. (
  6522. (taicpu(hp6).opcode=A_RET) or
  6523. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6524. )
  6525. ) then
  6526. { If condition is False, then the JMP/RET instructions matched conventionally }
  6527. begin
  6528. { See if one of the jumps can be instantly converted into a RET }
  6529. if (taicpu(hp3).opcode=A_JMP) then
  6530. begin
  6531. { Reuse hp5 }
  6532. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6533. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6534. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6535. Exit;
  6536. if MatchInstruction(hp5, A_RET, []) then
  6537. begin
  6538. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6539. ConvertJumpToRET(hp3, hp5);
  6540. Result := True;
  6541. end
  6542. else
  6543. Exit;
  6544. end;
  6545. if (taicpu(hp6).opcode=A_JMP) then
  6546. begin
  6547. { Reuse hp5 }
  6548. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6549. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6550. Exit;
  6551. if MatchInstruction(hp5, A_RET, []) then
  6552. begin
  6553. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6554. ConvertJumpToRET(hp6, hp5);
  6555. Result := True;
  6556. end
  6557. else
  6558. Exit;
  6559. end;
  6560. if not
  6561. (
  6562. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6563. (
  6564. (taicpu(hp6).opcode=A_RET) or
  6565. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6566. )
  6567. ) then
  6568. { Still doesn't match }
  6569. Exit;
  6570. end;
  6571. if (taicpu(hp2).oper[0]^.val = 1) then
  6572. begin
  6573. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6574. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6575. end
  6576. else
  6577. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6578. if taicpu(hp2).opsize=S_B then
  6579. begin
  6580. if taicpu(hp2).oper[1]^.typ = top_reg then
  6581. begin
  6582. SecondReg := taicpu(hp2).oper[1]^.reg;
  6583. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6584. end
  6585. else
  6586. begin
  6587. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6588. SecondReg := NR_NO;
  6589. end;
  6590. hp_pos := p;
  6591. hp_allocstart := hp4;
  6592. end
  6593. else
  6594. begin
  6595. { Will be a register because the size can't be S_B otherwise }
  6596. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6597. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6598. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6599. if (cs_opt_size in current_settings.optimizerswitches) then
  6600. begin
  6601. { Favour using MOVZX when optimising for size }
  6602. case taicpu(hp2).opsize of
  6603. S_W:
  6604. NewSize := S_BW;
  6605. S_L:
  6606. NewSize := S_BL;
  6607. {$ifdef x86_64}
  6608. S_Q:
  6609. begin
  6610. NewSize := S_BL;
  6611. { Will implicitly zero-extend to 64-bit }
  6612. setsubreg(SecondReg, R_SUBD);
  6613. end;
  6614. {$endif x86_64}
  6615. else
  6616. InternalError(2022101301);
  6617. end;
  6618. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6619. { Inserting it right before p will guarantee that the flags are also tracked }
  6620. Asml.InsertBefore(hp5, p);
  6621. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6622. hp_pos := hp5;
  6623. hp_allocstart := hp4;
  6624. end
  6625. else
  6626. begin
  6627. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6628. { Inserting it right before p will guarantee that the flags are also tracked }
  6629. Asml.InsertBefore(hp5, p);
  6630. hp_pos := p;
  6631. hp_allocstart := hp5;
  6632. end;
  6633. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6634. end;
  6635. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6636. taicpu(hp4).condition := taicpu(p).condition;
  6637. asml.InsertBefore(hp4, hp_pos);
  6638. if taicpu(hp3).is_jmp then
  6639. begin
  6640. JumpLoc.decrefs;
  6641. MakeUnconditional(taicpu(p));
  6642. { This also increases the reference count }
  6643. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6644. end
  6645. else
  6646. ConvertJumpToRET(p, hp3);
  6647. if SecondReg <> NR_NO then
  6648. { Ensure the destination register is allocated over this region }
  6649. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6650. if (JumpLoc.getrefs = 0) then
  6651. RemoveDeadCodeAfterJump(hp3);
  6652. Result:=true;
  6653. exit;
  6654. end;
  6655. end;
  6656. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6657. var
  6658. hp1, hp2: tai;
  6659. ActiveReg: TRegister;
  6660. OldOffset: asizeint;
  6661. ThisConst: TCGInt;
  6662. function RegDeallocated: Boolean;
  6663. begin
  6664. TransferUsedRegs(TmpUsedRegs);
  6665. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6666. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6667. end;
  6668. begin
  6669. Result:=false;
  6670. hp1 := nil;
  6671. { replace
  6672. subX const,%reg1
  6673. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6674. dealloc %reg1
  6675. by
  6676. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6677. }
  6678. if MatchOpType(taicpu(p),top_const,top_reg) then
  6679. begin
  6680. ActiveReg := taicpu(p).oper[1]^.reg;
  6681. { Ensures the entire register was updated }
  6682. if (taicpu(p).opsize >= S_L) and
  6683. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6684. MatchInstruction(hp1,A_LEA,[]) and
  6685. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6686. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6687. (
  6688. { Cover the case where the register in the reference is also the destination register }
  6689. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6690. (
  6691. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6692. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6693. RegDeallocated
  6694. )
  6695. ) then
  6696. begin
  6697. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6698. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6699. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6700. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6701. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6702. {$ifdef x86_64}
  6703. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6704. begin
  6705. { Overflow; abort }
  6706. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6707. end
  6708. else
  6709. {$endif x86_64}
  6710. begin
  6711. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6712. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6713. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6714. RemoveCurrentP(p, hp1)
  6715. else
  6716. RemoveCurrentP(p);
  6717. result:=true;
  6718. Exit;
  6719. end;
  6720. end;
  6721. if (
  6722. { Save calling GetNextInstructionUsingReg again }
  6723. Assigned(hp1) or
  6724. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6725. ) and
  6726. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6727. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6728. begin
  6729. { Make sure the flags aren't in use by the second operation }
  6730. TransferUsedRegs(TmpUsedRegs);
  6731. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6732. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6733. begin
  6734. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6735. begin
  6736. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6737. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6738. Result := True;
  6739. { Handle any overflows }
  6740. case taicpu(p).opsize of
  6741. S_B:
  6742. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6743. S_W:
  6744. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6745. S_L:
  6746. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6747. {$ifdef x86_64}
  6748. S_Q:
  6749. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6750. { Overflow; abort }
  6751. Result := False
  6752. else
  6753. taicpu(p).oper[0]^.val := ThisConst;
  6754. {$endif x86_64}
  6755. else
  6756. InternalError(2021102611);
  6757. end;
  6758. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6759. if Result then
  6760. begin
  6761. if (taicpu(p).oper[0]^.val < 0) and
  6762. (
  6763. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6764. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6765. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6766. ) then
  6767. begin
  6768. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6769. taicpu(p).opcode := A_SUB;
  6770. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6771. end
  6772. else
  6773. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6774. RemoveInstruction(hp1);
  6775. end;
  6776. end
  6777. else
  6778. begin
  6779. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6780. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6781. Asml.Remove(p);
  6782. Asml.InsertAfter(p, hp1);
  6783. p := hp1;
  6784. Result := True;
  6785. Exit;
  6786. end;
  6787. end;
  6788. end;
  6789. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6790. { * change "sub/add const1, reg" or "dec reg" followed by
  6791. "sub const2, reg" to one "sub ..., reg" }
  6792. {$ifdef i386}
  6793. if (taicpu(p).oper[0]^.val = 2) and
  6794. (ActiveReg = NR_ESP) and
  6795. { Don't do the sub/push optimization if the sub }
  6796. { comes from setting up the stack frame (JM) }
  6797. (not(GetLastInstruction(p,hp1)) or
  6798. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6799. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6800. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6801. begin
  6802. hp1 := tai(p.next);
  6803. while Assigned(hp1) and
  6804. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6805. not RegReadByInstruction(NR_ESP,hp1) and
  6806. not RegModifiedByInstruction(NR_ESP,hp1) do
  6807. hp1 := tai(hp1.next);
  6808. if Assigned(hp1) and
  6809. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6810. begin
  6811. taicpu(hp1).changeopsize(S_L);
  6812. if taicpu(hp1).oper[0]^.typ=top_reg then
  6813. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6814. hp1 := tai(p.next);
  6815. RemoveCurrentp(p, hp1);
  6816. Result:=true;
  6817. exit;
  6818. end;
  6819. end;
  6820. {$endif i386}
  6821. if DoArithCombineOpt(p) then
  6822. Result:=true;
  6823. end;
  6824. end;
  6825. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6826. var
  6827. TmpBool1,TmpBool2 : Boolean;
  6828. tmpref : treference;
  6829. hp1,hp2: tai;
  6830. mask, shiftval: tcgint;
  6831. begin
  6832. Result:=false;
  6833. { All these optimisations work on "shl/sal const,%reg" }
  6834. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6835. Exit;
  6836. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6837. (taicpu(p).oper[0]^.val <= 3) then
  6838. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6839. begin
  6840. { should we check the next instruction? }
  6841. TmpBool1 := True;
  6842. { have we found an add/sub which could be
  6843. integrated in the lea? }
  6844. TmpBool2 := False;
  6845. reference_reset(tmpref,2,[]);
  6846. TmpRef.index := taicpu(p).oper[1]^.reg;
  6847. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6848. while TmpBool1 and
  6849. GetNextInstruction(p, hp1) and
  6850. (tai(hp1).typ = ait_instruction) and
  6851. ((((taicpu(hp1).opcode = A_ADD) or
  6852. (taicpu(hp1).opcode = A_SUB)) and
  6853. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6854. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6855. (((taicpu(hp1).opcode = A_INC) or
  6856. (taicpu(hp1).opcode = A_DEC)) and
  6857. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6858. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6859. ((taicpu(hp1).opcode = A_LEA) and
  6860. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6861. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6862. (not GetNextInstruction(hp1,hp2) or
  6863. not instrReadsFlags(hp2)) Do
  6864. begin
  6865. TmpBool1 := False;
  6866. if taicpu(hp1).opcode=A_LEA then
  6867. begin
  6868. if (TmpRef.base = NR_NO) and
  6869. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6870. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6871. { Segment register isn't a concern here }
  6872. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6873. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6874. begin
  6875. TmpBool1 := True;
  6876. TmpBool2 := True;
  6877. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6878. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6879. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6880. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6881. RemoveInstruction(hp1);
  6882. end
  6883. end
  6884. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6885. begin
  6886. TmpBool1 := True;
  6887. TmpBool2 := True;
  6888. case taicpu(hp1).opcode of
  6889. A_ADD:
  6890. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6891. A_SUB:
  6892. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6893. else
  6894. internalerror(2019050536);
  6895. end;
  6896. RemoveInstruction(hp1);
  6897. end
  6898. else
  6899. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6900. (((taicpu(hp1).opcode = A_ADD) and
  6901. (TmpRef.base = NR_NO)) or
  6902. (taicpu(hp1).opcode = A_INC) or
  6903. (taicpu(hp1).opcode = A_DEC)) then
  6904. begin
  6905. TmpBool1 := True;
  6906. TmpBool2 := True;
  6907. case taicpu(hp1).opcode of
  6908. A_ADD:
  6909. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6910. A_INC:
  6911. inc(TmpRef.offset);
  6912. A_DEC:
  6913. dec(TmpRef.offset);
  6914. else
  6915. internalerror(2019050535);
  6916. end;
  6917. RemoveInstruction(hp1);
  6918. end;
  6919. end;
  6920. if TmpBool2
  6921. {$ifndef x86_64}
  6922. or
  6923. ((current_settings.optimizecputype < cpu_Pentium2) and
  6924. (taicpu(p).oper[0]^.val <= 3) and
  6925. not(cs_opt_size in current_settings.optimizerswitches))
  6926. {$endif x86_64}
  6927. then
  6928. begin
  6929. if not(TmpBool2) and
  6930. (taicpu(p).oper[0]^.val=1) then
  6931. begin
  6932. taicpu(p).opcode := A_ADD;
  6933. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6934. end
  6935. else
  6936. begin
  6937. taicpu(p).opcode := A_LEA;
  6938. taicpu(p).loadref(0, TmpRef);
  6939. end;
  6940. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6941. Result := True;
  6942. end;
  6943. end
  6944. {$ifndef x86_64}
  6945. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6946. begin
  6947. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6948. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6949. (unlike shl, which is only Tairable in the U pipe) }
  6950. if taicpu(p).oper[0]^.val=1 then
  6951. begin
  6952. taicpu(p).opcode := A_ADD;
  6953. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6954. Result := True;
  6955. end
  6956. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6957. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6958. else if (taicpu(p).opsize = S_L) and
  6959. (taicpu(p).oper[0]^.val<= 3) then
  6960. begin
  6961. reference_reset(tmpref,2,[]);
  6962. TmpRef.index := taicpu(p).oper[1]^.reg;
  6963. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6964. taicpu(p).opcode := A_LEA;
  6965. taicpu(p).loadref(0, TmpRef);
  6966. Result := True;
  6967. end;
  6968. end
  6969. {$endif x86_64}
  6970. else if
  6971. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6972. (
  6973. (
  6974. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6975. SetAndTest(hp1, hp2)
  6976. {$ifdef x86_64}
  6977. ) or
  6978. (
  6979. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6980. GetNextInstruction(hp1, hp2) and
  6981. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6982. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6983. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6984. {$endif x86_64}
  6985. )
  6986. ) and
  6987. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6988. begin
  6989. { Change:
  6990. shl x, %reg1
  6991. mov -(1<<x), %reg2
  6992. and %reg2, %reg1
  6993. Or:
  6994. shl x, %reg1
  6995. and -(1<<x), %reg1
  6996. To just:
  6997. shl x, %reg1
  6998. Since the and operation only zeroes bits that are already zero from the shl operation
  6999. }
  7000. case taicpu(p).oper[0]^.val of
  7001. 8:
  7002. mask:=$FFFFFFFFFFFFFF00;
  7003. 16:
  7004. mask:=$FFFFFFFFFFFF0000;
  7005. 32:
  7006. mask:=$FFFFFFFF00000000;
  7007. 63:
  7008. { Constant pre-calculated to prevent overflow errors with Int64 }
  7009. mask:=$8000000000000000;
  7010. else
  7011. begin
  7012. if taicpu(p).oper[0]^.val >= 64 then
  7013. { Shouldn't happen realistically, since the register
  7014. is guaranteed to be set to zero at this point }
  7015. mask := 0
  7016. else
  7017. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  7018. end;
  7019. end;
  7020. if taicpu(hp1).oper[0]^.val = mask then
  7021. begin
  7022. { Everything checks out, perform the optimisation, as long as
  7023. the FLAGS register isn't being used}
  7024. TransferUsedRegs(TmpUsedRegs);
  7025. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7026. {$ifdef x86_64}
  7027. if (hp1 <> hp2) then
  7028. begin
  7029. { "shl/mov/and" version }
  7030. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7031. { Don't do the optimisation if the FLAGS register is in use }
  7032. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  7033. begin
  7034. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  7035. { Don't remove the 'mov' instruction if its register is used elsewhere }
  7036. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  7037. begin
  7038. RemoveInstruction(hp1);
  7039. Result := True;
  7040. end;
  7041. { Only set Result to True if the 'mov' instruction was removed }
  7042. RemoveInstruction(hp2);
  7043. end;
  7044. end
  7045. else
  7046. {$endif x86_64}
  7047. begin
  7048. { "shl/and" version }
  7049. { Don't do the optimisation if the FLAGS register is in use }
  7050. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  7051. begin
  7052. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  7053. RemoveInstruction(hp1);
  7054. Result := True;
  7055. end;
  7056. end;
  7057. Exit;
  7058. end
  7059. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  7060. begin
  7061. { Even if the mask doesn't allow for its removal, we might be
  7062. able to optimise the mask for the "shl/and" version, which
  7063. may permit other peephole optimisations }
  7064. {$ifdef DEBUG_AOPTCPU}
  7065. mask := taicpu(hp1).oper[0]^.val and mask;
  7066. if taicpu(hp1).oper[0]^.val <> mask then
  7067. begin
  7068. DebugMsg(
  7069. SPeepholeOptimization +
  7070. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  7071. ' to $' + debug_tostr(mask) +
  7072. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  7073. taicpu(hp1).oper[0]^.val := mask;
  7074. end;
  7075. {$else DEBUG_AOPTCPU}
  7076. { If debugging is off, just set the operand even if it's the same }
  7077. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  7078. {$endif DEBUG_AOPTCPU}
  7079. end;
  7080. end;
  7081. {
  7082. change
  7083. shl/sal const,reg
  7084. <op> ...(...,reg,1),...
  7085. into
  7086. <op> ...(...,reg,1 shl const),...
  7087. if const in 1..3
  7088. }
  7089. if MatchOpType(taicpu(p), top_const, top_reg) and
  7090. (taicpu(p).oper[0]^.val in [1..3]) and
  7091. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7092. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  7093. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  7094. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  7095. MatchOpType(taicpu(hp1),top_ref))
  7096. ) and
  7097. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  7098. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  7099. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  7100. begin
  7101. TransferUsedRegs(TmpUsedRegs);
  7102. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7103. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  7104. begin
  7105. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7106. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7107. RemoveCurrentP(p);
  7108. Result:=true;
  7109. exit;
  7110. end;
  7111. end;
  7112. if MatchOpType(taicpu(p), top_const, top_reg) and
  7113. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7114. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7115. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7116. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7117. begin
  7118. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7119. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7120. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7121. {$ifdef x86_64}
  7122. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7123. {$endif x86_64}
  7124. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7125. begin
  7126. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7127. taicpu(hp1).opcode:=A_MOV;
  7128. taicpu(hp1).oper[0]^.val:=0;
  7129. end
  7130. else
  7131. begin
  7132. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7133. taicpu(hp1).oper[0]^.val:=shiftval;
  7134. end;
  7135. RemoveCurrentP(p);
  7136. Result:=true;
  7137. exit;
  7138. end;
  7139. end;
  7140. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7141. begin
  7142. case shr_size of
  7143. S_B:
  7144. { No valid combinations }
  7145. Result := False;
  7146. S_W:
  7147. Result := (Shift >= 8) and (movz_size = S_BW);
  7148. S_L:
  7149. Result :=
  7150. (Shift >= 24) { Any opsize is valid for this shift } or
  7151. ((Shift >= 16) and (movz_size = S_WL));
  7152. {$ifdef x86_64}
  7153. S_Q:
  7154. Result :=
  7155. (Shift >= 56) { Any opsize is valid for this shift } or
  7156. ((Shift >= 48) and (movz_size = S_WL));
  7157. {$endif x86_64}
  7158. else
  7159. InternalError(2022081510);
  7160. end;
  7161. end;
  7162. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7163. var
  7164. hp1, hp2: tai;
  7165. IdentityMask, Shift: TCGInt;
  7166. LimitSize: Topsize;
  7167. DoNotMerge: Boolean;
  7168. begin
  7169. if not MatchInstruction(p, A_SHR, []) then
  7170. InternalError(2025040301);
  7171. Result := False;
  7172. DoNotMerge := False;
  7173. Shift := taicpu(p).oper[0]^.val;
  7174. LimitSize := taicpu(p).opsize;
  7175. hp1 := p;
  7176. repeat
  7177. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7178. Exit;
  7179. case taicpu(hp1).opcode of
  7180. A_AND:
  7181. { Detect:
  7182. shr x, %reg
  7183. and y, %reg
  7184. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7185. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7186. (Post-peephole only)
  7187. }
  7188. if PostPeephole and
  7189. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7190. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7191. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7192. begin
  7193. { Make sure the FLAGS register isn't in use }
  7194. TransferUsedRegs(TmpUsedRegs);
  7195. hp2 := p;
  7196. repeat
  7197. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7198. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7199. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7200. begin
  7201. { Generate the identity mask }
  7202. case taicpu(p).opsize of
  7203. S_B:
  7204. IdentityMask := $FF shr Shift;
  7205. S_W:
  7206. IdentityMask := $FFFF shr Shift;
  7207. S_L:
  7208. IdentityMask := $FFFFFFFF shr Shift;
  7209. {$ifdef x86_64}
  7210. S_Q:
  7211. { We need to force the operands to be unsigned 64-bit
  7212. integers otherwise the wrong value is generated }
  7213. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7214. {$endif x86_64}
  7215. else
  7216. InternalError(2022081501);
  7217. end;
  7218. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7219. begin
  7220. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7221. { All the possible 1 bits are covered, so we can remove the AND }
  7222. hp2 := tai(hp1.Previous);
  7223. RemoveInstruction(hp1);
  7224. { p wasn't actually changed, so don't set Result to True,
  7225. but a change was nonetheless made elsewhere }
  7226. Include(OptsToCheck, aoc_ForceNewIteration);
  7227. { Do another pass in case other AND or MOVZX instructions
  7228. follow }
  7229. hp1 := hp2;
  7230. Continue;
  7231. end;
  7232. end;
  7233. end;
  7234. A_TEST, A_CMP:
  7235. { Skip over relevant comparisons, but shift instructions must
  7236. now not be merged since the original value is being read }
  7237. begin
  7238. DoNotMerge := True;
  7239. Continue;
  7240. end;
  7241. A_Jcc:
  7242. { Skip over conditional jumps and relevant comparisons }
  7243. Continue;
  7244. A_MOVZX:
  7245. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7246. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7247. begin
  7248. { Since the original register is being read as is, subsequent
  7249. SHRs must not be merged at this point }
  7250. DoNotMerge := True;
  7251. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7252. begin
  7253. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7254. begin
  7255. { If the MOVZX instruction reads and writes the same register,
  7256. defer this to the post-peephole optimisation stage }
  7257. if PostPeephole then
  7258. begin
  7259. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7260. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7261. hp2 := tai(hp1.Previous);
  7262. RemoveInstruction(hp1);
  7263. hp1 := hp2;
  7264. end;
  7265. end
  7266. else { Different register target }
  7267. begin
  7268. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7269. taicpu(hp1).opcode := A_MOV;
  7270. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7271. case taicpu(hp1).opsize of
  7272. S_BW:
  7273. taicpu(hp1).opsize := S_W;
  7274. S_BL, S_WL:
  7275. taicpu(hp1).opsize := S_L;
  7276. else
  7277. InternalError(2022081503);
  7278. end;
  7279. { p itself hasn't changed, so no need to set Result to True }
  7280. Include(OptsToCheck, aoc_ForceNewIteration);
  7281. { See if there's anything afterwards that can be
  7282. optimised, since the input register hasn't changed }
  7283. Continue;
  7284. end;
  7285. Exit;
  7286. end
  7287. else if PostPeephole and
  7288. (Shift > 0) and
  7289. (taicpu(p).opsize = S_W) and
  7290. (taicpu(hp1).opsize = S_WL) and
  7291. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7292. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7293. begin
  7294. { Detect:
  7295. shr x, %ax (x > 0)
  7296. ...
  7297. movzwl %ax,%eax
  7298. -
  7299. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7300. But first, check to see if movzwl %ax,%eax can be removed...
  7301. }
  7302. hp2 := tai(hp1.Previous);
  7303. TransferUsedRegs(TmpUsedRegs);
  7304. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7305. if PostPeepholeOptMovZX(hp1) then
  7306. hp1 := hp2
  7307. else
  7308. begin
  7309. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7310. taicpu(hp1).opcode := A_CWDE;
  7311. taicpu(hp1).clearop(0);
  7312. taicpu(hp1).clearop(1);
  7313. taicpu(hp1).ops := 0;
  7314. end;
  7315. RestoreUsedRegs(TmpUsedRegs);
  7316. { Don't need to set aoc_ForceNewIteration if
  7317. PostPeepholeOptMovZX returned True because it's the
  7318. post-peephole stage }
  7319. end;
  7320. { Move onto the next instruction }
  7321. Continue;
  7322. end;
  7323. A_SHL, A_SAL, A_SHR:
  7324. if (taicpu(hp1).opsize <= LimitSize) and
  7325. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7326. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7327. begin
  7328. { Make sure the sizes don't exceed the register size limit
  7329. (measured by the shift value falling below the limit) }
  7330. if taicpu(hp1).opsize < LimitSize then
  7331. LimitSize := taicpu(hp1).opsize;
  7332. if taicpu(hp1).opcode = A_SHR then
  7333. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7334. else
  7335. begin
  7336. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7337. DoNotMerge := True;
  7338. end;
  7339. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7340. Exit;
  7341. { Since we've established that the combined shift is within
  7342. limits, we can actually combine the adjacent SHR
  7343. instructions even if they're different sizes }
  7344. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7345. begin
  7346. hp2 := tai(hp1.Previous);
  7347. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7348. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7349. RemoveInstruction(hp1);
  7350. hp1 := hp2;
  7351. { Though p has changed, only the constant has, and its
  7352. effects can still be detected on the next iteration of
  7353. the repeat..until loop }
  7354. Include(OptsToCheck, aoc_ForceNewIteration);
  7355. end;
  7356. { Move onto the next instruction }
  7357. Continue;
  7358. end;
  7359. else
  7360. ;
  7361. end;
  7362. { If the register isn't actually modified, move onto the next instruction,
  7363. but set DoNotMerge to True since the register is being read }
  7364. if (
  7365. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7366. the next instruction, whether or not it contains the register }
  7367. (cs_opt_level3 in current_settings.optimizerswitches) or
  7368. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7369. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7370. begin
  7371. DoNotMerge := True;
  7372. Continue;
  7373. end;
  7374. Break;
  7375. until False;
  7376. end;
  7377. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7378. begin
  7379. Result := False;
  7380. { All these optimisations work on "shr const,%reg" }
  7381. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7382. Exit;
  7383. Result := HandleSHRMerge(p, False);
  7384. end;
  7385. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7386. var
  7387. CurrentRef: TReference;
  7388. FullReg: TRegister;
  7389. hp1, hp2: tai;
  7390. begin
  7391. Result := False;
  7392. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7393. Exit;
  7394. { We assume you've checked if the operand is actually a reference by
  7395. this point. If it isn't, you'll most likely get an access violation }
  7396. CurrentRef := first_mov.oper[1]^.ref^;
  7397. { Memory must be aligned }
  7398. if (CurrentRef.offset mod 4) <> 0 then
  7399. Exit;
  7400. Inc(CurrentRef.offset);
  7401. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7402. if MatchOperand(second_mov.oper[0]^, 0) and
  7403. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7404. GetNextInstruction(second_mov, hp1) and
  7405. (hp1.typ = ait_instruction) and
  7406. (taicpu(hp1).opcode = A_MOV) and
  7407. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7408. (taicpu(hp1).oper[0]^.val = 0) then
  7409. begin
  7410. Inc(CurrentRef.offset);
  7411. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7412. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7413. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7414. begin
  7415. case taicpu(hp1).opsize of
  7416. S_B:
  7417. if GetNextInstruction(hp1, hp2) and
  7418. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7419. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7420. (taicpu(hp2).oper[0]^.val = 0) then
  7421. begin
  7422. Inc(CurrentRef.offset);
  7423. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7424. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7425. (taicpu(hp2).opsize = S_B) then
  7426. begin
  7427. RemoveInstruction(hp1);
  7428. RemoveInstruction(hp2);
  7429. first_mov.opsize := S_L;
  7430. if first_mov.oper[0]^.typ = top_reg then
  7431. begin
  7432. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7433. { Reuse second_mov as a MOVZX instruction }
  7434. second_mov.opcode := A_MOVZX;
  7435. second_mov.opsize := S_BL;
  7436. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7437. second_mov.loadreg(1, FullReg);
  7438. first_mov.oper[0]^.reg := FullReg;
  7439. asml.Remove(second_mov);
  7440. asml.InsertBefore(second_mov, first_mov);
  7441. end
  7442. else
  7443. { It's a value }
  7444. begin
  7445. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7446. RemoveInstruction(second_mov);
  7447. end;
  7448. Result := True;
  7449. Exit;
  7450. end;
  7451. end;
  7452. S_W:
  7453. begin
  7454. RemoveInstruction(hp1);
  7455. first_mov.opsize := S_L;
  7456. if first_mov.oper[0]^.typ = top_reg then
  7457. begin
  7458. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7459. { Reuse second_mov as a MOVZX instruction }
  7460. second_mov.opcode := A_MOVZX;
  7461. second_mov.opsize := S_BL;
  7462. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7463. second_mov.loadreg(1, FullReg);
  7464. first_mov.oper[0]^.reg := FullReg;
  7465. asml.Remove(second_mov);
  7466. asml.InsertBefore(second_mov, first_mov);
  7467. end
  7468. else
  7469. { It's a value }
  7470. begin
  7471. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7472. RemoveInstruction(second_mov);
  7473. end;
  7474. Result := True;
  7475. Exit;
  7476. end;
  7477. else
  7478. ;
  7479. end;
  7480. end;
  7481. end;
  7482. end;
  7483. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7484. { returns true if a "continue" should be done after this optimization }
  7485. var
  7486. hp1, hp2, hp3: tai;
  7487. begin
  7488. Result := false;
  7489. hp3 := nil;
  7490. if MatchOpType(taicpu(p),top_ref) and
  7491. GetNextInstruction(p, hp1) and
  7492. (hp1.typ = ait_instruction) and
  7493. (((taicpu(hp1).opcode = A_FLD) and
  7494. (taicpu(p).opcode = A_FSTP)) or
  7495. ((taicpu(p).opcode = A_FISTP) and
  7496. (taicpu(hp1).opcode = A_FILD))) and
  7497. MatchOpType(taicpu(hp1),top_ref) and
  7498. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7499. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7500. begin
  7501. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7502. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7503. GetNextInstruction(hp1, hp2) and
  7504. (((hp2.typ = ait_instruction) and
  7505. IsExitCode(hp2) and
  7506. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7507. not(assigned(current_procinfo.procdef.funcretsym) and
  7508. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7509. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7510. { fstp <temp>
  7511. fld <temp>
  7512. <dealloc> <temp>
  7513. }
  7514. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7515. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7516. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7517. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7518. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7519. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7520. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7521. )
  7522. )
  7523. ) then
  7524. begin
  7525. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7526. RemoveInstruction(hp1);
  7527. RemoveCurrentP(p, hp2);
  7528. { first case: exit code }
  7529. if hp2.typ = ait_instruction then
  7530. RemoveLastDeallocForFuncRes(p);
  7531. Result := true;
  7532. end
  7533. else
  7534. { we can do this only in fast math mode as fstp is rounding ...
  7535. ... still disabled as it breaks the compiler and/or rtl }
  7536. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7537. { ... or if another fstp equal to the first one follows }
  7538. GetNextInstruction(hp1,hp2) and
  7539. (hp2.typ = ait_instruction) and
  7540. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7541. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7542. begin
  7543. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7544. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7545. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7546. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7547. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7548. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7549. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7550. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7551. ) then
  7552. begin
  7553. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7554. RemoveCurrentP(p,hp2);
  7555. RemoveInstruction(hp1);
  7556. Result := true;
  7557. end
  7558. else if { fst can't store an extended/comp value }
  7559. (taicpu(p).opsize <> S_FX) and
  7560. (taicpu(p).opsize <> S_IQ) then
  7561. begin
  7562. if (taicpu(p).opcode = A_FSTP) then
  7563. taicpu(p).opcode := A_FST
  7564. else
  7565. taicpu(p).opcode := A_FIST;
  7566. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7567. RemoveInstruction(hp1);
  7568. Result := true;
  7569. end;
  7570. end;
  7571. end;
  7572. end;
  7573. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7574. var
  7575. hp1, hp2, hp3: tai;
  7576. begin
  7577. result:=false;
  7578. if MatchOpType(taicpu(p),top_reg) and
  7579. GetNextInstruction(p, hp1) and
  7580. (hp1.typ = Ait_Instruction) and
  7581. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7582. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7583. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7584. { change to
  7585. fld reg fxxx reg,st
  7586. fxxxp st, st1 (hp1)
  7587. Remark: non commutative operations must be reversed!
  7588. }
  7589. begin
  7590. case taicpu(hp1).opcode Of
  7591. A_FMULP,A_FADDP,
  7592. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7593. begin
  7594. case taicpu(hp1).opcode Of
  7595. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7596. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7597. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7598. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7599. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7600. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7601. else
  7602. internalerror(2019050534);
  7603. end;
  7604. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7605. taicpu(hp1).oper[1]^.reg := NR_ST;
  7606. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7607. RemoveCurrentP(p, hp1);
  7608. Result:=true;
  7609. exit;
  7610. end;
  7611. else
  7612. ;
  7613. end;
  7614. end
  7615. else
  7616. if MatchOpType(taicpu(p),top_ref) and
  7617. GetNextInstruction(p, hp2) and
  7618. (hp2.typ = Ait_Instruction) and
  7619. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7620. (taicpu(p).opsize in [S_FS, S_FL]) and
  7621. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7622. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7623. if GetLastInstruction(p, hp1) and
  7624. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7625. MatchOpType(taicpu(hp1),top_ref) and
  7626. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7627. if ((taicpu(hp2).opcode = A_FMULP) or
  7628. (taicpu(hp2).opcode = A_FADDP)) then
  7629. { change to
  7630. fld/fst mem1 (hp1) fld/fst mem1
  7631. fld mem1 (p) fadd/
  7632. faddp/ fmul st, st
  7633. fmulp st, st1 (hp2) }
  7634. begin
  7635. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7636. RemoveCurrentP(p, hp1);
  7637. if (taicpu(hp2).opcode = A_FADDP) then
  7638. taicpu(hp2).opcode := A_FADD
  7639. else
  7640. taicpu(hp2).opcode := A_FMUL;
  7641. taicpu(hp2).oper[1]^.reg := NR_ST;
  7642. end
  7643. else
  7644. { change to
  7645. fld/fst mem1 (hp1) fld/fst mem1
  7646. fld mem1 (p) fld st
  7647. }
  7648. begin
  7649. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7650. taicpu(p).changeopsize(S_FL);
  7651. taicpu(p).loadreg(0,NR_ST);
  7652. end
  7653. else
  7654. begin
  7655. case taicpu(hp2).opcode Of
  7656. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7657. { change to
  7658. fld/fst mem1 (hp1) fld/fst mem1
  7659. fld mem2 (p) fxxx mem2
  7660. fxxxp st, st1 (hp2) }
  7661. begin
  7662. case taicpu(hp2).opcode Of
  7663. A_FADDP: taicpu(p).opcode := A_FADD;
  7664. A_FMULP: taicpu(p).opcode := A_FMUL;
  7665. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7666. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7667. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7668. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7669. else
  7670. internalerror(2019050533);
  7671. end;
  7672. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7673. RemoveInstruction(hp2);
  7674. end
  7675. else
  7676. ;
  7677. end
  7678. end
  7679. end;
  7680. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7681. begin
  7682. Result := condition_in(cond1, cond2) or
  7683. { Not strictly subsets due to the actual flags checked, but because we're
  7684. comparing integers, E is a subset of AE and GE and their aliases }
  7685. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7686. end;
  7687. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7688. var
  7689. v: TCGInt;
  7690. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7691. FirstMatch, TempBool: Boolean;
  7692. NewReg: TRegister;
  7693. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7694. begin
  7695. Result:=false;
  7696. { All these optimisations need a next instruction }
  7697. if not GetNextInstruction(p, hp1) then
  7698. Exit;
  7699. true_hp1 := hp1;
  7700. { Search for:
  7701. cmp ###,###
  7702. j(c1) @lbl1
  7703. ...
  7704. @lbl:
  7705. cmp ###,### (same comparison as above)
  7706. j(c2) @lbl2
  7707. If c1 is a subset of c2, change to:
  7708. cmp ###,###
  7709. j(c1) @lbl2
  7710. (@lbl1 may become a dead label as a result)
  7711. }
  7712. { Also handle cases where there are multiple jumps in a row }
  7713. p_jump := hp1;
  7714. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7715. begin
  7716. Prefetch(p_jump.Next);
  7717. if IsJumpToLabel(taicpu(p_jump)) then
  7718. begin
  7719. { Do jump optimisations first in case the condition becomes
  7720. unnecessary }
  7721. TempBool := True;
  7722. if DoJumpOptimizations(p_jump, TempBool) or
  7723. not TempBool then
  7724. begin
  7725. if Assigned(p_jump) then
  7726. begin
  7727. { CollapseZeroDistJump will be set to the label or an align
  7728. before it after the jump if it optimises, whether or not
  7729. the label is live or dead }
  7730. if (p_jump.typ = ait_align) or
  7731. (
  7732. (p_jump.typ = ait_label) and
  7733. not (tai_label(p_jump).labsym.is_used)
  7734. ) then
  7735. GetNextInstruction(p_jump, p_jump);
  7736. end;
  7737. TransferUsedRegs(TmpUsedRegs);
  7738. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7739. if not Assigned(p_jump) or
  7740. (
  7741. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7742. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7743. ) then
  7744. begin
  7745. { No more conditional jumps; conditional statement is no longer required }
  7746. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7747. RemoveCurrentP(p);
  7748. Result := True;
  7749. Exit;
  7750. end;
  7751. hp1 := p_jump;
  7752. Include(OptsToCheck, aoc_ForceNewIteration);
  7753. Continue;
  7754. end;
  7755. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7756. if GetNextInstruction(p_jump, hp2) and
  7757. (
  7758. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7759. not TempBool
  7760. ) then
  7761. begin
  7762. hp1 := p_jump;
  7763. Include(OptsToCheck, aoc_ForceNewIteration);
  7764. Continue;
  7765. end;
  7766. p_label := nil;
  7767. if Assigned(JumpLabel) then
  7768. p_label := getlabelwithsym(JumpLabel);
  7769. if Assigned(p_label) and
  7770. GetNextInstruction(p_label, p_dist) and
  7771. MatchInstruction(p_dist, A_CMP, []) and
  7772. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7773. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7774. GetNextInstruction(p_dist, hp1_dist) and
  7775. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7776. begin
  7777. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7778. if JumpLabel = JumpLabel_dist then
  7779. { This is an infinite loop }
  7780. Exit;
  7781. { Best optimisation when the first condition is a subset (or equal) of the second }
  7782. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7783. begin
  7784. { Any registers used here will already be allocated }
  7785. if Assigned(JumpLabel) then
  7786. JumpLabel.DecRefs;
  7787. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7788. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7789. Include(OptsToCheck, aoc_ForceNewIteration);
  7790. { Don't exit yet. Since p and p_jump haven't actually been
  7791. removed, we can check for more on this iteration }
  7792. end
  7793. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7794. GetNextInstruction(hp1_dist, hp1_label) and
  7795. (hp1_label.typ = ait_label) then
  7796. begin
  7797. JumpLabel_far := tai_label(hp1_label).labsym;
  7798. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7799. { This is an infinite loop }
  7800. Exit;
  7801. if Assigned(JumpLabel_far) then
  7802. begin
  7803. { In this situation, if the first jump branches, the second one will never,
  7804. branch so change the destination label to after the second jump }
  7805. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7806. if Assigned(JumpLabel) then
  7807. JumpLabel.DecRefs;
  7808. JumpLabel_far.IncRefs;
  7809. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7810. Result := True;
  7811. { Don't exit yet. Since p and p_jump haven't actually been
  7812. removed, we can check for more on this iteration }
  7813. Continue;
  7814. end;
  7815. end;
  7816. end;
  7817. end;
  7818. { Search for:
  7819. cmp ###,###
  7820. j(c1) @lbl1
  7821. cmp ###,### (same as first)
  7822. Remove second cmp
  7823. }
  7824. if GetNextInstruction(p_jump, hp2) and
  7825. (
  7826. (
  7827. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7828. (
  7829. (
  7830. MatchOpType(taicpu(p), top_const, top_reg) and
  7831. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7832. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7833. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7834. ) or (
  7835. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7836. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7837. )
  7838. )
  7839. ) or (
  7840. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7841. MatchOperand(taicpu(p).oper[0]^, 0) and
  7842. (taicpu(p).oper[1]^.typ = top_reg) and
  7843. MatchInstruction(hp2, A_TEST, []) and
  7844. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7845. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7846. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7847. )
  7848. ) then
  7849. begin
  7850. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7851. TransferUsedRegs(TmpUsedRegs);
  7852. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7853. RemoveInstruction(hp2);
  7854. Result := True;
  7855. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7856. end
  7857. else
  7858. begin
  7859. { hp2 is the next instruction, so save time and just set p_jump
  7860. to it instead of calling GetNextInstruction below }
  7861. p_jump := hp2;
  7862. Continue;
  7863. end;
  7864. GetNextInstruction(p_jump, p_jump);
  7865. end;
  7866. if (
  7867. { Don't call GetNextInstruction again if we already have it }
  7868. (true_hp1 = p_jump) or
  7869. GetNextInstruction(p, hp1)
  7870. ) and
  7871. MatchInstruction(hp1, A_Jcc, []) and
  7872. IsJumpToLabel(taicpu(hp1)) and
  7873. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7874. GetNextInstruction(hp1, hp2) then
  7875. begin
  7876. {
  7877. cmp x, y (or "cmp y, x")
  7878. je @lbl
  7879. mov x, y
  7880. @lbl:
  7881. (x and y can be constants, registers or references)
  7882. Change to:
  7883. mov x, y (x and y will always be equal in the end)
  7884. @lbl: (may beceome a dead label)
  7885. Also:
  7886. cmp x, y (or "cmp y, x")
  7887. jne @lbl
  7888. mov x, y
  7889. @lbl:
  7890. (x and y can be constants, registers or references)
  7891. Change to:
  7892. Absolutely nothing! (Except @lbl if it's still live)
  7893. }
  7894. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7895. (
  7896. (
  7897. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7898. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7899. ) or (
  7900. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7901. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7902. )
  7903. ) and
  7904. GetNextInstruction(hp2, hp1_label) and
  7905. (hp1_label.typ = ait_label) and
  7906. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7907. begin
  7908. tai_label(hp1_label).labsym.DecRefs;
  7909. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7910. begin
  7911. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7912. RemoveInstruction(hp2);
  7913. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7914. end
  7915. else
  7916. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7917. RemoveInstruction(hp1);
  7918. RemoveCurrentp(p, hp2);
  7919. Result := True;
  7920. Exit;
  7921. end;
  7922. {
  7923. Try to optimise the following:
  7924. cmp $x,### ($x and $y can be registers or constants)
  7925. je @lbl1 (only reference)
  7926. cmp $y,### (### are identical)
  7927. @Lbl:
  7928. sete %reg1
  7929. Change to:
  7930. cmp $x,###
  7931. sete %reg2 (allocate new %reg2)
  7932. cmp $y,###
  7933. sete %reg1
  7934. orb %reg2,%reg1
  7935. (dealloc %reg2)
  7936. This adds an instruction (so don't perform under -Os), but it removes
  7937. a conditional branch.
  7938. }
  7939. if not (cs_opt_size in current_settings.optimizerswitches) and
  7940. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7941. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7942. { The first operand of CMP instructions can only be a register or
  7943. immediate anyway, so no need to check }
  7944. GetNextInstruction(hp2, p_label) and
  7945. (p_label.typ = ait_label) and
  7946. (tai_label(p_label).labsym.getrefs = 1) and
  7947. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7948. GetNextInstruction(p_label, p_dist) and
  7949. MatchInstruction(p_dist, A_SETcc, []) and
  7950. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7951. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7952. begin
  7953. TransferUsedRegs(TmpUsedRegs);
  7954. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7955. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7956. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7957. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7958. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7959. { Get the instruction after the SETcc instruction so we can
  7960. allocate a new register over the entire range }
  7961. GetNextInstruction(p_dist, hp1_dist) then
  7962. begin
  7963. { Register can appear in p if it's not used afterwards, so only
  7964. allocate between hp1 and hp1_dist }
  7965. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7966. if NewReg <> NR_NO then
  7967. begin
  7968. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7969. { Change the jump instruction into a SETcc instruction }
  7970. taicpu(hp1).opcode := A_SETcc;
  7971. taicpu(hp1).opsize := S_B;
  7972. taicpu(hp1).loadreg(0, NewReg);
  7973. { This is now a dead label }
  7974. tai_label(p_label).labsym.decrefs;
  7975. { Prefer adding before the next instruction so the FLAGS
  7976. register is deallicated first }
  7977. AsmL.InsertBefore(
  7978. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7979. hp1_dist
  7980. );
  7981. Result := True;
  7982. { Don't exit yet, as p wasn't changed and hp1, while
  7983. modified, is still intact and might be optimised by the
  7984. SETcc optimisation below }
  7985. end;
  7986. end;
  7987. end;
  7988. end;
  7989. if (taicpu(p).oper[0]^.typ = top_const) and
  7990. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7991. begin
  7992. if (taicpu(p).oper[0]^.val = 0) and
  7993. (taicpu(p).oper[1]^.typ = top_reg) then
  7994. begin
  7995. hp2 := p;
  7996. FirstMatch := True;
  7997. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7998. anything meaningful once it's converted to "test %reg,%reg";
  7999. additionally, some jumps will always (or never) branch, so
  8000. evaluate every jump immediately following the
  8001. comparison, optimising the conditions if possible.
  8002. Similarly with SETcc... those that are always set to 0 or 1
  8003. are changed to MOV instructions }
  8004. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  8005. (
  8006. GetNextInstruction(hp2, hp1) and
  8007. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  8008. ) do
  8009. begin
  8010. Prefetch(hp1.Next);
  8011. FirstMatch := False;
  8012. case taicpu(hp1).condition of
  8013. C_B, C_C, C_NAE, C_O:
  8014. { For B/NAE:
  8015. Will never branch since an unsigned integer can never be below zero
  8016. For C/O:
  8017. Result cannot overflow because 0 is being subtracted
  8018. }
  8019. begin
  8020. if taicpu(hp1).opcode = A_Jcc then
  8021. begin
  8022. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  8023. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  8024. RemoveInstruction(hp1);
  8025. { Since hp1 was deleted, hp2 must not be updated }
  8026. Continue;
  8027. end
  8028. else
  8029. begin
  8030. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  8031. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  8032. taicpu(hp1).opcode := A_MOV;
  8033. taicpu(hp1).ops := 2;
  8034. taicpu(hp1).condition := C_None;
  8035. taicpu(hp1).opsize := S_B;
  8036. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8037. taicpu(hp1).loadconst(0, 0);
  8038. end;
  8039. end;
  8040. C_BE, C_NA:
  8041. begin
  8042. { Will only branch if equal to zero }
  8043. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  8044. taicpu(hp1).condition := C_E;
  8045. end;
  8046. C_A, C_NBE:
  8047. begin
  8048. { Will only branch if not equal to zero }
  8049. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  8050. taicpu(hp1).condition := C_NE;
  8051. end;
  8052. C_AE, C_NB, C_NC, C_NO:
  8053. begin
  8054. { Will always branch }
  8055. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  8056. if taicpu(hp1).opcode = A_Jcc then
  8057. begin
  8058. MakeUnconditional(taicpu(hp1));
  8059. { Any jumps/set that follow will now be dead code }
  8060. RemoveDeadCodeAfterJump(taicpu(hp1));
  8061. Break;
  8062. end
  8063. else
  8064. begin
  8065. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  8066. taicpu(hp1).opcode := A_MOV;
  8067. taicpu(hp1).ops := 2;
  8068. taicpu(hp1).condition := C_None;
  8069. taicpu(hp1).opsize := S_B;
  8070. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8071. taicpu(hp1).loadconst(0, 1);
  8072. end;
  8073. end;
  8074. C_None:
  8075. InternalError(2020012201);
  8076. C_P, C_PE, C_NP, C_PO:
  8077. { We can't handle parity checks and they should never be generated
  8078. after a general-purpose CMP (it's used in some floating-point
  8079. comparisons that don't use CMP) }
  8080. InternalError(2020012202);
  8081. else
  8082. { Zero/Equality, Sign, their complements and all of the
  8083. signed comparisons do not need to be converted };
  8084. end;
  8085. hp2 := hp1;
  8086. end;
  8087. { Convert the instruction to a TEST }
  8088. taicpu(p).opcode := A_TEST;
  8089. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8090. Result := True;
  8091. Exit;
  8092. end
  8093. else
  8094. begin
  8095. TransferUsedRegs(TmpUsedRegs);
  8096. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8097. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8098. begin
  8099. if (taicpu(p).oper[0]^.val = 1) and
  8100. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  8101. begin
  8102. { Convert; To:
  8103. cmp $1,r/m cmp $0,r/m
  8104. jl @lbl jle @lbl
  8105. (Also do inverted conditions)
  8106. }
  8107. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8108. taicpu(p).oper[0]^.val := 0;
  8109. if taicpu(hp1).condition in [C_L, C_NGE] then
  8110. taicpu(hp1).condition := C_LE
  8111. else
  8112. taicpu(hp1).condition := C_NLE;
  8113. { If the instruction is now "cmp $0,%reg", convert it to a
  8114. TEST (and effectively do the work of the "cmp $0,%reg" in
  8115. the block above)
  8116. }
  8117. if (taicpu(p).oper[1]^.typ = top_reg) then
  8118. begin
  8119. taicpu(p).opcode := A_TEST;
  8120. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8121. end;
  8122. Result := True;
  8123. Exit;
  8124. end
  8125. else if (taicpu(p).oper[1]^.typ = top_reg)
  8126. {$ifdef x86_64}
  8127. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8128. {$endif x86_64}
  8129. then
  8130. begin
  8131. { cmp register,$8000 neg register
  8132. je target --> jo target
  8133. .... only if register is deallocated before jump.}
  8134. case Taicpu(p).opsize of
  8135. S_B: v:=$80;
  8136. S_W: v:=$8000;
  8137. S_L: v:=qword($80000000);
  8138. else
  8139. internalerror(2013112905);
  8140. end;
  8141. if (taicpu(p).oper[0]^.val=v) and
  8142. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8143. begin
  8144. TransferUsedRegs(TmpUsedRegs);
  8145. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8146. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8147. begin
  8148. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8149. Taicpu(p).opcode:=A_NEG;
  8150. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8151. Taicpu(p).clearop(1);
  8152. Taicpu(p).ops:=1;
  8153. if Taicpu(hp1).condition=C_E then
  8154. Taicpu(hp1).condition:=C_O
  8155. else
  8156. Taicpu(hp1).condition:=C_NO;
  8157. Result:=true;
  8158. exit;
  8159. end;
  8160. end;
  8161. end;
  8162. end;
  8163. end;
  8164. end;
  8165. if TrySwapMovCmp(p, hp1) then
  8166. begin
  8167. Result := True;
  8168. Exit;
  8169. end;
  8170. end;
  8171. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8172. var
  8173. hp1: tai;
  8174. begin
  8175. {
  8176. remove the second (v)pxor from
  8177. pxor reg,reg
  8178. ...
  8179. pxor reg,reg
  8180. }
  8181. Result:=false;
  8182. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8183. MatchOpType(taicpu(p),top_reg,top_reg) and
  8184. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8185. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8186. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8187. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8188. begin
  8189. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8190. RemoveInstruction(hp1);
  8191. Result:=true;
  8192. Exit;
  8193. end
  8194. {
  8195. replace
  8196. pxor reg1,reg1
  8197. movapd/s reg1,reg2
  8198. dealloc reg1
  8199. by
  8200. pxor reg2,reg2
  8201. }
  8202. else if GetNextInstruction(p,hp1) and
  8203. { we mix single and double opperations here because we assume that the compiler
  8204. generates vmovapd only after double operations and vmovaps only after single operations }
  8205. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8206. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8207. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8208. (taicpu(p).oper[0]^.typ=top_reg) then
  8209. begin
  8210. TransferUsedRegs(TmpUsedRegs);
  8211. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8212. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8213. begin
  8214. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8215. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8216. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8217. RemoveInstruction(hp1);
  8218. result:=true;
  8219. end;
  8220. end;
  8221. end;
  8222. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8223. var
  8224. hp1: tai;
  8225. begin
  8226. {
  8227. remove the second (v)pxor from
  8228. (v)pxor reg,reg
  8229. ...
  8230. (v)pxor reg,reg
  8231. }
  8232. Result:=false;
  8233. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8234. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8235. begin
  8236. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8237. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8238. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8239. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8240. begin
  8241. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8242. RemoveInstruction(hp1);
  8243. Result:=true;
  8244. Exit;
  8245. end;
  8246. {$ifdef x86_64}
  8247. {
  8248. replace
  8249. vpxor reg1,reg1,reg1
  8250. vmov reg,mem
  8251. by
  8252. movq $0,mem
  8253. }
  8254. if GetNextInstruction(p,hp1) and
  8255. MatchInstruction(hp1,A_VMOVSD,[]) and
  8256. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8257. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8258. begin
  8259. TransferUsedRegs(TmpUsedRegs);
  8260. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8261. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8262. begin
  8263. taicpu(hp1).loadconst(0,0);
  8264. taicpu(hp1).opcode:=A_MOV;
  8265. taicpu(hp1).opsize:=S_Q;
  8266. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8267. RemoveCurrentP(p);
  8268. result:=true;
  8269. Exit;
  8270. end;
  8271. end;
  8272. {$endif x86_64}
  8273. end
  8274. {
  8275. replace
  8276. vpxor reg1,reg1,reg2
  8277. by
  8278. vpxor reg2,reg2,reg2
  8279. to avoid unncessary data dependencies
  8280. }
  8281. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8282. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8283. begin
  8284. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8285. { avoid unncessary data dependency }
  8286. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8287. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8288. result:=true;
  8289. exit;
  8290. end;
  8291. Result:=OptPass1VOP(p);
  8292. end;
  8293. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8294. var
  8295. hp1 : tai;
  8296. begin
  8297. result:=false;
  8298. { replace
  8299. IMul const,%mreg1,%mreg2
  8300. Mov %reg2,%mreg3
  8301. dealloc %mreg3
  8302. by
  8303. Imul const,%mreg1,%mreg23
  8304. }
  8305. if (taicpu(p).ops=3) and
  8306. GetNextInstruction(p,hp1) and
  8307. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8308. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8309. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8310. begin
  8311. TransferUsedRegs(TmpUsedRegs);
  8312. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8313. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8314. begin
  8315. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8316. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8317. RemoveInstruction(hp1);
  8318. result:=true;
  8319. end;
  8320. end;
  8321. end;
  8322. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8323. var
  8324. hp1 : tai;
  8325. begin
  8326. result:=false;
  8327. { replace
  8328. IMul %reg0,%reg1,%reg2
  8329. Mov %reg2,%reg3
  8330. dealloc %reg2
  8331. by
  8332. Imul %reg0,%reg1,%reg3
  8333. }
  8334. if GetNextInstruction(p,hp1) and
  8335. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8336. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8337. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8338. begin
  8339. TransferUsedRegs(TmpUsedRegs);
  8340. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8341. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8342. begin
  8343. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8344. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8345. RemoveInstruction(hp1);
  8346. result:=true;
  8347. end;
  8348. end;
  8349. end;
  8350. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8351. var
  8352. hp1: tai;
  8353. begin
  8354. Result:=false;
  8355. { get rid of
  8356. (v)cvtss2sd reg0,<reg1,>reg2
  8357. (v)cvtss2sd reg2,<reg2,>reg0
  8358. }
  8359. if GetNextInstruction(p,hp1) and
  8360. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8361. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8362. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8363. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8364. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8365. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8366. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8367. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8368. )
  8369. ) then
  8370. begin
  8371. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8372. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8373. begin
  8374. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8375. RemoveCurrentP(p);
  8376. RemoveInstruction(hp1);
  8377. end
  8378. else
  8379. begin
  8380. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8381. if taicpu(hp1).opcode=A_CVTSD2SS then
  8382. begin
  8383. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8384. taicpu(p).opcode:=A_MOVAPS;
  8385. end
  8386. else
  8387. begin
  8388. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8389. taicpu(p).opcode:=A_VMOVAPS;
  8390. end;
  8391. taicpu(p).ops:=2;
  8392. RemoveInstruction(hp1);
  8393. end;
  8394. Result:=true;
  8395. Exit;
  8396. end;
  8397. end;
  8398. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8399. var
  8400. hp1, hp2, hp3, hp4, hp5: tai;
  8401. ThisReg: TRegister;
  8402. begin
  8403. Result := False;
  8404. if not GetNextInstruction(p,hp1) then
  8405. Exit;
  8406. {
  8407. convert
  8408. j<c> .L1
  8409. mov 1,reg
  8410. jmp .L2
  8411. .L1
  8412. mov 0,reg
  8413. .L2
  8414. into
  8415. mov 0,reg
  8416. set<not(c)> reg
  8417. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8418. would destroy the flag contents
  8419. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8420. executed at the same time as a previous comparison.
  8421. set<not(c)> reg
  8422. movzx reg, reg
  8423. }
  8424. if MatchInstruction(hp1,A_MOV,[]) and
  8425. (taicpu(hp1).oper[0]^.typ = top_const) and
  8426. (
  8427. (
  8428. (taicpu(hp1).oper[1]^.typ = top_reg)
  8429. {$ifdef i386}
  8430. { Under i386, ESI, EDI, EBP and ESP
  8431. don't have an 8-bit representation }
  8432. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8433. {$endif i386}
  8434. ) or (
  8435. {$ifdef i386}
  8436. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8437. {$endif i386}
  8438. (taicpu(hp1).opsize = S_B)
  8439. )
  8440. ) and
  8441. GetNextInstruction(hp1,hp2) and
  8442. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8443. GetNextInstruction(hp2,hp3) and
  8444. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8445. GetNextInstruction(hp3,hp4) and
  8446. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8447. (taicpu(hp4).oper[0]^.typ = top_const) and
  8448. (
  8449. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8450. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8451. ) and
  8452. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8453. GetNextInstruction(hp4,hp5) and
  8454. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8455. begin
  8456. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8457. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8458. tai_label(hp3).labsym.DecRefs;
  8459. { If this isn't the only reference to the middle label, we can
  8460. still make a saving - only that the first jump and everything
  8461. that follows will remain. }
  8462. if (tai_label(hp3).labsym.getrefs = 0) then
  8463. begin
  8464. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8465. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8466. else
  8467. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8468. { remove jump, first label and second MOV (also catching any aligns) }
  8469. repeat
  8470. if not GetNextInstruction(hp2, hp3) then
  8471. InternalError(2021040810);
  8472. RemoveInstruction(hp2);
  8473. hp2 := hp3;
  8474. until hp2 = hp5;
  8475. { Don't decrement reference count before the removal loop
  8476. above, otherwise GetNextInstruction won't stop on the
  8477. the label }
  8478. tai_label(hp5).labsym.DecRefs;
  8479. end
  8480. else
  8481. begin
  8482. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8483. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8484. else
  8485. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8486. end;
  8487. taicpu(p).opcode:=A_SETcc;
  8488. taicpu(p).opsize:=S_B;
  8489. taicpu(p).is_jmp:=False;
  8490. if taicpu(hp1).opsize=S_B then
  8491. begin
  8492. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8493. if taicpu(hp1).oper[1]^.typ = top_reg then
  8494. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8495. RemoveInstruction(hp1);
  8496. end
  8497. else
  8498. begin
  8499. { Will be a register because the size can't be S_B otherwise }
  8500. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8501. taicpu(p).loadreg(0, ThisReg);
  8502. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8503. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8504. begin
  8505. case taicpu(hp1).opsize of
  8506. S_W:
  8507. taicpu(hp1).opsize := S_BW;
  8508. S_L:
  8509. taicpu(hp1).opsize := S_BL;
  8510. {$ifdef x86_64}
  8511. S_Q:
  8512. begin
  8513. taicpu(hp1).opsize := S_BL;
  8514. { Change the destination register to 32-bit }
  8515. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8516. end;
  8517. {$endif x86_64}
  8518. else
  8519. InternalError(2021040820);
  8520. end;
  8521. taicpu(hp1).opcode := A_MOVZX;
  8522. taicpu(hp1).loadreg(0, ThisReg);
  8523. end
  8524. else
  8525. begin
  8526. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8527. { hp1 is already a MOV instruction with the correct register }
  8528. taicpu(hp1).loadconst(0, 0);
  8529. { Inserting it right before p will guarantee that the flags are also tracked }
  8530. asml.Remove(hp1);
  8531. asml.InsertBefore(hp1, p);
  8532. end;
  8533. end;
  8534. Result:=true;
  8535. exit;
  8536. end
  8537. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8538. Result := TryJccStcClcOpt(p, hp1)
  8539. else if (hp1.typ = ait_label) then
  8540. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8541. end;
  8542. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8543. var
  8544. hp1, hp2, hp3: tai;
  8545. SourceRef, TargetRef: TReference;
  8546. CurrentReg: TRegister;
  8547. begin
  8548. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8549. if not UseAVX then
  8550. InternalError(2021100501);
  8551. Result := False;
  8552. { Look for the following to simplify:
  8553. vmovdqa/u x(mem1), %xmmreg
  8554. vmovdqa/u %xmmreg, y(mem2)
  8555. vmovdqa/u x+16(mem1), %xmmreg
  8556. vmovdqa/u %xmmreg, y+16(mem2)
  8557. Change to:
  8558. vmovdqa/u x(mem1), %ymmreg
  8559. vmovdqa/u %ymmreg, y(mem2)
  8560. vpxor %ymmreg, %ymmreg, %ymmreg
  8561. ( The VPXOR instruction is to zero the upper half, thus removing the
  8562. need to call the potentially expensive VZEROUPPER instruction. Other
  8563. peephole optimisations can remove VPXOR if it's unnecessary )
  8564. }
  8565. TransferUsedRegs(TmpUsedRegs);
  8566. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8567. { NOTE: In the optimisations below, if the references dictate that an
  8568. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8569. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8570. if (taicpu(p).opsize = S_XMM) and
  8571. MatchOpType(taicpu(p), top_ref, top_reg) and
  8572. GetNextInstruction(p, hp1) and
  8573. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8574. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8575. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8576. begin
  8577. SourceRef := taicpu(p).oper[0]^.ref^;
  8578. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8579. if GetNextInstruction(hp1, hp2) and
  8580. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8581. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8582. begin
  8583. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8584. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8585. Inc(SourceRef.offset, 16);
  8586. { Reuse the register in the first block move }
  8587. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8588. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8589. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8590. begin
  8591. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8592. Inc(TargetRef.offset, 16);
  8593. if GetNextInstruction(hp2, hp3) and
  8594. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8595. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8596. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8597. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8598. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8599. begin
  8600. { Update the register tracking to the new size }
  8601. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8602. { Remember that the offsets are 16 ahead }
  8603. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8604. if not (
  8605. ((SourceRef.offset mod 32) = 16) and
  8606. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8607. ) then
  8608. taicpu(p).opcode := A_VMOVDQU;
  8609. taicpu(p).opsize := S_YMM;
  8610. taicpu(p).oper[1]^.reg := CurrentReg;
  8611. if not (
  8612. ((TargetRef.offset mod 32) = 16) and
  8613. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8614. ) then
  8615. taicpu(hp1).opcode := A_VMOVDQU;
  8616. taicpu(hp1).opsize := S_YMM;
  8617. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8618. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8619. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8620. if (pi_uses_ymm in current_procinfo.flags) then
  8621. RemoveInstruction(hp2)
  8622. else
  8623. begin
  8624. taicpu(hp2).opcode := A_VPXOR;
  8625. taicpu(hp2).opsize := S_YMM;
  8626. taicpu(hp2).loadreg(0, CurrentReg);
  8627. taicpu(hp2).loadreg(1, CurrentReg);
  8628. taicpu(hp2).loadreg(2, CurrentReg);
  8629. taicpu(hp2).ops := 3;
  8630. end;
  8631. RemoveInstruction(hp3);
  8632. Result := True;
  8633. Exit;
  8634. end;
  8635. end
  8636. else
  8637. begin
  8638. { See if the next references are 16 less rather than 16 greater }
  8639. Dec(SourceRef.offset, 32); { -16 the other way }
  8640. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8641. begin
  8642. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8643. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8644. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8645. GetNextInstruction(hp2, hp3) and
  8646. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8647. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8648. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8649. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8650. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8651. begin
  8652. { Update the register tracking to the new size }
  8653. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8654. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8655. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8656. if not(
  8657. ((SourceRef.offset mod 32) = 0) and
  8658. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8659. ) then
  8660. taicpu(hp2).opcode := A_VMOVDQU;
  8661. taicpu(hp2).opsize := S_YMM;
  8662. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8663. if not (
  8664. ((TargetRef.offset mod 32) = 0) and
  8665. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8666. ) then
  8667. taicpu(hp3).opcode := A_VMOVDQU;
  8668. taicpu(hp3).opsize := S_YMM;
  8669. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8670. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8671. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8672. if (pi_uses_ymm in current_procinfo.flags) then
  8673. RemoveInstruction(hp1)
  8674. else
  8675. begin
  8676. taicpu(hp1).opcode := A_VPXOR;
  8677. taicpu(hp1).opsize := S_YMM;
  8678. taicpu(hp1).loadreg(0, CurrentReg);
  8679. taicpu(hp1).loadreg(1, CurrentReg);
  8680. taicpu(hp1).loadreg(2, CurrentReg);
  8681. taicpu(hp1).ops := 3;
  8682. Asml.Remove(hp1);
  8683. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8684. end;
  8685. RemoveCurrentP(p, hp2);
  8686. Result := True;
  8687. Exit;
  8688. end;
  8689. end;
  8690. end;
  8691. end;
  8692. end;
  8693. end;
  8694. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8695. var
  8696. hp2, hp3, first_assignment: tai;
  8697. IncCount, OperIdx: Integer;
  8698. OrigLabel: TAsmLabel;
  8699. begin
  8700. Count := 0;
  8701. Result := False;
  8702. first_assignment := nil;
  8703. if (LoopCount >= 20) then
  8704. begin
  8705. { Guard against infinite loops }
  8706. Exit;
  8707. end;
  8708. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8709. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8710. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8711. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8712. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8713. Exit;
  8714. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8715. {
  8716. change
  8717. jmp .L1
  8718. ...
  8719. .L1:
  8720. mov ##, ## ( multiple movs possible )
  8721. jmp/ret
  8722. into
  8723. mov ##, ##
  8724. jmp/ret
  8725. }
  8726. if not Assigned(hp1) then
  8727. begin
  8728. hp1 := GetLabelWithSym(OrigLabel);
  8729. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8730. Exit;
  8731. end;
  8732. hp2 := hp1;
  8733. while Assigned(hp2) do
  8734. begin
  8735. if Assigned(hp2) and (hp2.typ = ait_label) then
  8736. SkipLabels(hp2,hp2);
  8737. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8738. Break;
  8739. case taicpu(hp2).opcode of
  8740. A_MOVSD:
  8741. begin
  8742. if taicpu(hp2).ops = 0 then
  8743. { Wrong MOVSD }
  8744. Break;
  8745. Inc(Count);
  8746. if Count >= 5 then
  8747. { Too many to be worthwhile }
  8748. Break;
  8749. GetNextInstruction(hp2, hp2);
  8750. Continue;
  8751. end;
  8752. A_MOV,
  8753. A_MOVD,
  8754. A_MOVQ,
  8755. A_MOVSX,
  8756. {$ifdef x86_64}
  8757. A_MOVSXD,
  8758. {$endif x86_64}
  8759. A_MOVZX,
  8760. A_MOVAPS,
  8761. A_MOVUPS,
  8762. A_MOVSS,
  8763. A_MOVAPD,
  8764. A_MOVUPD,
  8765. A_MOVDQA,
  8766. A_MOVDQU,
  8767. A_VMOVSS,
  8768. A_VMOVAPS,
  8769. A_VMOVUPS,
  8770. A_VMOVSD,
  8771. A_VMOVAPD,
  8772. A_VMOVUPD,
  8773. A_VMOVDQA,
  8774. A_VMOVDQU:
  8775. begin
  8776. Inc(Count);
  8777. if Count >= 5 then
  8778. { Too many to be worthwhile }
  8779. Break;
  8780. GetNextInstruction(hp2, hp2);
  8781. Continue;
  8782. end;
  8783. A_JMP:
  8784. begin
  8785. { Guard against infinite loops }
  8786. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8787. Exit;
  8788. { Analyse this jump first in case it also duplicates assignments }
  8789. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8790. begin
  8791. { Something did change! }
  8792. Result := True;
  8793. Inc(Count, IncCount);
  8794. if Count >= 5 then
  8795. begin
  8796. { Too many to be worthwhile }
  8797. Exit;
  8798. end;
  8799. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8800. Break;
  8801. end;
  8802. Result := True;
  8803. Break;
  8804. end;
  8805. A_RET:
  8806. begin
  8807. Result := True;
  8808. Break;
  8809. end;
  8810. else
  8811. Break;
  8812. end;
  8813. end;
  8814. if Result then
  8815. begin
  8816. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8817. if Count = 0 then
  8818. begin
  8819. Result := False;
  8820. Exit;
  8821. end;
  8822. TransferUsedRegs(TmpUsedRegs);
  8823. hp3 := p;
  8824. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8825. while True do
  8826. begin
  8827. if Assigned(hp1) and (hp1.typ = ait_label) then
  8828. SkipLabels(hp1,hp1);
  8829. case hp1.typ of
  8830. ait_regalloc:
  8831. if tai_regalloc(hp1).ratype = ra_dealloc then
  8832. begin
  8833. { Duplicate the register deallocation... }
  8834. hp3:=tai(hp1.getcopy);
  8835. if first_assignment = nil then
  8836. first_assignment := hp3;
  8837. asml.InsertBefore(hp3, p);
  8838. { ... but also reallocate it after the jump }
  8839. hp3:=tai(hp1.getcopy);
  8840. tai_regalloc(hp3).ratype := ra_alloc;
  8841. asml.InsertAfter(hp3, p);
  8842. end;
  8843. ait_instruction:
  8844. case taicpu(hp1).opcode of
  8845. A_JMP:
  8846. begin
  8847. { Change the original jump to the new destination }
  8848. OrigLabel.decrefs;
  8849. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8850. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8851. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8852. if not Assigned(first_assignment) then
  8853. InternalError(2021040810)
  8854. else
  8855. p := first_assignment;
  8856. Exit;
  8857. end;
  8858. A_RET:
  8859. begin
  8860. { Now change the jump into a RET instruction }
  8861. ConvertJumpToRET(p, hp1);
  8862. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8863. if not Assigned(first_assignment) then
  8864. InternalError(2021040811)
  8865. else
  8866. p := first_assignment;
  8867. Exit;
  8868. end;
  8869. else
  8870. begin
  8871. { Duplicate the MOV instruction }
  8872. hp3:=tai(hp1.getcopy);
  8873. if first_assignment = nil then
  8874. first_assignment := hp3;
  8875. asml.InsertBefore(hp3, p);
  8876. { Make sure the compiler knows about any final registers written here }
  8877. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8878. with taicpu(hp3).oper[OperIdx]^ do
  8879. begin
  8880. case typ of
  8881. top_ref:
  8882. begin
  8883. if (ref^.base <> NR_NO) and
  8884. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8885. (
  8886. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8887. (
  8888. { Allow the frame pointer if it's not being used by the procedure as such }
  8889. Assigned(current_procinfo) and
  8890. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8891. )
  8892. )
  8893. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8894. then
  8895. begin
  8896. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8897. if not Assigned(first_assignment) then
  8898. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8899. end;
  8900. if (ref^.index <> NR_NO) and
  8901. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8902. (
  8903. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8904. (
  8905. { Allow the frame pointer if it's not being used by the procedure as such }
  8906. Assigned(current_procinfo) and
  8907. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8908. )
  8909. )
  8910. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8911. (ref^.index <> ref^.base) then
  8912. begin
  8913. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8914. if not Assigned(first_assignment) then
  8915. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8916. end;
  8917. end;
  8918. top_reg:
  8919. begin
  8920. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8921. if not Assigned(first_assignment) then
  8922. IncludeRegInUsedRegs(reg, UsedRegs);
  8923. end;
  8924. else
  8925. ;
  8926. end;
  8927. end;
  8928. end;
  8929. end;
  8930. else
  8931. InternalError(2021040720);
  8932. end;
  8933. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8934. { Should have dropped out earlier }
  8935. InternalError(2021040710);
  8936. end;
  8937. end;
  8938. end;
  8939. const
  8940. WriteOp: array[0..3] of set of TInsChange = (
  8941. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8942. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8943. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8944. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8945. RegWriteFlags: array[0..7] of set of TInsChange = (
  8946. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8947. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8948. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8949. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8950. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8951. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8952. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8953. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8954. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8955. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8956. var
  8957. hp2: tai;
  8958. X: Integer;
  8959. begin
  8960. { If we have something like:
  8961. op ###,###
  8962. mov ###,###
  8963. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8964. interfere in regards to what they write to.
  8965. NOTE: p must be a 2-operand instruction
  8966. }
  8967. Result := False;
  8968. if (hp1.typ <> ait_instruction) or
  8969. taicpu(hp1).is_jmp or
  8970. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8971. Exit;
  8972. { NOP is a pipeline fence, likely marking the beginning of the function
  8973. epilogue, so drop out. Similarly, drop out if POP or RET are
  8974. encountered }
  8975. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8976. Exit;
  8977. if (taicpu(hp1).opcode = A_MOVSD) and
  8978. (taicpu(hp1).ops = 0) then
  8979. { Wrong MOVSD }
  8980. Exit;
  8981. { Check for writes to specific registers first }
  8982. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8983. for X := 0 to 7 do
  8984. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8985. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8986. Exit;
  8987. for X := 0 to taicpu(hp1).ops - 1 do
  8988. begin
  8989. { Check to see if this operand writes to something }
  8990. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8991. { And matches something in the CMP/TEST instruction }
  8992. (
  8993. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8994. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8995. (
  8996. { If it's a register, make sure the register written to doesn't
  8997. appear in the cmp instruction as part of a reference }
  8998. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8999. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  9000. )
  9001. ) then
  9002. Exit;
  9003. end;
  9004. { Check p to make sure it doesn't write to something that affects hp1 }
  9005. { Check for writes to specific registers first }
  9006. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9007. for X := 0 to 7 do
  9008. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  9009. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  9010. Exit;
  9011. for X := 0 to taicpu(p).ops - 1 do
  9012. begin
  9013. { Check to see if this operand writes to something }
  9014. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  9015. { And matches something in hp1 }
  9016. (taicpu(p).oper[X]^.typ = top_reg) and
  9017. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  9018. Exit;
  9019. end;
  9020. { The instruction can be safely moved }
  9021. asml.Remove(hp1);
  9022. { Try to insert after the last instructions where the FLAGS register is not
  9023. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  9024. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  9025. asml.InsertBefore(hp1, hp2)
  9026. { Failing that, try to insert after the last instructions where the
  9027. FLAGS register is not yet in use }
  9028. else if GetLastInstruction(p, hp2) and
  9029. (
  9030. (hp2.typ <> ait_instruction) or
  9031. { Don't insert after an instruction that uses the flags when p doesn't use them }
  9032. RegInInstruction(NR_DEFAULTFLAGS, p) or
  9033. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  9034. ) then
  9035. asml.InsertAfter(hp1, hp2)
  9036. else
  9037. { Note, if p.Previous is nil (even if it should logically never be the
  9038. case), FindRegAllocBackward immediately exits with False and so we
  9039. safely land here (we can't just pass p because FindRegAllocBackward
  9040. immediately exits on an instruction). [Kit] }
  9041. asml.InsertBefore(hp1, p);
  9042. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  9043. { We can't trust UsedRegs because we're looking backwards, although we
  9044. know the registers are allocated after p at the very least, so manually
  9045. create tai_regalloc objects if needed }
  9046. for X := 0 to taicpu(hp1).ops - 1 do
  9047. case taicpu(hp1).oper[X]^.typ of
  9048. top_reg:
  9049. begin
  9050. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  9051. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  9052. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  9053. end;
  9054. top_ref:
  9055. begin
  9056. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  9057. begin
  9058. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  9059. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  9060. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  9061. end;
  9062. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  9063. begin
  9064. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  9065. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  9066. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  9067. end;
  9068. end;
  9069. else
  9070. ;
  9071. end;
  9072. Result := True;
  9073. end;
  9074. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  9075. var
  9076. hp2: tai;
  9077. X: Integer;
  9078. begin
  9079. { If we have something like:
  9080. cmp ###,%reg1
  9081. mov 0,%reg2
  9082. And no modified registers are shared, move the instruction to before
  9083. the comparison as this means it can be optimised without worrying
  9084. about the FLAGS register. (CMP/MOV is generated by
  9085. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  9086. As long as the second instruction doesn't use the flags or one of the
  9087. registers used by CMP or TEST (also check any references that use the
  9088. registers), then it can be moved prior to the comparison.
  9089. }
  9090. Result := False;
  9091. if not TrySwapMovOp(p, hp1) then
  9092. Exit;
  9093. if taicpu(hp1).opcode = A_LEA then
  9094. { The flags will be overwritten by the CMP/TEST instruction }
  9095. ConvertLEA(taicpu(hp1));
  9096. Result := True;
  9097. { Can we move it one further back? }
  9098. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  9099. { Check to see if CMP/TEST is a comparison against zero }
  9100. (
  9101. (
  9102. (taicpu(p).opcode = A_CMP) and
  9103. MatchOperand(taicpu(p).oper[0]^, 0)
  9104. ) or
  9105. (
  9106. (taicpu(p).opcode = A_TEST) and
  9107. (
  9108. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9109. MatchOperand(taicpu(p).oper[0]^, -1)
  9110. )
  9111. )
  9112. ) and
  9113. { These instructions set the zero flag if the result is zero }
  9114. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9115. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9116. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9117. TrySwapMovOp(hp2, hp1);
  9118. end;
  9119. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9120. var
  9121. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9122. JumpLabel: TAsmLabel;
  9123. TmpBool: Boolean;
  9124. begin
  9125. Result := False;
  9126. { Look for:
  9127. stc/clc
  9128. j(c) .L1
  9129. ...
  9130. .L1:
  9131. set(n)cb %reg
  9132. (flags deallocated)
  9133. j(c) .L2
  9134. Change to:
  9135. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9136. j(c) .L2
  9137. }
  9138. p_last := p;
  9139. while GetNextInstruction(p_last, hp1) and
  9140. (hp1.typ = ait_instruction) and
  9141. IsJumpToLabel(taicpu(hp1)) do
  9142. begin
  9143. if DoJumpOptimizations(hp1, TmpBool) then
  9144. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9145. Continue;
  9146. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9147. if not Assigned(JumpLabel) then
  9148. InternalError(2024012801);
  9149. { Optimise the J(c); stc/clc optimisation first since this will
  9150. get missed if the main optimisation takes place }
  9151. if (taicpu(hp1).opcode = A_JCC) then
  9152. begin
  9153. if GetNextInstruction(hp1, hp2) and
  9154. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9155. TryJccStcClcOpt(hp1, hp2) then
  9156. begin
  9157. Result := True;
  9158. Exit;
  9159. end;
  9160. hp2 := nil; { Suppress compiler warning }
  9161. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9162. { Make sure the flags aren't used again }
  9163. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9164. begin
  9165. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9166. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9167. begin
  9168. if (taicpu(p).opcode = A_STC) then
  9169. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9170. else
  9171. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9172. MakeUnconditional(taicpu(hp1));
  9173. { Move the jump to after the flag deallocations }
  9174. Asml.Remove(hp1);
  9175. Asml.InsertAfter(hp1, hp2);
  9176. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9177. Result := True;
  9178. Exit;
  9179. end
  9180. else
  9181. begin
  9182. if (taicpu(p).opcode = A_STC) then
  9183. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9184. else
  9185. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9186. { In this case, the jump is deterministic in that it will never be taken }
  9187. JumpLabel.DecRefs;
  9188. RemoveInstruction(hp1);
  9189. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9190. Result := True;
  9191. Exit;
  9192. end;
  9193. end;
  9194. end;
  9195. hp2 := nil; { Suppress compiler warning }
  9196. if
  9197. { Make sure the carry flag doesn't appear in the jump conditions }
  9198. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9199. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9200. GetNextInstruction(hp2, p_dist) and
  9201. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9202. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9203. begin
  9204. case taicpu(p_dist).opcode of
  9205. A_Jcc:
  9206. begin
  9207. if DoJumpOptimizations(p_dist, TmpBool) then
  9208. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9209. Continue;
  9210. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9211. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9212. begin
  9213. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9214. JumpLabel.decrefs;
  9215. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9216. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9217. Result := True;
  9218. Exit;
  9219. end
  9220. else if GetNextInstruction(p_dist, hp1_dist) and
  9221. (hp1_dist.typ = ait_label) then
  9222. begin
  9223. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9224. JumpLabel.decrefs;
  9225. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9226. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9227. Result := True;
  9228. Exit;
  9229. end;
  9230. end;
  9231. A_SETcc:
  9232. if { Make sure the flags aren't used again }
  9233. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9234. GetNextInstruction(hp2, hp1_dist) and
  9235. (hp1_dist.typ = ait_instruction) and
  9236. IsJumpToLabel(taicpu(hp1_dist)) and
  9237. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9238. { This works if hp1_dist or both are regular JMP instructions }
  9239. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9240. (
  9241. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9242. { Make sure the register isn't still in use, otherwise it
  9243. may get corrupted (fixes #40659) }
  9244. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9245. ) then
  9246. begin
  9247. taicpu(p).allocate_oper(2);
  9248. taicpu(p).ops := 2;
  9249. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9250. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9251. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9252. taicpu(p).opcode := A_MOV;
  9253. taicpu(p).opsize := S_B;
  9254. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9255. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9256. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9257. JumpLabel.decrefs;
  9258. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9259. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9260. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9261. (tai_regalloc(hp2).ratype = ra_alloc) then
  9262. begin
  9263. Asml.Remove(hp2);
  9264. Asml.InsertAfter(hp2, p);
  9265. end;
  9266. Result := True;
  9267. Exit;
  9268. end;
  9269. else
  9270. ;
  9271. end;
  9272. end;
  9273. p_last := hp1;
  9274. end;
  9275. end;
  9276. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9277. var
  9278. hp2, hp3: tai;
  9279. TempBool: Boolean;
  9280. begin
  9281. Result := False;
  9282. {
  9283. j(c) .L1
  9284. stc/clc
  9285. .L1:
  9286. jc/jnc .L2
  9287. (Flags deallocated)
  9288. Change to:
  9289. j)c) .L1
  9290. jmp .L2
  9291. .L1:
  9292. jc/jnc .L2
  9293. Then call DoJumpOptimizations to convert to:
  9294. j(nc) .L2
  9295. .L1: (may become a dead label)
  9296. jc/jnc .L2
  9297. }
  9298. if GetNextInstruction(hp1, hp2) and
  9299. (hp2.typ = ait_label) and
  9300. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9301. GetNextInstruction(hp2, hp3) and
  9302. MatchInstruction(hp3, A_Jcc, []) and
  9303. (
  9304. (
  9305. (taicpu(hp3).condition = C_C) and
  9306. (taicpu(hp1).opcode = A_STC)
  9307. ) or (
  9308. (taicpu(hp3).condition = C_NC) and
  9309. (taicpu(hp1).opcode = A_CLC)
  9310. )
  9311. ) and
  9312. { Make sure the flags aren't used again }
  9313. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9314. begin
  9315. taicpu(hp1).allocate_oper(1);
  9316. taicpu(hp1).ops := 1;
  9317. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9318. taicpu(hp1).opcode := A_JMP;
  9319. taicpu(hp1).is_jmp := True;
  9320. TempBool := True; { Prevent compiler warnings }
  9321. if DoJumpOptimizations(p, TempBool) then
  9322. Result := True
  9323. else
  9324. Include(OptsToCheck, aoc_ForceNewIteration);
  9325. end;
  9326. end;
  9327. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9328. begin
  9329. { This generally only executes under -O3 and above }
  9330. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9331. end;
  9332. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9333. var
  9334. hp1, hp2: tai;
  9335. FoundComparison: Boolean;
  9336. begin
  9337. { Run the pass 1 optimisations as well, since they may have some effect
  9338. after the CMOV blocks are created in OptPass2Jcc }
  9339. Result := False;
  9340. { Result := OptPass1CMOVcc(p);
  9341. if Result then
  9342. Exit;}
  9343. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9344. and make a slightly inefficent result on branching-type blocks, notably
  9345. when setting a function result then jumping to the function epilogue.
  9346. In this case, change:
  9347. cmov(c) %reg1,%reg2
  9348. j(c) @lbl
  9349. (%reg2 deallocated)
  9350. To:
  9351. mov %reg11,%reg2
  9352. j(c) @lbl
  9353. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9354. jump because if it's not present, we may end up with a jump that's
  9355. completely unrelated.
  9356. }
  9357. hp1 := p;
  9358. while GetNextInstruction(hp1, hp1) and
  9359. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9360. if (hp1.typ = ait_instruction) and
  9361. (taicpu(hp1).opcode = A_Jcc) and
  9362. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9363. begin
  9364. TransferUsedRegs(TmpUsedRegs);
  9365. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9366. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9367. (
  9368. { See if we can find a more distant instruction that overwrites
  9369. the destination register }
  9370. (cs_opt_level3 in current_settings.optimizerswitches) and
  9371. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9372. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9373. ) then
  9374. begin
  9375. if (taicpu(p).oper[0]^.typ = top_reg) then
  9376. begin
  9377. { Search backwards to see if the source register is set to a
  9378. constant }
  9379. FoundComparison := False;
  9380. hp1 := p;
  9381. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9382. begin
  9383. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9384. begin
  9385. FoundComparison := True;
  9386. Continue;
  9387. end;
  9388. { Once we find the CMP, TEST or similar instruction, we
  9389. have to stop if we find anything other than a MOV }
  9390. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9391. Break;
  9392. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9393. { Destination register was modified }
  9394. Break;
  9395. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9396. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9397. begin
  9398. { Found a constant! }
  9399. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9400. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9401. { The source register is no longer in use }
  9402. RemoveInstruction(hp1);
  9403. Break;
  9404. end;
  9405. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9406. { Some other instruction has modified the source register }
  9407. Break;
  9408. end;
  9409. end;
  9410. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9411. taicpu(p).opcode := A_MOV;
  9412. taicpu(p).condition := C_None;
  9413. { Rely on the post peephole stage to put the MOV before the
  9414. CMP/TEST instruction that appears prior }
  9415. Result := True;
  9416. Exit;
  9417. end;
  9418. end;
  9419. end;
  9420. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9421. function IsXCHGAcceptable: Boolean; inline;
  9422. begin
  9423. { Always accept if optimising for size }
  9424. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9425. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9426. than 3, so it becomes a saving compared to three MOVs with two of
  9427. them able to execute simultaneously. [Kit] }
  9428. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9429. end;
  9430. var
  9431. NewRef: TReference;
  9432. hp1, hp2, hp3, hp4: Tai;
  9433. {$ifndef x86_64}
  9434. OperIdx: Integer;
  9435. {$endif x86_64}
  9436. NewInstr : Taicpu;
  9437. NewAligh : Tai_align;
  9438. DestLabel: TAsmLabel;
  9439. TempTracking: TAllUsedRegs;
  9440. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9441. var
  9442. NextInstr: tai;
  9443. begin
  9444. Result := False;
  9445. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9446. if not GetNextInstruction(InputInstr, NextInstr) or
  9447. (
  9448. { The FLAGS register isn't always tracked properly, so do not
  9449. perform this optimisation if a conditional statement follows }
  9450. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9451. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9452. ) then
  9453. begin
  9454. reference_reset(NewRef, 1, []);
  9455. NewRef.base := taicpu(p).oper[0]^.reg;
  9456. NewRef.scalefactor := 1;
  9457. if taicpu(InputInstr).opcode = A_ADD then
  9458. begin
  9459. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9460. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9461. end
  9462. else
  9463. begin
  9464. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9465. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9466. end;
  9467. taicpu(p).opcode := A_LEA;
  9468. taicpu(p).loadref(0, NewRef);
  9469. { For the sake of debugging, have the line info match the
  9470. arithmetic instruction rather than the MOV instruction }
  9471. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9472. RemoveInstruction(InputInstr);
  9473. Result := True;
  9474. end;
  9475. end;
  9476. begin
  9477. Result:=false;
  9478. { This optimisation adds an instruction, so only do it for speed }
  9479. if not (cs_opt_size in current_settings.optimizerswitches) and
  9480. MatchOpType(taicpu(p), top_const, top_reg) and
  9481. (taicpu(p).oper[0]^.val = 0) then
  9482. begin
  9483. { To avoid compiler warning }
  9484. DestLabel := nil;
  9485. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9486. InternalError(2021040750);
  9487. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9488. Exit;
  9489. case hp1.typ of
  9490. ait_label:
  9491. begin
  9492. { Change:
  9493. mov $0,%reg mov $0,%reg
  9494. @Lbl1: @Lbl1:
  9495. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9496. je @Lbl2 jne @Lbl2
  9497. To: To:
  9498. mov $0,%reg mov $0,%reg
  9499. jmp @Lbl2 jmp @Lbl3
  9500. (align) (align)
  9501. @Lbl1: @Lbl1:
  9502. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9503. je @Lbl2 je @Lbl2
  9504. @Lbl3: <-- Only if label exists
  9505. (Not if it's optimised for size)
  9506. }
  9507. if not GetNextInstruction(hp1, hp2) then
  9508. Exit;
  9509. if (hp2.typ = ait_instruction) and
  9510. (
  9511. { Register sizes must exactly match }
  9512. (
  9513. (taicpu(hp2).opcode = A_CMP) and
  9514. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9515. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9516. ) or (
  9517. (taicpu(hp2).opcode = A_TEST) and
  9518. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9519. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9520. )
  9521. ) and GetNextInstruction(hp2, hp3) and
  9522. (hp3.typ = ait_instruction) and
  9523. (taicpu(hp3).opcode = A_JCC) and
  9524. (taicpu(hp3).oper[0]^.typ=top_ref) and (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and (taicpu(hp3).oper[0]^.ref^.base=NR_NO) and
  9525. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9526. begin
  9527. { Check condition of jump }
  9528. { Always true? }
  9529. if condition_in(C_E, taicpu(hp3).condition) then
  9530. begin
  9531. { Copy label symbol and obtain matching label entry for the
  9532. conditional jump, as this will be our destination}
  9533. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9534. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9535. Result := True;
  9536. end
  9537. { Always false? }
  9538. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9539. begin
  9540. { This is only worth it if there's a jump to take }
  9541. case hp2.typ of
  9542. ait_instruction:
  9543. begin
  9544. if taicpu(hp2).opcode = A_JMP then
  9545. begin
  9546. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9547. { An unconditional jump follows the conditional jump which will always be false,
  9548. so use this jump's destination for the new jump }
  9549. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9550. Result := True;
  9551. end
  9552. else if taicpu(hp2).opcode = A_JCC then
  9553. begin
  9554. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9555. if condition_in(C_E, taicpu(hp2).condition) then
  9556. begin
  9557. { A second conditional jump follows the conditional jump which will always be false,
  9558. while the second jump is always True, so use this jump's destination for the new jump }
  9559. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9560. Result := True;
  9561. end;
  9562. { Don't risk it if the jump isn't always true (Result remains False) }
  9563. end;
  9564. end;
  9565. else
  9566. { If anything else don't optimise };
  9567. end;
  9568. end;
  9569. if Result then
  9570. begin
  9571. { Just so we have something to insert as a paremeter}
  9572. reference_reset(NewRef, 1, []);
  9573. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9574. { Now actually load the correct parameter (this also
  9575. increases the reference count) }
  9576. NewInstr.loadsymbol(0, DestLabel, 0);
  9577. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9578. begin
  9579. { Get instruction before original label (may not be p under -O3) }
  9580. if not GetLastInstruction(hp1, hp2) then
  9581. { Shouldn't fail here }
  9582. InternalError(2021040701);
  9583. end
  9584. else
  9585. hp2 := p;
  9586. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9587. AsmL.InsertAfter(NewInstr, hp2);
  9588. { Add new alignment field }
  9589. (* AsmL.InsertAfter(
  9590. cai_align.create_max(
  9591. current_settings.alignment.jumpalign,
  9592. current_settings.alignment.jumpalignskipmax
  9593. ),
  9594. NewInstr
  9595. ); *)
  9596. end;
  9597. Exit;
  9598. end;
  9599. end;
  9600. else
  9601. ;
  9602. end;
  9603. end;
  9604. if not GetNextInstruction(p, hp1) then
  9605. Exit;
  9606. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9607. begin
  9608. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9609. begin
  9610. Result := True;
  9611. Exit;
  9612. end;
  9613. { This optimisation is only effective on a second run of Pass 2,
  9614. hence -O3 or above.
  9615. Change:
  9616. mov %reg1,%reg2
  9617. cmp/test (contains %reg1)
  9618. mov x, %reg1
  9619. (another mov or a j(c))
  9620. To:
  9621. mov %reg1,%reg2
  9622. mov x, %reg1
  9623. cmp (%reg1 replaced with %reg2)
  9624. (another mov or a j(c))
  9625. The requirement of an additional MOV or a jump ensures there
  9626. isn't performance loss, since a j(c) will permit macro-fusion
  9627. with the cmp instruction, while another MOV likely means it's
  9628. not all being executed in a single cycle due to parallelisation.
  9629. }
  9630. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9631. MatchOpType(taicpu(p), top_reg, top_reg) and
  9632. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9633. GetNextInstruction(hp1, hp2) and
  9634. MatchInstruction(hp2, A_MOV, []) and
  9635. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9636. { Registers don't have to be the same size in this case }
  9637. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9638. GetNextInstruction(hp2, hp3) and
  9639. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9640. { Make sure the operands in the camparison can be safely replaced }
  9641. (
  9642. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9643. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9644. ) and
  9645. (
  9646. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9647. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9648. ) then
  9649. begin
  9650. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9651. AsmL.Remove(hp2);
  9652. AsmL.InsertAfter(hp2, p);
  9653. Result := True;
  9654. Exit;
  9655. end;
  9656. end;
  9657. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9658. begin
  9659. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9660. further, but we can't just put this jump optimisation in pass 1
  9661. because it tends to perform worse when conditional jumps are
  9662. nearby (e.g. when converting CMOV instructions). [Kit] }
  9663. CopyUsedRegs(TempTracking);
  9664. UpdateUsedRegs(tai(p.Next));
  9665. if OptPass2JMP(hp1) then
  9666. begin
  9667. { Restore register state }
  9668. RestoreUsedRegs(TempTracking);
  9669. ReleaseUsedRegs(TempTracking);
  9670. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9671. OptPass1MOV(p);
  9672. Result := True;
  9673. Exit;
  9674. end;
  9675. { If OptPass2JMP returned False, no optimisations were done to
  9676. the jump and there are no further optimisations that can be done
  9677. to the MOV instruction on this pass other than FuncMov2Func }
  9678. { Restore register state }
  9679. RestoreUsedRegs(TempTracking);
  9680. ReleaseUsedRegs(TempTracking);
  9681. Result := FuncMov2Func(p, hp1);
  9682. Exit;
  9683. end;
  9684. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9685. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9686. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9687. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9688. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9689. begin
  9690. { Change:
  9691. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9692. addl/q $x,%reg2 subl/q $x,%reg2
  9693. To:
  9694. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9695. }
  9696. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9697. { be lazy, checking separately for sub would be slightly better }
  9698. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9699. begin
  9700. TransferUsedRegs(TmpUsedRegs);
  9701. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9702. if TryMovArith2Lea(hp1) then
  9703. begin
  9704. Result := True;
  9705. Exit;
  9706. end
  9707. end
  9708. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9709. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9710. { Same as above, but also adds or subtracts to %reg2 in between.
  9711. It's still valid as long as the flags aren't in use }
  9712. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9713. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9714. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9715. { be lazy, checking separately for sub would be slightly better }
  9716. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9717. begin
  9718. TransferUsedRegs(TmpUsedRegs);
  9719. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9720. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9721. if TryMovArith2Lea(hp2) then
  9722. begin
  9723. Result := True;
  9724. Exit;
  9725. end;
  9726. end;
  9727. end;
  9728. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9729. {$ifdef x86_64}
  9730. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9731. {$else x86_64}
  9732. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9733. {$endif x86_64}
  9734. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9735. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9736. { mov reg1, reg2 mov reg1, reg2
  9737. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9738. begin
  9739. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9740. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9741. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9742. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9743. TransferUsedRegs(TmpUsedRegs);
  9744. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9745. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9746. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9747. then
  9748. begin
  9749. RemoveCurrentP(p, hp1);
  9750. Result:=true;
  9751. end;
  9752. Exit;
  9753. end;
  9754. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9755. IsXCHGAcceptable and
  9756. { XCHG doesn't support 8-bit registers }
  9757. (taicpu(p).opsize <> S_B) and
  9758. MatchInstruction(hp1, A_MOV, []) and
  9759. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9760. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9761. GetNextInstruction(hp1, hp2) and
  9762. MatchInstruction(hp2, A_MOV, []) and
  9763. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9764. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9765. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9766. begin
  9767. { mov %reg1,%reg2
  9768. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9769. mov %reg2,%reg3
  9770. (%reg2 not used afterwards)
  9771. Note that xchg takes 3 cycles to execute, and generally mov's take
  9772. only one cycle apiece, but the first two mov's can be executed in
  9773. parallel, only taking 2 cycles overall. Older processors should
  9774. therefore only optimise for size. [Kit]
  9775. }
  9776. TransferUsedRegs(TmpUsedRegs);
  9777. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9778. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9779. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9780. begin
  9781. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9782. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9783. taicpu(hp1).opcode := A_XCHG;
  9784. RemoveCurrentP(p, hp1);
  9785. RemoveInstruction(hp2);
  9786. Result := True;
  9787. Exit;
  9788. end;
  9789. end;
  9790. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9791. MatchInstruction(hp1, A_SAR, []) then
  9792. begin
  9793. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9794. begin
  9795. { the use of %edx also covers the opsize being S_L }
  9796. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9797. begin
  9798. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9799. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9800. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9801. begin
  9802. { Change:
  9803. movl %eax,%edx
  9804. sarl $31,%edx
  9805. To:
  9806. cltd
  9807. }
  9808. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9809. RemoveInstruction(hp1);
  9810. taicpu(p).opcode := A_CDQ;
  9811. taicpu(p).opsize := S_NO;
  9812. taicpu(p).clearop(1);
  9813. taicpu(p).clearop(0);
  9814. taicpu(p).ops:=0;
  9815. Result := True;
  9816. Exit;
  9817. end
  9818. else if (cs_opt_size in current_settings.optimizerswitches) and
  9819. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9820. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9821. begin
  9822. { Change:
  9823. movl %edx,%eax
  9824. sarl $31,%edx
  9825. To:
  9826. movl %edx,%eax
  9827. cltd
  9828. Note that this creates a dependency between the two instructions,
  9829. so only perform if optimising for size.
  9830. }
  9831. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9832. taicpu(hp1).opcode := A_CDQ;
  9833. taicpu(hp1).opsize := S_NO;
  9834. taicpu(hp1).clearop(1);
  9835. taicpu(hp1).clearop(0);
  9836. taicpu(hp1).ops:=0;
  9837. Include(OptsToCheck, aoc_ForceNewIteration);
  9838. Exit;
  9839. end;
  9840. {$ifndef x86_64}
  9841. end
  9842. { Don't bother if CMOV is supported, because a more optimal
  9843. sequence would have been generated for the Abs() intrinsic }
  9844. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9845. { the use of %eax also covers the opsize being S_L }
  9846. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9847. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9848. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9849. GetNextInstruction(hp1, hp2) and
  9850. MatchInstruction(hp2, A_XOR, [S_L]) and
  9851. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9852. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9853. GetNextInstruction(hp2, hp3) and
  9854. MatchInstruction(hp3, A_SUB, [S_L]) and
  9855. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9856. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9857. begin
  9858. { Change:
  9859. movl %eax,%edx
  9860. sarl $31,%eax
  9861. xorl %eax,%edx
  9862. subl %eax,%edx
  9863. (Instruction that uses %edx)
  9864. (%eax deallocated)
  9865. (%edx deallocated)
  9866. To:
  9867. cltd
  9868. xorl %edx,%eax <-- Note the registers have swapped
  9869. subl %edx,%eax
  9870. (Instruction that uses %eax) <-- %eax rather than %edx
  9871. }
  9872. TransferUsedRegs(TmpUsedRegs);
  9873. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9874. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9875. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9876. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9877. begin
  9878. if GetNextInstruction(hp3, hp4) and
  9879. not RegModifiedByInstruction(NR_EDX, hp4) and
  9880. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9881. begin
  9882. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9883. taicpu(p).opcode := A_CDQ;
  9884. taicpu(p).clearop(1);
  9885. taicpu(p).clearop(0);
  9886. taicpu(p).ops:=0;
  9887. RemoveInstruction(hp1);
  9888. taicpu(hp2).loadreg(0, NR_EDX);
  9889. taicpu(hp2).loadreg(1, NR_EAX);
  9890. taicpu(hp3).loadreg(0, NR_EDX);
  9891. taicpu(hp3).loadreg(1, NR_EAX);
  9892. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9893. { Convert references in the following instruction (hp4) from %edx to %eax }
  9894. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9895. with taicpu(hp4).oper[OperIdx]^ do
  9896. case typ of
  9897. top_reg:
  9898. if getsupreg(reg) = RS_EDX then
  9899. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9900. top_ref:
  9901. begin
  9902. if getsupreg(reg) = RS_EDX then
  9903. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9904. if getsupreg(reg) = RS_EDX then
  9905. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9906. end;
  9907. else
  9908. ;
  9909. end;
  9910. Result := True;
  9911. Exit;
  9912. end;
  9913. end;
  9914. {$else x86_64}
  9915. end;
  9916. end
  9917. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9918. { the use of %rdx also covers the opsize being S_Q }
  9919. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9920. begin
  9921. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9922. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9923. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9924. begin
  9925. { Change:
  9926. movq %rax,%rdx
  9927. sarq $63,%rdx
  9928. To:
  9929. cqto
  9930. }
  9931. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9932. RemoveInstruction(hp1);
  9933. taicpu(p).opcode := A_CQO;
  9934. taicpu(p).opsize := S_NO;
  9935. taicpu(p).clearop(1);
  9936. taicpu(p).clearop(0);
  9937. taicpu(p).ops:=0;
  9938. Result := True;
  9939. Exit;
  9940. end
  9941. else if (cs_opt_size in current_settings.optimizerswitches) and
  9942. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9943. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9944. begin
  9945. { Change:
  9946. movq %rdx,%rax
  9947. sarq $63,%rdx
  9948. To:
  9949. movq %rdx,%rax
  9950. cqto
  9951. Note that this creates a dependency between the two instructions,
  9952. so only perform if optimising for size.
  9953. }
  9954. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9955. taicpu(hp1).opcode := A_CQO;
  9956. taicpu(hp1).opsize := S_NO;
  9957. taicpu(hp1).clearop(1);
  9958. taicpu(hp1).clearop(0);
  9959. taicpu(hp1).ops:=0;
  9960. Include(OptsToCheck, aoc_ForceNewIteration);
  9961. Exit;
  9962. {$endif x86_64}
  9963. end;
  9964. end;
  9965. end;
  9966. if MatchInstruction(hp1, A_MOV, []) and
  9967. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9968. { Though "GetNextInstruction" could be factored out, along with
  9969. the instructions that depend on hp2, it is an expensive call that
  9970. should be delayed for as long as possible, hence we do cheaper
  9971. checks first that are likely to be False. [Kit] }
  9972. begin
  9973. if (
  9974. (
  9975. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9976. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9977. (
  9978. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9979. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9980. )
  9981. ) or
  9982. (
  9983. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9984. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9985. (
  9986. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9987. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9988. )
  9989. )
  9990. ) and
  9991. GetNextInstruction(hp1, hp2) and
  9992. MatchInstruction(hp2, A_SAR, []) and
  9993. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9994. begin
  9995. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9996. begin
  9997. { Change:
  9998. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9999. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  10000. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  10001. To:
  10002. movl r/m,%eax <- Note the change in register
  10003. cltd
  10004. }
  10005. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  10006. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  10007. taicpu(p).loadreg(1, NR_EAX);
  10008. taicpu(hp1).opcode := A_CDQ;
  10009. taicpu(hp1).clearop(1);
  10010. taicpu(hp1).clearop(0);
  10011. taicpu(hp1).ops:=0;
  10012. RemoveInstruction(hp2);
  10013. Include(OptsToCheck, aoc_ForceNewIteration);
  10014. (*
  10015. {$ifdef x86_64}
  10016. end
  10017. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  10018. { This code sequence does not get generated - however it might become useful
  10019. if and when 128-bit signed integer types make an appearance, so the code
  10020. is kept here for when it is eventually needed. [Kit] }
  10021. (
  10022. (
  10023. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  10024. (
  10025. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10026. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  10027. )
  10028. ) or
  10029. (
  10030. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  10031. (
  10032. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10033. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  10034. )
  10035. )
  10036. ) and
  10037. GetNextInstruction(hp1, hp2) and
  10038. MatchInstruction(hp2, A_SAR, [S_Q]) and
  10039. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  10040. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  10041. begin
  10042. { Change:
  10043. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  10044. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  10045. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  10046. To:
  10047. movq r/m,%rax <- Note the change in register
  10048. cqto
  10049. }
  10050. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  10051. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  10052. taicpu(p).loadreg(1, NR_RAX);
  10053. taicpu(hp1).opcode := A_CQO;
  10054. taicpu(hp1).clearop(1);
  10055. taicpu(hp1).clearop(0);
  10056. taicpu(hp1).ops:=0;
  10057. RemoveInstruction(hp2);
  10058. Include(OptsToCheck, aoc_ForceNewIteration);
  10059. {$endif x86_64}
  10060. *)
  10061. end;
  10062. end;
  10063. {$ifdef x86_64}
  10064. end;
  10065. if (taicpu(p).opsize = S_L) and
  10066. (taicpu(p).oper[1]^.typ = top_reg) and
  10067. (
  10068. MatchInstruction(hp1, A_MOV,[]) and
  10069. (taicpu(hp1).opsize = S_L) and
  10070. (taicpu(hp1).oper[1]^.typ = top_reg)
  10071. ) and (
  10072. GetNextInstruction(hp1, hp2) and
  10073. (tai(hp2).typ=ait_instruction) and
  10074. (taicpu(hp2).opsize = S_Q) and
  10075. (
  10076. (
  10077. MatchInstruction(hp2, A_ADD,[]) and
  10078. (taicpu(hp2).opsize = S_Q) and
  10079. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10080. (
  10081. (
  10082. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10083. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10084. ) or (
  10085. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10086. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10087. )
  10088. )
  10089. ) or (
  10090. MatchInstruction(hp2, A_LEA,[]) and
  10091. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  10092. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  10093. (
  10094. (
  10095. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10096. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10097. ) or (
  10098. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10099. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  10100. )
  10101. ) and (
  10102. (
  10103. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10104. ) or (
  10105. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10106. )
  10107. )
  10108. )
  10109. )
  10110. ) and (
  10111. GetNextInstruction(hp2, hp3) and
  10112. MatchInstruction(hp3, A_SHR,[]) and
  10113. (taicpu(hp3).opsize = S_Q) and
  10114. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10115. (taicpu(hp3).oper[0]^.val = 1) and
  10116. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10117. ) then
  10118. begin
  10119. { Change movl x, reg1d movl x, reg1d
  10120. movl y, reg2d movl y, reg2d
  10121. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10122. shrq $1, reg1q shrq $1, reg1q
  10123. ( reg1d and reg2d can be switched around in the first two instructions )
  10124. To movl x, reg1d
  10125. addl y, reg1d
  10126. rcrl $1, reg1d
  10127. This corresponds to the common expression (x + y) shr 1, where
  10128. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10129. smaller code, but won't account for x + y causing an overflow). [Kit]
  10130. }
  10131. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10132. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10133. begin
  10134. { Change first MOV command to have the same register as the final output }
  10135. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10136. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10137. Result := True;
  10138. end
  10139. else
  10140. begin
  10141. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10142. Include(OptsToCheck, aoc_ForceNewIteration);
  10143. end;
  10144. { Change second MOV command to an ADD command. This is easier than
  10145. converting the existing command because it means we don't have to
  10146. touch 'y', which might be a complicated reference, and also the
  10147. fact that the third command might either be ADD or LEA. [Kit] }
  10148. taicpu(hp1).opcode := A_ADD;
  10149. { Delete old ADD/LEA instruction }
  10150. RemoveInstruction(hp2);
  10151. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10152. taicpu(hp3).opcode := A_RCR;
  10153. taicpu(hp3).changeopsize(S_L);
  10154. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10155. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10156. called, so FuncMov2Func below is safe to call }
  10157. {$endif x86_64}
  10158. end;
  10159. if FuncMov2Func(p, hp1) then
  10160. begin
  10161. Result := True;
  10162. Exit;
  10163. end;
  10164. end;
  10165. {$push}
  10166. {$q-}{$r-}
  10167. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10168. var
  10169. ThisReg: TRegister;
  10170. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10171. TargetSubReg: TSubRegister;
  10172. hp1, hp2: tai;
  10173. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10174. { Store list of found instructions so we don't have to call
  10175. GetNextInstructionUsingReg multiple times }
  10176. InstrList: array of taicpu;
  10177. InstrMax, Index: Integer;
  10178. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10179. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10180. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10181. WorkingValue: TCgInt;
  10182. PreMessage: string;
  10183. { Data flow analysis }
  10184. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10185. BitwiseOnly, OrXorUsed,
  10186. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10187. function CheckOverflowConditions: Boolean;
  10188. begin
  10189. Result := True;
  10190. if (TestValSignedMax > SignedUpperLimit) then
  10191. UpperSignedOverflow := True;
  10192. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10193. LowerSignedOverflow := True;
  10194. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10195. LowerUnsignedOverflow := True;
  10196. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10197. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10198. begin
  10199. { Absolute overflow }
  10200. Result := False;
  10201. Exit;
  10202. end;
  10203. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10204. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10205. ShiftDownOverflow := True;
  10206. if (TestValMin < 0) or (TestValMax < 0) then
  10207. begin
  10208. LowerUnsignedOverflow := True;
  10209. UpperUnsignedOverflow := True;
  10210. end;
  10211. end;
  10212. function AdjustInitialLoadAndSize: Boolean;
  10213. begin
  10214. Result := False;
  10215. if not p_removed then
  10216. begin
  10217. if TargetSize = MinSize then
  10218. begin
  10219. { Convert the input MOVZX to a MOV }
  10220. if (taicpu(p).oper[0]^.typ = top_reg) and
  10221. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10222. begin
  10223. { Or remove it completely! }
  10224. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10225. RemoveCurrentP(p);
  10226. p_removed := True;
  10227. end
  10228. else
  10229. begin
  10230. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10231. taicpu(p).opcode := A_MOV;
  10232. taicpu(p).oper[1]^.reg := ThisReg;
  10233. taicpu(p).opsize := TargetSize;
  10234. end;
  10235. Result := True;
  10236. end
  10237. else if TargetSize <> MaxSize then
  10238. begin
  10239. case MaxSize of
  10240. S_L:
  10241. if TargetSize = S_W then
  10242. begin
  10243. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10244. taicpu(p).opsize := S_BW;
  10245. taicpu(p).oper[1]^.reg := ThisReg;
  10246. Result := True;
  10247. end
  10248. else
  10249. InternalError(2020112341);
  10250. S_W:
  10251. if TargetSize = S_L then
  10252. begin
  10253. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10254. taicpu(p).opsize := S_BL;
  10255. taicpu(p).oper[1]^.reg := ThisReg;
  10256. Result := True;
  10257. end
  10258. else
  10259. InternalError(2020112342);
  10260. else
  10261. ;
  10262. end;
  10263. end
  10264. else if not hp1_removed and not RegInUse then
  10265. begin
  10266. { If we have something like:
  10267. movzbl (oper),%regd
  10268. add x, %regd
  10269. movzbl %regb, %regd
  10270. We can reduce the register size to the input of the final
  10271. movzbl instruction. Overflows won't have any effect.
  10272. }
  10273. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10274. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10275. begin
  10276. TargetSize := S_B;
  10277. setsubreg(ThisReg, R_SUBL);
  10278. Result := True;
  10279. end
  10280. else if (taicpu(p).opsize = S_WL) and
  10281. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10282. begin
  10283. TargetSize := S_W;
  10284. setsubreg(ThisReg, R_SUBW);
  10285. Result := True;
  10286. end;
  10287. if Result then
  10288. begin
  10289. { Convert the input MOVZX to a MOV }
  10290. if (taicpu(p).oper[0]^.typ = top_reg) and
  10291. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10292. begin
  10293. { Or remove it completely! }
  10294. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10295. RemoveCurrentP(p);
  10296. p_removed := True;
  10297. end
  10298. else
  10299. begin
  10300. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10301. taicpu(p).opcode := A_MOV;
  10302. taicpu(p).oper[1]^.reg := ThisReg;
  10303. taicpu(p).opsize := TargetSize;
  10304. end;
  10305. end;
  10306. end;
  10307. end;
  10308. end;
  10309. procedure AdjustFinalLoad;
  10310. begin
  10311. if not LowerUnsignedOverflow then
  10312. begin
  10313. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10314. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10315. begin
  10316. { Convert the output MOVZX to a MOV }
  10317. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10318. begin
  10319. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10320. if (MinSize = S_B) or
  10321. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10322. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10323. begin
  10324. { Remove it completely! }
  10325. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10326. { Be careful; if p = hp1 and p was also removed, p
  10327. will become a dangling pointer }
  10328. if p = hp1 then
  10329. begin
  10330. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10331. p_removed := True;
  10332. end
  10333. else
  10334. RemoveInstruction(hp1);
  10335. hp1_removed := True;
  10336. end;
  10337. end
  10338. else
  10339. begin
  10340. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10341. taicpu(hp1).opcode := A_MOV;
  10342. taicpu(hp1).oper[0]^.reg := ThisReg;
  10343. taicpu(hp1).opsize := TargetSize;
  10344. end;
  10345. end
  10346. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10347. begin
  10348. { Need to change the size of the output }
  10349. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10350. taicpu(hp1).oper[0]^.reg := ThisReg;
  10351. taicpu(hp1).opsize := S_BL;
  10352. end;
  10353. end;
  10354. end;
  10355. function CompressInstructions: Boolean;
  10356. var
  10357. LocalIndex: Integer;
  10358. begin
  10359. Result := False;
  10360. { The objective here is to try to find a combination that
  10361. removes one of the MOV/Z instructions. }
  10362. if (
  10363. (taicpu(p).oper[0]^.typ <> top_reg) or
  10364. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10365. ) and
  10366. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10367. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10368. begin
  10369. { Make a preference to remove the second MOVZX instruction }
  10370. case taicpu(hp1).opsize of
  10371. S_BL, S_WL:
  10372. begin
  10373. TargetSize := S_L;
  10374. TargetSubReg := R_SUBD;
  10375. end;
  10376. S_BW:
  10377. begin
  10378. TargetSize := S_W;
  10379. TargetSubReg := R_SUBW;
  10380. end;
  10381. else
  10382. InternalError(2020112302);
  10383. end;
  10384. end
  10385. else
  10386. begin
  10387. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10388. begin
  10389. { Exceeded lower bound but not upper bound }
  10390. TargetSize := MaxSize;
  10391. end
  10392. else if not LowerUnsignedOverflow then
  10393. begin
  10394. { Size didn't exceed lower bound }
  10395. TargetSize := MinSize;
  10396. end
  10397. else
  10398. Exit;
  10399. end;
  10400. case TargetSize of
  10401. S_B:
  10402. TargetSubReg := R_SUBL;
  10403. S_W:
  10404. TargetSubReg := R_SUBW;
  10405. S_L:
  10406. TargetSubReg := R_SUBD;
  10407. else
  10408. InternalError(2020112350);
  10409. end;
  10410. { Update the register to its new size }
  10411. setsubreg(ThisReg, TargetSubReg);
  10412. RegInUse := False;
  10413. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10414. begin
  10415. { Check to see if the active register is used afterwards;
  10416. if not, we can change it and make a saving. }
  10417. TransferUsedRegs(TmpUsedRegs);
  10418. { The target register may be marked as in use to cross
  10419. a jump to a distant label, so exclude it }
  10420. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10421. hp2 := p;
  10422. repeat
  10423. { Explicitly check for the excluded register (don't include the first
  10424. instruction as it may be reading from here }
  10425. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10426. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10427. begin
  10428. RegInUse := True;
  10429. Break;
  10430. end;
  10431. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10432. if not GetNextInstruction(hp2, hp2) then
  10433. InternalError(2020112340);
  10434. until (hp2 = hp1);
  10435. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10436. { We might still be able to get away with this }
  10437. RegInUse := not
  10438. (
  10439. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10440. (hp2.typ = ait_instruction) and
  10441. (
  10442. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10443. instruction that doesn't actually contain ThisReg }
  10444. (cs_opt_level3 in current_settings.optimizerswitches) or
  10445. RegInInstruction(ThisReg, hp2)
  10446. ) and
  10447. RegLoadedWithNewValue(ThisReg, hp2)
  10448. );
  10449. if not RegInUse then
  10450. begin
  10451. { Force the register size to the same as this instruction so it can be removed}
  10452. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10453. begin
  10454. TargetSize := S_L;
  10455. TargetSubReg := R_SUBD;
  10456. end
  10457. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10458. begin
  10459. TargetSize := S_W;
  10460. TargetSubReg := R_SUBW;
  10461. end;
  10462. ThisReg := taicpu(hp1).oper[1]^.reg;
  10463. setsubreg(ThisReg, TargetSubReg);
  10464. RegChanged := True;
  10465. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10466. TransferUsedRegs(TmpUsedRegs);
  10467. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10468. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10469. if p = hp1 then
  10470. begin
  10471. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10472. p_removed := True;
  10473. end
  10474. else
  10475. RemoveInstruction(hp1);
  10476. hp1_removed := True;
  10477. { Instruction will become "mov %reg,%reg" }
  10478. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10479. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10480. begin
  10481. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10482. RemoveCurrentP(p);
  10483. p_removed := True;
  10484. end
  10485. else
  10486. taicpu(p).oper[1]^.reg := ThisReg;
  10487. Result := True;
  10488. end
  10489. else
  10490. begin
  10491. if TargetSize <> MaxSize then
  10492. begin
  10493. { Since the register is in use, we have to force it to
  10494. MaxSize otherwise part of it may become undefined later on }
  10495. TargetSize := MaxSize;
  10496. case TargetSize of
  10497. S_B:
  10498. TargetSubReg := R_SUBL;
  10499. S_W:
  10500. TargetSubReg := R_SUBW;
  10501. S_L:
  10502. TargetSubReg := R_SUBD;
  10503. else
  10504. InternalError(2020112351);
  10505. end;
  10506. setsubreg(ThisReg, TargetSubReg);
  10507. end;
  10508. AdjustFinalLoad;
  10509. end;
  10510. end
  10511. else
  10512. AdjustFinalLoad;
  10513. Result := AdjustInitialLoadAndSize or Result;
  10514. { Now go through every instruction we found and change the
  10515. size. If TargetSize = MaxSize, then almost no changes are
  10516. needed and Result can remain False if it hasn't been set
  10517. yet.
  10518. If RegChanged is True, then the register requires changing
  10519. and so the point about TargetSize = MaxSize doesn't apply. }
  10520. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10521. begin
  10522. for LocalIndex := 0 to InstrMax do
  10523. begin
  10524. { If p_removed is true, then the original MOV/Z was removed
  10525. and removing the AND instruction may not be safe if it
  10526. appears first }
  10527. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10528. InternalError(2020112310);
  10529. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10530. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10531. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10532. InstrList[LocalIndex].opsize := TargetSize;
  10533. end;
  10534. Result := True;
  10535. end;
  10536. end;
  10537. begin
  10538. Result := False;
  10539. p_removed := False;
  10540. hp1_removed := False;
  10541. ThisReg := taicpu(p).oper[1]^.reg;
  10542. { Check for:
  10543. movs/z ###,%ecx (or %cx or %rcx)
  10544. ...
  10545. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10546. (dealloc %ecx)
  10547. Change to:
  10548. mov ###,%cl (if ### = %cl, then remove completely)
  10549. ...
  10550. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10551. }
  10552. if (getsupreg(ThisReg) = RS_ECX) and
  10553. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10554. (hp1.typ = ait_instruction) and
  10555. (
  10556. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10557. instruction that doesn't actually contain ECX }
  10558. (cs_opt_level3 in current_settings.optimizerswitches) or
  10559. RegInInstruction(NR_ECX, hp1) or
  10560. (
  10561. { It's common for the shift/rotate's read/write register to be
  10562. initialised in between, so under -O2 and under, search ahead
  10563. one more instruction
  10564. }
  10565. GetNextInstruction(hp1, hp1) and
  10566. (hp1.typ = ait_instruction) and
  10567. RegInInstruction(NR_ECX, hp1)
  10568. )
  10569. ) and
  10570. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10571. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10572. begin
  10573. TransferUsedRegs(TmpUsedRegs);
  10574. hp2 := p;
  10575. repeat
  10576. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10577. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10578. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10579. begin
  10580. case taicpu(p).opsize of
  10581. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10582. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10583. begin
  10584. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10585. RemoveCurrentP(p);
  10586. end
  10587. else
  10588. begin
  10589. taicpu(p).opcode := A_MOV;
  10590. taicpu(p).opsize := S_B;
  10591. taicpu(p).oper[1]^.reg := NR_CL;
  10592. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10593. end;
  10594. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10595. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10596. begin
  10597. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10598. RemoveCurrentP(p);
  10599. end
  10600. else
  10601. begin
  10602. taicpu(p).opcode := A_MOV;
  10603. taicpu(p).opsize := S_W;
  10604. taicpu(p).oper[1]^.reg := NR_CX;
  10605. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10606. end;
  10607. {$ifdef x86_64}
  10608. S_LQ:
  10609. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10610. begin
  10611. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10612. RemoveCurrentP(p);
  10613. end
  10614. else
  10615. begin
  10616. taicpu(p).opcode := A_MOV;
  10617. taicpu(p).opsize := S_L;
  10618. taicpu(p).oper[1]^.reg := NR_ECX;
  10619. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10620. end;
  10621. {$endif x86_64}
  10622. else
  10623. InternalError(2021120401);
  10624. end;
  10625. Result := True;
  10626. Exit;
  10627. end;
  10628. end;
  10629. { This is anything but quick! }
  10630. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10631. Exit;
  10632. SetLength(InstrList, 0);
  10633. InstrMax := -1;
  10634. case taicpu(p).opsize of
  10635. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10636. begin
  10637. {$if defined(i386) or defined(i8086)}
  10638. { If the target size is 8-bit, make sure we can actually encode it }
  10639. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10640. Exit;
  10641. {$endif i386 or i8086}
  10642. LowerLimit := $FF;
  10643. SignedLowerLimit := $7F;
  10644. SignedLowerLimitBottom := -128;
  10645. MinSize := S_B;
  10646. if taicpu(p).opsize = S_BW then
  10647. begin
  10648. MaxSize := S_W;
  10649. UpperLimit := $FFFF;
  10650. SignedUpperLimit := $7FFF;
  10651. SignedUpperLimitBottom := -32768;
  10652. end
  10653. else
  10654. begin
  10655. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10656. MaxSize := S_L;
  10657. UpperLimit := $FFFFFFFF;
  10658. SignedUpperLimit := $7FFFFFFF;
  10659. SignedUpperLimitBottom := -2147483648;
  10660. end;
  10661. end;
  10662. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10663. begin
  10664. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10665. LowerLimit := $FFFF;
  10666. SignedLowerLimit := $7FFF;
  10667. SignedLowerLimitBottom := -32768;
  10668. UpperLimit := $FFFFFFFF;
  10669. SignedUpperLimit := $7FFFFFFF;
  10670. SignedUpperLimitBottom := -2147483648;
  10671. MinSize := S_W;
  10672. MaxSize := S_L;
  10673. end;
  10674. {$ifdef x86_64}
  10675. S_LQ:
  10676. begin
  10677. { Both the lower and upper limits are set to 32-bit. If a limit
  10678. is breached, then optimisation is impossible }
  10679. LowerLimit := $FFFFFFFF;
  10680. SignedLowerLimit := $7FFFFFFF;
  10681. SignedLowerLimitBottom := -2147483648;
  10682. UpperLimit := $FFFFFFFF;
  10683. SignedUpperLimit := $7FFFFFFF;
  10684. SignedUpperLimitBottom := -2147483648;
  10685. MinSize := S_L;
  10686. MaxSize := S_L;
  10687. end;
  10688. {$endif x86_64}
  10689. else
  10690. InternalError(2020112301);
  10691. end;
  10692. TestValMin := 0;
  10693. TestValMax := LowerLimit;
  10694. TestValSignedMax := SignedLowerLimit;
  10695. TryShiftDownLimit := LowerLimit;
  10696. TryShiftDown := S_NO;
  10697. ShiftDownOverflow := False;
  10698. RegChanged := False;
  10699. BitwiseOnly := True;
  10700. OrXorUsed := False;
  10701. UpperSignedOverflow := False;
  10702. LowerSignedOverflow := False;
  10703. UpperUnsignedOverflow := False;
  10704. LowerUnsignedOverflow := False;
  10705. hp1 := p;
  10706. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10707. (hp1.typ = ait_instruction) and
  10708. (
  10709. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10710. instruction that doesn't actually contain ThisReg }
  10711. (cs_opt_level3 in current_settings.optimizerswitches) or
  10712. { This allows this Movx optimisation to work through the SETcc instructions
  10713. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10714. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10715. skip over these SETcc instructions). }
  10716. (taicpu(hp1).opcode = A_SETcc) or
  10717. RegInInstruction(ThisReg, hp1)
  10718. ) do
  10719. begin
  10720. case taicpu(hp1).opcode of
  10721. A_INC,A_DEC:
  10722. begin
  10723. { Has to be an exact match on the register }
  10724. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10725. Break;
  10726. if taicpu(hp1).opcode = A_INC then
  10727. begin
  10728. Inc(TestValMin);
  10729. Inc(TestValMax);
  10730. Inc(TestValSignedMax);
  10731. end
  10732. else
  10733. begin
  10734. Dec(TestValMin);
  10735. Dec(TestValMax);
  10736. Dec(TestValSignedMax);
  10737. end;
  10738. end;
  10739. A_TEST, A_CMP:
  10740. begin
  10741. if (
  10742. { Too high a risk of non-linear behaviour that breaks DFA
  10743. here, unless it's cmp $0,%reg, which is equivalent to
  10744. test %reg,%reg }
  10745. OrXorUsed and
  10746. (taicpu(hp1).opcode = A_CMP) and
  10747. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10748. ) or
  10749. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10750. { Has to be an exact match on the register }
  10751. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10752. (
  10753. { Permit "test %reg,%reg" }
  10754. (taicpu(hp1).opcode = A_TEST) and
  10755. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10756. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10757. ) or
  10758. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10759. { Make sure the comparison value is not smaller than the
  10760. smallest allowed signed value for the minimum size (e.g.
  10761. -128 for 8-bit) }
  10762. not (
  10763. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10764. { Is it in the negative range? }
  10765. (
  10766. (taicpu(hp1).oper[0]^.val < 0) and
  10767. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10768. )
  10769. ) then
  10770. Break;
  10771. { Check to see if the active register is used afterwards }
  10772. TransferUsedRegs(TmpUsedRegs);
  10773. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10774. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10775. begin
  10776. { Make sure the comparison or any previous instructions
  10777. hasn't pushed the test values outside of the range of
  10778. MinSize }
  10779. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10780. begin
  10781. { Exceeded lower bound but not upper bound }
  10782. Exit;
  10783. end
  10784. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10785. begin
  10786. { Size didn't exceed lower bound }
  10787. TargetSize := MinSize;
  10788. end
  10789. else
  10790. Break;
  10791. case TargetSize of
  10792. S_B:
  10793. TargetSubReg := R_SUBL;
  10794. S_W:
  10795. TargetSubReg := R_SUBW;
  10796. S_L:
  10797. TargetSubReg := R_SUBD;
  10798. else
  10799. InternalError(2021051002);
  10800. end;
  10801. if TargetSize <> MaxSize then
  10802. begin
  10803. { Update the register to its new size }
  10804. setsubreg(ThisReg, TargetSubReg);
  10805. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10806. taicpu(hp1).oper[1]^.reg := ThisReg;
  10807. taicpu(hp1).opsize := TargetSize;
  10808. { Convert the input MOVZX to a MOV if necessary }
  10809. AdjustInitialLoadAndSize;
  10810. if (InstrMax >= 0) then
  10811. begin
  10812. for Index := 0 to InstrMax do
  10813. begin
  10814. { If p_removed is true, then the original MOV/Z was removed
  10815. and removing the AND instruction may not be safe if it
  10816. appears first }
  10817. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10818. InternalError(2020112311);
  10819. if InstrList[Index].oper[0]^.typ = top_reg then
  10820. InstrList[Index].oper[0]^.reg := ThisReg;
  10821. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10822. InstrList[Index].opsize := MinSize;
  10823. end;
  10824. end;
  10825. Result := True;
  10826. end;
  10827. Exit;
  10828. end;
  10829. end;
  10830. A_SETcc:
  10831. begin
  10832. { This allows this Movx optimisation to work through the SETcc instructions
  10833. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10834. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10835. skip over these SETcc instructions). }
  10836. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10837. { Of course, break out if the current register is used }
  10838. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10839. Break
  10840. else
  10841. { We must use Continue so the instruction doesn't get added
  10842. to InstrList }
  10843. Continue;
  10844. end;
  10845. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10846. begin
  10847. if
  10848. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10849. { Has to be an exact match on the register }
  10850. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10851. (
  10852. (
  10853. (taicpu(hp1).oper[0]^.typ = top_const) and
  10854. (
  10855. (
  10856. (taicpu(hp1).opcode = A_SHL) and
  10857. (
  10858. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10859. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10860. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10861. )
  10862. ) or (
  10863. (taicpu(hp1).opcode <> A_SHL) and
  10864. (
  10865. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10866. { Is it in the negative range? }
  10867. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10868. )
  10869. )
  10870. )
  10871. ) or (
  10872. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10873. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10874. )
  10875. ) then
  10876. Break;
  10877. { Only process OR and XOR if there are only bitwise operations,
  10878. since otherwise they can too easily fool the data flow
  10879. analysis (they can cause non-linear behaviour) }
  10880. case taicpu(hp1).opcode of
  10881. A_ADD:
  10882. begin
  10883. if OrXorUsed then
  10884. { Too high a risk of non-linear behaviour that breaks DFA here }
  10885. Break
  10886. else
  10887. BitwiseOnly := False;
  10888. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10889. begin
  10890. TestValMin := TestValMin * 2;
  10891. TestValMax := TestValMax * 2;
  10892. TestValSignedMax := TestValSignedMax * 2;
  10893. end
  10894. else
  10895. begin
  10896. WorkingValue := taicpu(hp1).oper[0]^.val;
  10897. TestValMin := TestValMin + WorkingValue;
  10898. TestValMax := TestValMax + WorkingValue;
  10899. TestValSignedMax := TestValSignedMax + WorkingValue;
  10900. end;
  10901. end;
  10902. A_SUB:
  10903. begin
  10904. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10905. begin
  10906. TestValMin := 0;
  10907. TestValMax := 0;
  10908. TestValSignedMax := 0;
  10909. end
  10910. else
  10911. begin
  10912. if OrXorUsed then
  10913. { Too high a risk of non-linear behaviour that breaks DFA here }
  10914. Break
  10915. else
  10916. BitwiseOnly := False;
  10917. WorkingValue := taicpu(hp1).oper[0]^.val;
  10918. TestValMin := TestValMin - WorkingValue;
  10919. TestValMax := TestValMax - WorkingValue;
  10920. TestValSignedMax := TestValSignedMax - WorkingValue;
  10921. end;
  10922. end;
  10923. A_AND:
  10924. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10925. begin
  10926. { we might be able to go smaller if AND appears first }
  10927. if InstrMax = -1 then
  10928. case MinSize of
  10929. S_B:
  10930. ;
  10931. S_W:
  10932. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10933. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10934. begin
  10935. TryShiftDown := S_B;
  10936. TryShiftDownLimit := $FF;
  10937. end;
  10938. S_L:
  10939. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10940. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10941. begin
  10942. TryShiftDown := S_B;
  10943. TryShiftDownLimit := $FF;
  10944. end
  10945. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10946. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10947. begin
  10948. TryShiftDown := S_W;
  10949. TryShiftDownLimit := $FFFF;
  10950. end;
  10951. else
  10952. InternalError(2020112320);
  10953. end;
  10954. WorkingValue := taicpu(hp1).oper[0]^.val;
  10955. TestValMin := TestValMin and WorkingValue;
  10956. TestValMax := TestValMax and WorkingValue;
  10957. TestValSignedMax := TestValSignedMax and WorkingValue;
  10958. end;
  10959. A_OR:
  10960. begin
  10961. if not BitwiseOnly then
  10962. Break;
  10963. OrXorUsed := True;
  10964. WorkingValue := taicpu(hp1).oper[0]^.val;
  10965. TestValMin := TestValMin or WorkingValue;
  10966. TestValMax := TestValMax or WorkingValue;
  10967. TestValSignedMax := TestValSignedMax or WorkingValue;
  10968. end;
  10969. A_XOR:
  10970. begin
  10971. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10972. begin
  10973. TestValMin := 0;
  10974. TestValMax := 0;
  10975. TestValSignedMax := 0;
  10976. end
  10977. else
  10978. begin
  10979. if not BitwiseOnly then
  10980. Break;
  10981. OrXorUsed := True;
  10982. WorkingValue := taicpu(hp1).oper[0]^.val;
  10983. TestValMin := TestValMin xor WorkingValue;
  10984. TestValMax := TestValMax xor WorkingValue;
  10985. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10986. end;
  10987. end;
  10988. A_SHL:
  10989. begin
  10990. BitwiseOnly := False;
  10991. WorkingValue := taicpu(hp1).oper[0]^.val;
  10992. TestValMin := TestValMin shl WorkingValue;
  10993. TestValMax := TestValMax shl WorkingValue;
  10994. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10995. end;
  10996. A_SHR,
  10997. { The first instruction was MOVZX, so the value won't be negative }
  10998. A_SAR:
  10999. begin
  11000. if InstrMax <> -1 then
  11001. BitwiseOnly := False
  11002. else
  11003. { we might be able to go smaller if SHR appears first }
  11004. case MinSize of
  11005. S_B:
  11006. ;
  11007. S_W:
  11008. if (taicpu(hp1).oper[0]^.val >= 8) then
  11009. begin
  11010. TryShiftDown := S_B;
  11011. TryShiftDownLimit := $FF;
  11012. TryShiftDownSignedLimit := $7F;
  11013. TryShiftDownSignedLimitLower := -128;
  11014. end;
  11015. S_L:
  11016. if (taicpu(hp1).oper[0]^.val >= 24) then
  11017. begin
  11018. TryShiftDown := S_B;
  11019. TryShiftDownLimit := $FF;
  11020. TryShiftDownSignedLimit := $7F;
  11021. TryShiftDownSignedLimitLower := -128;
  11022. end
  11023. else if (taicpu(hp1).oper[0]^.val >= 16) then
  11024. begin
  11025. TryShiftDown := S_W;
  11026. TryShiftDownLimit := $FFFF;
  11027. TryShiftDownSignedLimit := $7FFF;
  11028. TryShiftDownSignedLimitLower := -32768;
  11029. end;
  11030. else
  11031. InternalError(2020112321);
  11032. end;
  11033. WorkingValue := taicpu(hp1).oper[0]^.val;
  11034. if taicpu(hp1).opcode = A_SAR then
  11035. begin
  11036. TestValMin := SarInt64(TestValMin, WorkingValue);
  11037. TestValMax := SarInt64(TestValMax, WorkingValue);
  11038. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  11039. end
  11040. else
  11041. begin
  11042. TestValMin := TestValMin shr WorkingValue;
  11043. TestValMax := TestValMax shr WorkingValue;
  11044. TestValSignedMax := TestValSignedMax shr WorkingValue;
  11045. end;
  11046. end;
  11047. else
  11048. InternalError(2020112303);
  11049. end;
  11050. end;
  11051. (*
  11052. A_IMUL:
  11053. case taicpu(hp1).ops of
  11054. 2:
  11055. begin
  11056. if not MatchOpType(hp1, top_reg, top_reg) or
  11057. { Has to be an exact match on the register }
  11058. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  11059. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  11060. Break;
  11061. TestValMin := TestValMin * TestValMin;
  11062. TestValMax := TestValMax * TestValMax;
  11063. TestValSignedMax := TestValSignedMax * TestValMax;
  11064. end;
  11065. 3:
  11066. begin
  11067. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11068. { Has to be an exact match on the register }
  11069. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11070. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11071. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11072. { Is it in the negative range? }
  11073. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11074. Break;
  11075. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  11076. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  11077. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  11078. end;
  11079. else
  11080. Break;
  11081. end;
  11082. A_IDIV:
  11083. case taicpu(hp1).ops of
  11084. 3:
  11085. begin
  11086. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11087. { Has to be an exact match on the register }
  11088. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11089. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11090. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11091. { Is it in the negative range? }
  11092. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11093. Break;
  11094. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  11095. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  11096. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  11097. end;
  11098. else
  11099. Break;
  11100. end;
  11101. *)
  11102. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11103. begin
  11104. { If there are no instructions in between, then we might be able to make a saving }
  11105. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11106. Break;
  11107. { We have something like:
  11108. movzbw %dl,%dx
  11109. ...
  11110. movswl %dx,%edx
  11111. Change the latter to a zero-extension then enter the
  11112. A_MOVZX case branch.
  11113. }
  11114. {$ifdef x86_64}
  11115. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11116. begin
  11117. { this becomes a zero extension from 32-bit to 64-bit, but
  11118. the upper 32 bits are already zero, so just delete the
  11119. instruction }
  11120. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11121. RemoveInstruction(hp1);
  11122. Result := True;
  11123. Exit;
  11124. end
  11125. else
  11126. {$endif x86_64}
  11127. begin
  11128. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11129. taicpu(hp1).opcode := A_MOVZX;
  11130. {$ifdef x86_64}
  11131. case taicpu(hp1).opsize of
  11132. S_BQ:
  11133. begin
  11134. taicpu(hp1).opsize := S_BL;
  11135. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11136. end;
  11137. S_WQ:
  11138. begin
  11139. taicpu(hp1).opsize := S_WL;
  11140. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11141. end;
  11142. S_LQ:
  11143. begin
  11144. taicpu(hp1).opcode := A_MOV;
  11145. taicpu(hp1).opsize := S_L;
  11146. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11147. { In this instance, we need to break out because the
  11148. instruction is no longer MOVZX or MOVSXD }
  11149. Result := True;
  11150. Exit;
  11151. end;
  11152. else
  11153. ;
  11154. end;
  11155. {$endif x86_64}
  11156. Result := CompressInstructions;
  11157. Exit;
  11158. end;
  11159. end;
  11160. A_MOVZX:
  11161. begin
  11162. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11163. Break;
  11164. if (InstrMax = -1) then
  11165. begin
  11166. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11167. begin
  11168. { Optimise around i40003 }
  11169. { Check to see if the active register is used afterwards }
  11170. TransferUsedRegs(TmpUsedRegs);
  11171. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  11172. if (
  11173. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) or
  11174. not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs)
  11175. ) and
  11176. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11177. {$ifndef x86_64}
  11178. and (
  11179. (taicpu(p).oper[0]^.typ <> top_reg) or
  11180. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11181. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11182. )
  11183. {$endif not x86_64}
  11184. then
  11185. begin
  11186. if (taicpu(p).oper[0]^.typ = top_reg) then
  11187. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11188. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11189. taicpu(p).opsize := S_BL;
  11190. { Only remove if the active register is overwritten }
  11191. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11192. begin
  11193. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11194. RemoveInstruction(hp1);
  11195. end;
  11196. Result := True;
  11197. Exit;
  11198. end;
  11199. end
  11200. else
  11201. begin
  11202. { Will return false if the second parameter isn't ThisReg
  11203. (can happen on -O2 and under) }
  11204. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11205. begin
  11206. { The two MOVZX instructions are adjacent, so remove the first one }
  11207. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11208. RemoveCurrentP(p);
  11209. Result := True;
  11210. Exit;
  11211. end;
  11212. Break;
  11213. end;
  11214. end;
  11215. Result := CompressInstructions;
  11216. Exit;
  11217. end;
  11218. else
  11219. { This includes ADC, SBB and IDIV }
  11220. Break;
  11221. end;
  11222. if not CheckOverflowConditions then
  11223. Break;
  11224. { Contains highest index (so instruction count - 1) }
  11225. Inc(InstrMax);
  11226. if InstrMax > High(InstrList) then
  11227. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11228. InstrList[InstrMax] := taicpu(hp1);
  11229. end;
  11230. end;
  11231. {$pop}
  11232. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11233. var
  11234. hp1 : tai;
  11235. begin
  11236. Result:=false;
  11237. if (taicpu(p).ops >= 2) and
  11238. ((taicpu(p).oper[0]^.typ = top_const) or
  11239. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11240. (taicpu(p).oper[1]^.typ = top_reg) and
  11241. ((taicpu(p).ops = 2) or
  11242. ((taicpu(p).oper[2]^.typ = top_reg) and
  11243. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11244. GetLastInstruction(p,hp1) and
  11245. MatchInstruction(hp1,A_MOV,[]) and
  11246. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11247. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11248. begin
  11249. TransferUsedRegs(TmpUsedRegs);
  11250. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11251. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11252. { change
  11253. mov reg1,reg2
  11254. imul y,reg2 to imul y,reg1,reg2 }
  11255. begin
  11256. taicpu(p).ops := 3;
  11257. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11258. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11259. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11260. RemoveInstruction(hp1);
  11261. result:=true;
  11262. end;
  11263. end;
  11264. end;
  11265. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11266. var
  11267. ThisLabel: TAsmLabel;
  11268. begin
  11269. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11270. ThisLabel.decrefs;
  11271. taicpu(p).condition := C_None;
  11272. taicpu(p).opcode := A_RET;
  11273. taicpu(p).is_jmp := false;
  11274. taicpu(p).ops := taicpu(ret_p).ops;
  11275. case taicpu(ret_p).ops of
  11276. 0:
  11277. taicpu(p).clearop(0);
  11278. 1:
  11279. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11280. else
  11281. internalerror(2016041301);
  11282. end;
  11283. { If the original label is now dead, it might turn out that the label
  11284. immediately follows p. As a result, everything beyond it, which will
  11285. be just some final register configuration and a RET instruction, is
  11286. now dead code. [Kit] }
  11287. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11288. running RemoveDeadCodeAfterJump for each RET instruction, because
  11289. this optimisation rarely happens and most RETs appear at the end of
  11290. routines where there is nothing that can be stripped. [Kit] }
  11291. if not ThisLabel.is_used then
  11292. RemoveDeadCodeAfterJump(p);
  11293. end;
  11294. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11295. var
  11296. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11297. Unconditional, PotentialModified: Boolean;
  11298. OperPtr: POper;
  11299. NewRef: TReference;
  11300. InstrList: array of taicpu;
  11301. InstrMax, Index: Integer;
  11302. const
  11303. {$ifdef DEBUG_AOPTCPU}
  11304. SNoFlags: shortstring = ' so the flags aren''t modified';
  11305. {$else DEBUG_AOPTCPU}
  11306. SNoFlags = '';
  11307. {$endif DEBUG_AOPTCPU}
  11308. begin
  11309. Result:=false;
  11310. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11311. begin
  11312. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11313. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11314. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11315. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11316. GetNextInstruction(hp1, hp2) and
  11317. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11318. { Change from: To:
  11319. set(C) %reg j(~C) label
  11320. test %reg,%reg/cmp $0,%reg
  11321. je label
  11322. set(C) %reg j(C) label
  11323. test %reg,%reg/cmp $0,%reg
  11324. jne label
  11325. (Also do something similar with sete/setne instead of je/jne)
  11326. }
  11327. begin
  11328. { Before we do anything else, we need to check the instructions
  11329. in between SETcc and TEST to make sure they don't modify the
  11330. FLAGS register - if -O2 or under, there won't be any
  11331. instructions between SET and TEST }
  11332. TransferUsedRegs(TmpUsedRegs);
  11333. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11334. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11335. begin
  11336. next := p;
  11337. SetLength(InstrList, 0);
  11338. InstrMax := -1;
  11339. PotentialModified := False;
  11340. { Make a note of every instruction that modifies the FLAGS
  11341. register }
  11342. while GetNextInstruction(next, next) and (next <> hp1) do
  11343. begin
  11344. if next.typ <> ait_instruction then
  11345. { GetNextInstructionUsingReg should have returned False }
  11346. InternalError(2021051701);
  11347. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11348. begin
  11349. case taicpu(next).opcode of
  11350. A_SETcc,
  11351. A_CMOVcc,
  11352. A_Jcc:
  11353. begin
  11354. if PotentialModified then
  11355. { Not safe because the flags were modified earlier }
  11356. Exit
  11357. else
  11358. { Condition is the same as the initial SETcc, so this is safe
  11359. (don't add to instruction list though) }
  11360. Continue;
  11361. end;
  11362. A_ADD:
  11363. begin
  11364. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11365. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11366. (taicpu(next).oper[1]^.typ <> top_reg) or
  11367. { Must write to a register }
  11368. (taicpu(next).oper[0]^.typ = top_ref) then
  11369. { Require a constant or a register }
  11370. Exit;
  11371. PotentialModified := True;
  11372. end;
  11373. A_SUB:
  11374. begin
  11375. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11376. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11377. (taicpu(next).oper[1]^.typ <> top_reg) or
  11378. { Must write to a register }
  11379. (taicpu(next).oper[0]^.typ <> top_const) or
  11380. (taicpu(next).oper[0]^.val = $80000000) then
  11381. { Can't subtract a register with LEA - also
  11382. check that the value isn't -2^31, as this
  11383. can't be negated }
  11384. Exit;
  11385. PotentialModified := True;
  11386. end;
  11387. A_SAL,
  11388. A_SHL:
  11389. begin
  11390. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11391. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11392. (taicpu(next).oper[1]^.typ <> top_reg) or
  11393. { Must write to a register }
  11394. (taicpu(next).oper[0]^.typ <> top_const) or
  11395. (taicpu(next).oper[0]^.val < 0) or
  11396. (taicpu(next).oper[0]^.val > 3) then
  11397. Exit;
  11398. PotentialModified := True;
  11399. end;
  11400. A_IMUL:
  11401. begin
  11402. if (taicpu(next).ops <> 3) or
  11403. (taicpu(next).oper[1]^.typ <> top_reg) or
  11404. { Must write to a register }
  11405. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11406. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11407. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11408. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11409. Exit
  11410. else
  11411. PotentialModified := True;
  11412. end;
  11413. else
  11414. { Don't know how to change this, so abort }
  11415. Exit;
  11416. end;
  11417. { Contains highest index (so instruction count - 1) }
  11418. Inc(InstrMax);
  11419. if InstrMax > High(InstrList) then
  11420. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11421. InstrList[InstrMax] := taicpu(next);
  11422. end;
  11423. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11424. end;
  11425. if not Assigned(next) or (next <> hp1) then
  11426. { It should be equal to hp1 }
  11427. InternalError(2021051702);
  11428. { Cycle through each instruction and check to see if we can
  11429. change them to versions that don't modify the flags }
  11430. if (InstrMax >= 0) then
  11431. begin
  11432. for Index := 0 to InstrMax do
  11433. case InstrList[Index].opcode of
  11434. A_ADD:
  11435. begin
  11436. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11437. InstrList[Index].opcode := A_LEA;
  11438. reference_reset(NewRef, 1, []);
  11439. NewRef.base := InstrList[Index].oper[1]^.reg;
  11440. if InstrList[Index].oper[0]^.typ = top_reg then
  11441. begin
  11442. NewRef.index := InstrList[Index].oper[0]^.reg;
  11443. NewRef.scalefactor := 1;
  11444. end
  11445. else
  11446. NewRef.offset := InstrList[Index].oper[0]^.val;
  11447. InstrList[Index].loadref(0, NewRef);
  11448. end;
  11449. A_SUB:
  11450. begin
  11451. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11452. InstrList[Index].opcode := A_LEA;
  11453. reference_reset(NewRef, 1, []);
  11454. NewRef.base := InstrList[Index].oper[1]^.reg;
  11455. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11456. InstrList[Index].loadref(0, NewRef);
  11457. end;
  11458. A_SHL,
  11459. A_SAL:
  11460. begin
  11461. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11462. InstrList[Index].opcode := A_LEA;
  11463. reference_reset(NewRef, 1, []);
  11464. NewRef.index := InstrList[Index].oper[1]^.reg;
  11465. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11466. InstrList[Index].loadref(0, NewRef);
  11467. end;
  11468. A_IMUL:
  11469. begin
  11470. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11471. InstrList[Index].opcode := A_LEA;
  11472. reference_reset(NewRef, 1, []);
  11473. NewRef.index := InstrList[Index].oper[1]^.reg;
  11474. case InstrList[Index].oper[0]^.val of
  11475. 2, 4, 8:
  11476. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11477. else {3, 5 and 9}
  11478. begin
  11479. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11480. NewRef.base := InstrList[Index].oper[1]^.reg;
  11481. end;
  11482. end;
  11483. InstrList[Index].loadref(0, NewRef);
  11484. end;
  11485. else
  11486. InternalError(2021051710);
  11487. end;
  11488. end;
  11489. { Mark the FLAGS register as used across this whole block }
  11490. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11491. end;
  11492. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11493. JumpC := taicpu(hp2).condition;
  11494. Unconditional := False;
  11495. if conditions_equal(JumpC, C_E) then
  11496. SetC := inverse_cond(taicpu(p).condition)
  11497. else if conditions_equal(JumpC, C_NE) then
  11498. SetC := taicpu(p).condition
  11499. else
  11500. { We've got something weird here (and inefficent) }
  11501. begin
  11502. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11503. SetC := C_NONE;
  11504. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11505. if condition_in(C_AE, JumpC) then
  11506. Unconditional := True
  11507. else
  11508. { Not sure what to do with this jump - drop out }
  11509. Exit;
  11510. end;
  11511. RemoveInstruction(hp1);
  11512. if Unconditional then
  11513. MakeUnconditional(taicpu(hp2))
  11514. else
  11515. begin
  11516. if SetC = C_NONE then
  11517. InternalError(2018061402);
  11518. taicpu(hp2).SetCondition(SetC);
  11519. end;
  11520. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11521. TmpUsedRegs }
  11522. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11523. begin
  11524. RemoveCurrentp(p, hp2);
  11525. if taicpu(hp2).opcode = A_SETcc then
  11526. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11527. else
  11528. begin
  11529. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11530. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11531. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11532. end;
  11533. end
  11534. else
  11535. if taicpu(hp2).opcode = A_SETcc then
  11536. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11537. else
  11538. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11539. Result := True;
  11540. end
  11541. else if
  11542. { Make sure the instructions are adjacent }
  11543. (
  11544. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11545. GetNextInstruction(p, hp1)
  11546. ) and
  11547. MatchInstruction(hp1, A_MOV, [S_B]) and
  11548. { Writing to memory is allowed }
  11549. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11550. begin
  11551. {
  11552. Watch out for sequences such as:
  11553. set(c)b %regb
  11554. movb %regb,(ref)
  11555. movb $0,1(ref)
  11556. movb $0,2(ref)
  11557. movb $0,3(ref)
  11558. Much more efficient to turn it into:
  11559. movl $0,%regl
  11560. set(c)b %regb
  11561. movl %regl,(ref)
  11562. Or:
  11563. set(c)b %regb
  11564. movzbl %regb,%regl
  11565. movl %regl,(ref)
  11566. }
  11567. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11568. GetNextInstruction(hp1, hp2) and
  11569. MatchInstruction(hp2, A_MOV, [S_B]) and
  11570. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11571. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11572. begin
  11573. { Don't do anything else except set Result to True }
  11574. end
  11575. else
  11576. begin
  11577. if taicpu(p).oper[0]^.typ = top_reg then
  11578. begin
  11579. TransferUsedRegs(TmpUsedRegs);
  11580. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11581. end;
  11582. { If it's not a register, it's a memory address }
  11583. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11584. begin
  11585. { Even if the register is still in use, we can minimise the
  11586. pipeline stall by changing the MOV into another SETcc. }
  11587. taicpu(hp1).opcode := A_SETcc;
  11588. taicpu(hp1).condition := taicpu(p).condition;
  11589. if taicpu(hp1).oper[1]^.typ = top_ref then
  11590. begin
  11591. { Swapping the operand pointers like this is probably a
  11592. bit naughty, but it is far faster than using loadoper
  11593. to transfer the reference from oper[1] to oper[0] if
  11594. you take into account the extra procedure calls and
  11595. the memory allocation and deallocation required }
  11596. OperPtr := taicpu(hp1).oper[1];
  11597. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11598. taicpu(hp1).oper[0] := OperPtr;
  11599. end
  11600. else
  11601. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11602. taicpu(hp1).clearop(1);
  11603. taicpu(hp1).ops := 1;
  11604. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11605. end
  11606. else
  11607. begin
  11608. if taicpu(hp1).oper[1]^.typ = top_reg then
  11609. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11610. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11611. RemoveInstruction(hp1);
  11612. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11613. end
  11614. end;
  11615. Result := True;
  11616. end;
  11617. end;
  11618. end;
  11619. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11620. var
  11621. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11622. TargetReg: TRegister;
  11623. condition, inverted_condition: TAsmCond;
  11624. FoundMOV: Boolean;
  11625. begin
  11626. Result := False;
  11627. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11628. create the most optimial instructions possible due to limited
  11629. register availability, and there are situations where two
  11630. complementary "simple" CMOV blocks are created which, after the fact
  11631. can be merged into a "double" block. For example:
  11632. movw $257,%ax
  11633. movw $2,%r8w
  11634. xorl r9d,%r9d
  11635. testw $16,18(%rcx)
  11636. cmovew %ax,%dx
  11637. cmovew %r8w,%bx
  11638. cmovel %r9d,%r14d
  11639. movw $1283,%ax
  11640. movw $4,%r8w
  11641. movl $9,%r9d
  11642. cmovnew %ax,%dx
  11643. cmovnew %r8w,%bx
  11644. cmovnel %r9d,%r14d
  11645. The CMOVNE instructions at the end can be removed, and the
  11646. destination registers copied into the MOV instructions directly
  11647. above them, before finally being moved to before the first CMOVE
  11648. instructions, to produce:
  11649. movw $257,%ax
  11650. movw $2,%r8w
  11651. xorl r9d,%r9d
  11652. testw $16,18(%rcx)
  11653. movw $1283,%dx
  11654. movw $4,%bx
  11655. movl $9,%r14d
  11656. cmovew %ax,%dx
  11657. cmovew %r8w,%bx
  11658. cmovel %r9d,%r14d
  11659. Which can then be later optimised to:
  11660. movw $257,%ax
  11661. movw $2,%r8w
  11662. xorl r9d,%r9d
  11663. movw $1283,%dx
  11664. movw $4,%bx
  11665. movl $9,%r14d
  11666. testw $16,18(%rcx)
  11667. cmovew %ax,%dx
  11668. cmovew %r8w,%bx
  11669. cmovel %r9d,%r14d
  11670. }
  11671. TargetReg := taicpu(hp1).oper[1]^.reg;
  11672. condition := taicpu(hp1).condition;
  11673. inverted_condition := inverse_cond(condition);
  11674. pFirstMov := nil;
  11675. pLastMov := nil;
  11676. pCMOV := nil;
  11677. if (p.typ = ait_instruction) then
  11678. pCond := p
  11679. else if not GetNextInstruction(p, pCond) then
  11680. InternalError(2024012501);
  11681. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11682. { We should get the CMP or TEST instructeion }
  11683. InternalError(2024012502);
  11684. if (
  11685. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11686. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11687. ) then
  11688. begin
  11689. { We have to tread carefully here, hence why we're not using
  11690. GetNextInstructionUsingReg... we can only accept MOV and other
  11691. CMOV instructions. Anything else and we must drop out}
  11692. hp2 := hp1;
  11693. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11694. begin
  11695. if (hp2.typ <> ait_instruction) then
  11696. Exit;
  11697. case taicpu(hp2).opcode of
  11698. A_MOV:
  11699. begin
  11700. if not Assigned(pFirstMov) then
  11701. pFirstMov := hp2;
  11702. pLastMOV := hp2;
  11703. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11704. { Something different - drop out }
  11705. Exit;
  11706. { Otherwise, leave it for now }
  11707. end;
  11708. A_CMOVcc:
  11709. begin
  11710. if taicpu(hp2).condition = inverted_condition then
  11711. begin
  11712. { We found what we're looking for }
  11713. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11714. begin
  11715. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11716. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11717. begin
  11718. pCMOV := hp2;
  11719. Break;
  11720. end
  11721. else
  11722. { Unsafe reference - drop out }
  11723. Exit;
  11724. end;
  11725. end
  11726. else if taicpu(hp2).condition <> condition then
  11727. { Something weird - drop out }
  11728. Exit;
  11729. end;
  11730. else
  11731. { Invalid }
  11732. Exit;
  11733. end;
  11734. end;
  11735. if not Assigned(pCMOV) then
  11736. { No complementary CMOV found }
  11737. Exit;
  11738. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11739. begin
  11740. { Don't need to do anything special or search for a matching MOV }
  11741. Asml.Remove(pCMOV);
  11742. if RegInInstruction(TargetReg, pCond) then
  11743. { Make sure we don't overwrite the register if it's being used in the condition }
  11744. Asml.InsertAfter(pCMOV, pCond)
  11745. else
  11746. Asml.InsertBefore(pCMOV, pCond);
  11747. taicpu(pCMOV).opcode := A_MOV;
  11748. taicpu(pCMOV).condition := C_None;
  11749. { Don't need to worry about allocating new registers in these cases }
  11750. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11751. Result := True;
  11752. Exit;
  11753. end
  11754. else
  11755. begin
  11756. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11757. FoundMOV := False;
  11758. { Search for the MOV that sets the target register }
  11759. hp2 := pFirstMov;
  11760. repeat
  11761. if (taicpu(hp2).opcode = A_MOV) and
  11762. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11763. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11764. begin
  11765. { Change the destination }
  11766. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11767. if not FoundMOV then
  11768. begin
  11769. FoundMOV := True;
  11770. { Make sure the register is allocated }
  11771. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11772. end;
  11773. hp1 := tai(hp2.Previous);
  11774. Asml.Remove(hp2);
  11775. if RegInInstruction(TargetReg, pCond) then
  11776. { Make sure we don't overwrite the register if it's being used in the condition }
  11777. Asml.InsertAfter(hp2, pCond)
  11778. else
  11779. Asml.InsertBefore(hp2, pCond);
  11780. if (hp2 = pLastMov) then
  11781. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11782. Break;
  11783. hp2 := hp1;
  11784. end;
  11785. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11786. if FoundMOV then
  11787. { Delete the CMOV }
  11788. RemoveInstruction(pCMOV)
  11789. else
  11790. begin
  11791. { If no MOV was found, we have to actually move and transmute the CMOV }
  11792. Asml.Remove(pCMOV);
  11793. if RegInInstruction(TargetReg, pCond) then
  11794. { Make sure we don't overwrite the register if it's being used in the condition }
  11795. Asml.InsertAfter(pCMOV, pCond)
  11796. else
  11797. Asml.InsertBefore(pCMOV, pCond);
  11798. taicpu(pCMOV).opcode := A_MOV;
  11799. taicpu(pCMOV).condition := C_None;
  11800. end;
  11801. Result := True;
  11802. Exit;
  11803. end;
  11804. end;
  11805. end;
  11806. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11807. var
  11808. hp1, hp2, pCond: tai;
  11809. begin
  11810. Result := False;
  11811. { Search ahead for CMOV instructions }
  11812. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11813. begin
  11814. hp1 := p;
  11815. hp2 := p;
  11816. pCond := nil; { To prevent compiler warnings }
  11817. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11818. DEFAULTFLAGS }
  11819. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11820. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11821. pCond := p;
  11822. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11823. begin
  11824. if (hp1.typ <> ait_instruction) then
  11825. { Break out on markers and labels etc. }
  11826. Break;
  11827. case taicpu(hp1).opcode of
  11828. A_MOV:
  11829. { Ignore regular MOVs unless they are obviously not related
  11830. to a CMOV block }
  11831. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11832. Break;
  11833. A_CMOVcc:
  11834. if TryCmpCMovOpts(pCond, hp1) then
  11835. begin
  11836. hp1 := hp2;
  11837. { p itself isn't changed, and we're still inside a
  11838. while loop to catch subsequent CMOVs, so just flag
  11839. a new iteration }
  11840. Include(OptsToCheck, aoc_ForceNewIteration);
  11841. Continue;
  11842. end;
  11843. else
  11844. { Drop out if we find anything else }
  11845. Break;
  11846. end;
  11847. hp2 := hp1;
  11848. end;
  11849. end;
  11850. end;
  11851. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11852. var
  11853. hp1, hp2, pCond: tai;
  11854. SourceReg, TargetReg: TRegister;
  11855. begin
  11856. Result := False;
  11857. { In some situations, we end up with an inefficient arrangement of
  11858. instructions in the form of:
  11859. or %reg1,%reg2
  11860. (%reg1 deallocated)
  11861. test %reg2,%reg2
  11862. mov x,%reg2
  11863. we may be able to swap and rearrange the registers to produce:
  11864. or %reg2,%reg1
  11865. mov x,%reg2
  11866. test %reg1,%reg1
  11867. (%reg1 deallocated)
  11868. }
  11869. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11870. (taicpu(p).oper[1]^.typ = top_reg) and
  11871. (
  11872. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11873. MatchOperand(taicpu(p).oper[0]^, -1)
  11874. ) and
  11875. GetNextInstruction(p, hp1) and
  11876. MatchInstruction(hp1, A_MOV, []) and
  11877. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11878. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11879. begin
  11880. TargetReg := taicpu(p).oper[1]^.reg;
  11881. { Now look backwards to find a simple commutative operation: ADD,
  11882. IMUL (2-register version), OR, AND or XOR - whose destination
  11883. register is the same as TEST }
  11884. hp2 := p;
  11885. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11886. if RegInInstruction(TargetReg, hp2) then
  11887. begin
  11888. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11889. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11890. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11891. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11892. begin
  11893. SourceReg := taicpu(hp2).oper[0]^.reg;
  11894. if
  11895. { Make sure the MOV doesn't use the other register }
  11896. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11897. { And make sure the source register is not used afterwards }
  11898. not RegInUsedRegs(SourceReg, UsedRegs) then
  11899. begin
  11900. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11901. taicpu(hp2).oper[0]^.reg := TargetReg;
  11902. taicpu(hp2).oper[1]^.reg := SourceReg;
  11903. if taicpu(p).oper[0]^.typ = top_reg then
  11904. taicpu(p).oper[0]^.reg := SourceReg;
  11905. taicpu(p).oper[1]^.reg := SourceReg;
  11906. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11907. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11908. Include(OptsToCheck, aoc_ForceNewIteration);
  11909. { We can still check the following optimisations since
  11910. the instruction is still a TEST }
  11911. end;
  11912. end;
  11913. Break;
  11914. end;
  11915. end;
  11916. { Search ahead3 for CMOV instructions }
  11917. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11918. begin
  11919. hp1 := p;
  11920. hp2 := p;
  11921. pCond := nil; { To prevent compiler warnings }
  11922. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11923. DEFAULTFLAGS }
  11924. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11925. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11926. pCond := p;
  11927. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11928. begin
  11929. if (hp1.typ <> ait_instruction) then
  11930. { Break out on markers and labels etc. }
  11931. Break;
  11932. case taicpu(hp1).opcode of
  11933. A_MOV:
  11934. { Ignore regular MOVs unless they are obviously not related
  11935. to a CMOV block }
  11936. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11937. Break;
  11938. A_CMOVcc:
  11939. if TryCmpCMovOpts(pCond, hp1) then
  11940. begin
  11941. hp1 := hp2;
  11942. { p itself isn't changed, and we're still inside a
  11943. while loop to catch subsequent CMOVs, so just flag
  11944. a new iteration }
  11945. Include(OptsToCheck, aoc_ForceNewIteration);
  11946. Continue;
  11947. end;
  11948. else
  11949. { Drop out if we find anything else }
  11950. Break;
  11951. end;
  11952. hp2 := hp1;
  11953. end;
  11954. end;
  11955. end;
  11956. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11957. var
  11958. hp1: tai;
  11959. Count: Integer;
  11960. OrigLabel: TAsmLabel;
  11961. begin
  11962. result := False;
  11963. { Sometimes, the optimisations below can permit this }
  11964. RemoveDeadCodeAfterJump(p);
  11965. if (taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full) and (taicpu(p).oper[0]^.ref^.base=NR_NO) and
  11966. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11967. begin
  11968. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11969. { Also a side-effect of optimisations }
  11970. if CollapseZeroDistJump(p, OrigLabel) then
  11971. begin
  11972. Result := True;
  11973. Exit;
  11974. end;
  11975. hp1 := GetLabelWithSym(OrigLabel);
  11976. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11977. begin
  11978. if taicpu(hp1).opcode = A_RET then
  11979. begin
  11980. {
  11981. change
  11982. jmp .L1
  11983. ...
  11984. .L1:
  11985. ret
  11986. into
  11987. ret
  11988. }
  11989. begin
  11990. ConvertJumpToRET(p, hp1);
  11991. result:=true;
  11992. end;
  11993. end
  11994. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11995. not (cs_opt_size in current_settings.optimizerswitches) and
  11996. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11997. begin
  11998. Result := True;
  11999. Exit;
  12000. end;
  12001. end;
  12002. end;
  12003. end;
  12004. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  12005. begin
  12006. Result := assigned(p) and
  12007. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  12008. (taicpu(p).oper[1]^.typ = top_reg) and
  12009. (
  12010. (taicpu(p).oper[0]^.typ = top_reg) or
  12011. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  12012. it is not expected that this can cause a seg. violation }
  12013. (
  12014. (taicpu(p).oper[0]^.typ = top_ref) and
  12015. { TODO: Can we detect which references become constants at this
  12016. stage so we don't have to do a blanket ban? }
  12017. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  12018. (
  12019. IsRefSafe(taicpu(p).oper[0]^.ref) or
  12020. (
  12021. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  12022. not RefModified and
  12023. { If the reference also appears in the condition, then we know it's safe, otherwise
  12024. any kind of access violation would have occurred already }
  12025. Assigned(cond_p) and
  12026. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12027. (cond_p.typ = ait_instruction) and
  12028. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  12029. { Just consider 2-operand comparison instructions for now to be safe }
  12030. (taicpu(cond_p).ops = 2) and
  12031. (
  12032. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  12033. (
  12034. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  12035. { Don't risk identical registers but different offsets, as we may have constructs
  12036. such as buffer streams with things like length fields that indicate whether
  12037. any more data follows. And there are probably some contrived examples where
  12038. writing to offsets behind the one being read also lead to access violations }
  12039. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  12040. (
  12041. { Check that we're not modifying a register that appears in the reference }
  12042. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  12043. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  12044. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  12045. )
  12046. )
  12047. )
  12048. )
  12049. )
  12050. )
  12051. );
  12052. end;
  12053. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  12054. begin
  12055. { Update integer registers, ignoring deallocations }
  12056. repeat
  12057. while assigned(p) and
  12058. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  12059. (p.typ = ait_label) or
  12060. ((p.typ = ait_marker) and
  12061. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  12062. p := tai(p.next);
  12063. while assigned(p) and
  12064. (p.typ=ait_RegAlloc) Do
  12065. begin
  12066. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  12067. begin
  12068. case tai_regalloc(p).ratype of
  12069. ra_alloc :
  12070. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  12071. else
  12072. ;
  12073. end;
  12074. end;
  12075. p := tai(p.next);
  12076. end;
  12077. until not(assigned(p)) or
  12078. (not(p.typ in SkipInstr) and
  12079. not((p.typ = ait_label) and
  12080. labelCanBeSkipped(tai_label(p))));
  12081. end;
  12082. {$ifndef 8086}
  12083. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  12084. begin
  12085. Result := False;
  12086. EndJump := nil;
  12087. BlockStop := nil;
  12088. while (BlockStart <> fOptimizer.BlockEnd) and
  12089. { stop on labels }
  12090. (BlockStart.typ <> ait_label) do
  12091. begin
  12092. { Keep track of all integer registers that are used }
  12093. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  12094. if BlockStart.typ = ait_instruction then
  12095. begin
  12096. if (taicpu(BlockStart).opcode = A_JMP) then
  12097. begin
  12098. if not IsJumpToLabel(taicpu(BlockStart)) or
  12099. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  12100. Exit;
  12101. EndJump := BlockStart;
  12102. Break;
  12103. end
  12104. { Check to see if we have a valid MOV instruction instead }
  12105. else if (taicpu(BlockStart).opcode <> A_MOV) or
  12106. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  12107. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12108. begin
  12109. Exit;
  12110. end
  12111. else
  12112. { This will be a valid MOV }
  12113. fAllocationRange := BlockStart;
  12114. end;
  12115. OneBeforeBlock := BlockStart;
  12116. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12117. end;
  12118. if (BlockStart = fOptimizer.BlockEnd) then
  12119. Exit;
  12120. BlockStop := BlockStart;
  12121. Result := True;
  12122. end;
  12123. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12124. var
  12125. hp1: tai;
  12126. RefModified: Boolean;
  12127. begin
  12128. Result := 0;
  12129. hp1 := BlockStart;
  12130. RefModified := False; { As long as the condition is inverted, this can be reset }
  12131. while assigned(hp1) and
  12132. (hp1 <> BlockStop) do
  12133. begin
  12134. case hp1.typ of
  12135. ait_instruction:
  12136. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12137. begin
  12138. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12139. begin
  12140. Inc(Result);
  12141. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12142. Assigned(fCondition) and
  12143. { Will have 2 operands }
  12144. (
  12145. (
  12146. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12147. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12148. ) or
  12149. (
  12150. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12151. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12152. )
  12153. ) then
  12154. { It is no longer safe to use the reference in the condition.
  12155. this prevents problems such as:
  12156. mov (%reg),%reg
  12157. mov (%reg),...
  12158. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12159. (fixes #40165)
  12160. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12161. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12162. }
  12163. RefModified := True;
  12164. end
  12165. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12166. { CMOV with constants grows the code size }
  12167. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12168. begin
  12169. { Register was reserved by TryCMOVConst and
  12170. stored on ConstRegs }
  12171. end
  12172. else
  12173. begin
  12174. Result := -1;
  12175. Exit;
  12176. end;
  12177. end
  12178. else
  12179. begin
  12180. Result := -1;
  12181. Exit;
  12182. end;
  12183. else
  12184. { Most likely an align };
  12185. end;
  12186. fOptimizer.GetNextInstruction(hp1, hp1);
  12187. end;
  12188. end;
  12189. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12190. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12191. (this is done as a separate stage because the double types are extensions of the branching type,
  12192. but we can't discount the conditional jump until the last step) }
  12193. procedure EvaluateBranchingType;
  12194. begin
  12195. Inc(CMOVScore);
  12196. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12197. { Too many instructions to be worthwhile }
  12198. fState := tsInvalid;
  12199. end;
  12200. var
  12201. hp1: tai;
  12202. Count: Integer;
  12203. begin
  12204. { Table of valid CMOV block types
  12205. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12206. ---------- --------- --------- --------- --------- ---------
  12207. tsSimple X Yes X X X
  12208. tsDetour = 1st X X X X
  12209. tsBranching <> Mid Yes X X X
  12210. tsDouble End-label Yes * Yes X Yes
  12211. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12212. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12213. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12214. * Only one reference allowed
  12215. }
  12216. hp1 := nil; { To prevent compiler warnings }
  12217. Optimizer.CopyUsedRegs(RegisterTracking);
  12218. fOptimizer := Optimizer;
  12219. fLabel := AFirstLabel;
  12220. CMOVScore := 0;
  12221. ConstCount := 0;
  12222. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12223. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12224. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12225. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12226. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12227. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12228. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12229. fInsertionPoint := p_initialjump;
  12230. fCondition := nil;
  12231. fInitialJump := p_initialjump;
  12232. fFirstMovBlock := p_initialmov;
  12233. fFirstMovBlockStop := nil;
  12234. fSecondJump := nil;
  12235. fSecondMovBlock := nil;
  12236. fSecondMovBlockStop := nil;
  12237. fMidLabel := nil;
  12238. fSecondJump := nil;
  12239. fSecondMovBlock := nil;
  12240. fEndLabel := nil;
  12241. fAllocationRange := nil;
  12242. { Assume it all goes horribly wrong! }
  12243. fState := tsInvalid;
  12244. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12245. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12246. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  12247. begin
  12248. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12249. for Count := 0 to 1 do
  12250. with taicpu(fCondition).oper[Count]^ do
  12251. case typ of
  12252. top_reg:
  12253. if getregtype(reg) = R_INTREGISTER then
  12254. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12255. top_ref:
  12256. begin
  12257. if
  12258. {$ifdef x86_64}
  12259. (ref^.base <> NR_RIP) and
  12260. {$endif x86_64}
  12261. (ref^.base <> NR_NO) then
  12262. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12263. if (ref^.index <> NR_NO) then
  12264. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12265. end
  12266. else
  12267. ;
  12268. end;
  12269. { When inserting instructions before hp_prev, try to insert them
  12270. before the allocation of the FLAGS register }
  12271. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12272. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12273. { If not found, set it equal to the condition so it's something sensible }
  12274. fInsertionPoint := fCondition;
  12275. { When dealing with a comparison against zero, take note of the
  12276. instruction before it to see if we can move instructions further
  12277. back in order to benefit PostPeepholeOptTestOr.
  12278. }
  12279. if (
  12280. (
  12281. (taicpu(fCondition).opcode = A_CMP) and
  12282. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12283. ) or
  12284. (
  12285. (taicpu(fCondition).opcode = A_TEST) and
  12286. (
  12287. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12288. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12289. )
  12290. )
  12291. ) and
  12292. Optimizer.GetLastInstruction(fCondition, hp1) then
  12293. begin
  12294. { These instructions set the zero flag if the result is zero }
  12295. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12296. begin
  12297. fInsertionPoint := hp1;
  12298. { Also mark all the registers in this previous instruction
  12299. as 'in use', even if they've just been deallocated }
  12300. for Count := 0 to 1 do
  12301. with taicpu(hp1).oper[Count]^ do
  12302. case typ of
  12303. top_reg:
  12304. if getregtype(reg) = R_INTREGISTER then
  12305. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12306. top_ref:
  12307. begin
  12308. if
  12309. {$ifdef x86_64}
  12310. (ref^.base <> NR_RIP) and
  12311. {$endif x86_64}
  12312. (ref^.base <> NR_NO) then
  12313. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12314. if (ref^.index <> NR_NO) then
  12315. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12316. end
  12317. else
  12318. ;
  12319. end;
  12320. end;
  12321. end;
  12322. end
  12323. else
  12324. fCondition := nil;
  12325. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12326. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12327. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12328. { If not found, set it equal to p so it's something sensible }
  12329. fInsertionPoint := hp1;
  12330. hp1 := p_initialmov;
  12331. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12332. Exit;
  12333. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12334. if (hp1.typ <> ait_label) then { should be on a jump }
  12335. begin
  12336. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12337. { Need a label afterwards }
  12338. Exit;
  12339. end
  12340. else
  12341. fMidLabel := hp1;
  12342. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12343. { Not the correct label }
  12344. fMidLabel := nil;
  12345. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12346. { If there's neither a 2nd jump nor correct label, then it's invalid
  12347. (see above table) }
  12348. Exit;
  12349. { Analyse the first block of MOVs more closely }
  12350. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12351. if Assigned(fSecondJump) then
  12352. begin
  12353. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12354. begin
  12355. fState := tsDetour
  12356. end
  12357. else
  12358. begin
  12359. { Need the correct mid-label for this one }
  12360. if not Assigned(fMidLabel) then
  12361. Exit;
  12362. fState := tsBranching;
  12363. end;
  12364. end
  12365. else
  12366. { No jump. but mid-label is present }
  12367. fState := tsSimple;
  12368. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12369. begin
  12370. { Invalid or too many instructions to be worthwhile }
  12371. fState := tsInvalid;
  12372. Exit;
  12373. end;
  12374. { check further for
  12375. jCC xxx
  12376. <several movs 1>
  12377. jmp yyy
  12378. xxx:
  12379. <several movs 2>
  12380. yyy:
  12381. etc.
  12382. }
  12383. if (fState = tsBranching) and
  12384. { Estimate for required savings for extra jump }
  12385. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12386. { Only one reference is allowed for double blocks }
  12387. (AFirstLabel.getrefs = 1) then
  12388. begin
  12389. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12390. fSecondMovBlock := hp1;
  12391. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12392. begin
  12393. EvaluateBranchingType;
  12394. Exit;
  12395. end;
  12396. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12397. if (hp1.typ <> ait_label) then { should be on a jump }
  12398. begin
  12399. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12400. begin
  12401. { Need a label afterwards }
  12402. EvaluateBranchingType;
  12403. Exit;
  12404. end;
  12405. end
  12406. else
  12407. fEndLabel := hp1;
  12408. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12409. { Second jump doesn't go to the end }
  12410. fEndLabel := nil;
  12411. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12412. begin
  12413. { If there's neither a 3rd jump nor correct end label, then it's
  12414. not a invalid double block, but is a valid single branching
  12415. block (see above table) }
  12416. EvaluateBranchingType;
  12417. Exit;
  12418. end;
  12419. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12420. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12421. { Invalid or too many instructions to be worthwhile }
  12422. Exit;
  12423. Inc(CMOVScore, Count);
  12424. if Assigned(fThirdJump) then
  12425. begin
  12426. if not Assigned(fSecondJump) then
  12427. fState := tsDoubleSecondBranching
  12428. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12429. fState := tsDoubleBranchSame
  12430. else
  12431. fState := tsDoubleBranchDifferent;
  12432. end
  12433. else
  12434. fState := tsDouble;
  12435. end;
  12436. if fState = tsBranching then
  12437. EvaluateBranchingType;
  12438. end;
  12439. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12440. new register to store the constant }
  12441. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12442. var
  12443. RegSize: TSubRegister;
  12444. CurrentVal: TCGInt;
  12445. ANewReg: TRegister;
  12446. X: ShortInt;
  12447. begin
  12448. Result := False;
  12449. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12450. Exit;
  12451. if ConstCount >= MAX_CMOV_REGISTERS then
  12452. { Arrays are full }
  12453. Exit;
  12454. { Remember that CMOV can't encode 8-bit registers }
  12455. case taicpu(p).opsize of
  12456. S_W:
  12457. RegSize := R_SUBW;
  12458. S_L:
  12459. RegSize := R_SUBD;
  12460. {$ifdef x86_64}
  12461. S_Q:
  12462. RegSize := R_SUBQ;
  12463. {$endif x86_64}
  12464. else
  12465. InternalError(2021100401);
  12466. end;
  12467. { See if the value has already been reserved for another CMOV instruction }
  12468. CurrentVal := taicpu(p).oper[0]^.val;
  12469. for X := 0 to ConstCount - 1 do
  12470. if ConstVals[X] = CurrentVal then
  12471. begin
  12472. ConstRegs[ConstCount] := ConstRegs[X];
  12473. ConstSizes[ConstCount] := RegSize;
  12474. ConstVals[ConstCount] := CurrentVal;
  12475. Inc(ConstCount);
  12476. Inc(Count);
  12477. Result := True;
  12478. Exit;
  12479. end;
  12480. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12481. if ANewReg = NR_NO then
  12482. { No free registers }
  12483. Exit;
  12484. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12485. up vying for the same register }
  12486. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12487. ConstRegs[ConstCount] := ANewReg;
  12488. ConstSizes[ConstCount] := RegSize;
  12489. ConstVals[ConstCount] := CurrentVal;
  12490. Inc(ConstCount);
  12491. Inc(Count);
  12492. Result := True;
  12493. end;
  12494. destructor TCMOVTracking.Done;
  12495. begin
  12496. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12497. end;
  12498. procedure TCMOVTracking.Process(out new_p: tai);
  12499. var
  12500. Count, Writes: LongInt;
  12501. RegMatch: Boolean;
  12502. hp1, hp_new: tai;
  12503. inverted_condition, condition: TAsmCond;
  12504. begin
  12505. if (fState in [tsInvalid, tsProcessed]) then
  12506. InternalError(2023110701);
  12507. { Repurpose RegisterTracking to mark registers that we've defined }
  12508. RegisterTracking[R_INTREGISTER].Clear;
  12509. Count := 0;
  12510. Writes := 0;
  12511. condition := taicpu(fInitialJump).condition;
  12512. inverted_condition := inverse_cond(condition);
  12513. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12514. doesn't get CMOVs in this case }
  12515. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12516. begin
  12517. { Include the jump in the flag tracking }
  12518. if Assigned(fThirdJump) then
  12519. begin
  12520. if (fState = tsDoubleBranchSame) then
  12521. begin
  12522. { Will be an unconditional jump, so track to the instruction before it }
  12523. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12524. InternalError(2023110710);
  12525. end
  12526. else
  12527. hp1 := fThirdJump;
  12528. end
  12529. else
  12530. hp1 := fSecondMovBlockStop;
  12531. end
  12532. else
  12533. begin
  12534. { Include a conditional jump in the flag tracking }
  12535. if Assigned(fSecondJump) then
  12536. begin
  12537. if (fState = tsDetour) then
  12538. begin
  12539. { Will be an unconditional jump, so track to the instruction before it }
  12540. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12541. InternalError(2023110711);
  12542. end
  12543. else
  12544. hp1 := fSecondJump;
  12545. end
  12546. else
  12547. hp1 := fFirstMovBlockStop;
  12548. end;
  12549. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12550. { Process the second set of MOVs first, because if a destination
  12551. register is shared between the first and second MOV sets, it is more
  12552. efficient to turn the first one into a MOV instruction and place it
  12553. before the CMP if possible, but we won't know which registers are
  12554. shared until we've processed at least one list, so we might as well
  12555. make it the second one since that won't be modified again. }
  12556. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12557. begin
  12558. hp1 := fSecondMovBlock;
  12559. repeat
  12560. if not Assigned(hp1) then
  12561. InternalError(2018062902);
  12562. if (hp1.typ = ait_instruction) then
  12563. begin
  12564. { Extra safeguard }
  12565. if (taicpu(hp1).opcode <> A_MOV) then
  12566. InternalError(2018062903);
  12567. { Note: tsDoubleBranchDifferent is essentially identical to
  12568. tsBranching and the 2nd block is best left largely
  12569. untouched, but we need to evaluate which registers the MOVs
  12570. write to in order to track what would be complementary CMOV
  12571. pairs that can be further optimised. [Kit] }
  12572. if fState <> tsDoubleBranchDifferent then
  12573. begin
  12574. if taicpu(hp1).oper[0]^.typ = top_const then
  12575. begin
  12576. RegMatch := False;
  12577. for Count := 0 to ConstCount - 1 do
  12578. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12579. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12580. begin
  12581. RegMatch := True;
  12582. { If it's in RegisterTracking, then this register
  12583. is being used more than once and hence has
  12584. already had its value defined (it gets added to
  12585. UsedRegs through AllocRegBetween below) }
  12586. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12587. begin
  12588. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12589. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12590. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12591. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12592. ConstMovs[Count] := hp_new;
  12593. end
  12594. else
  12595. { We just need an instruction between hp_prev and hp1
  12596. where we know the register is marked as in use }
  12597. hp_new := fSecondMovBlock;
  12598. { Keep track of largest write for this register so it can be optimised later }
  12599. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12600. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12601. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12602. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12603. Break;
  12604. end;
  12605. if not RegMatch then
  12606. InternalError(2021100411);
  12607. end;
  12608. taicpu(hp1).opcode := A_CMOVcc;
  12609. taicpu(hp1).condition := condition;
  12610. end;
  12611. { Store these writes to search for duplicates later on }
  12612. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12613. Inc(Writes);
  12614. end;
  12615. fOptimizer.GetNextInstruction(hp1, hp1);
  12616. until (hp1 = fSecondMovBlockStop);
  12617. end;
  12618. { Now do the first set of MOVs }
  12619. hp1 := fFirstMovBlock;
  12620. repeat
  12621. if not Assigned(hp1) then
  12622. InternalError(2018062904);
  12623. if (hp1.typ = ait_instruction) then
  12624. begin
  12625. RegMatch := False;
  12626. { Extra safeguard }
  12627. if (taicpu(hp1).opcode <> A_MOV) then
  12628. InternalError(2018062905);
  12629. { Search through the RegWrites list to see if there are any
  12630. opposing CMOV pairs that write to the same register }
  12631. for Count := 0 to Writes - 1 do
  12632. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12633. begin
  12634. { We have a match. Keep this as a MOV }
  12635. { Move ahead in preparation }
  12636. fOptimizer.GetNextInstruction(hp1, hp1);
  12637. RegMatch := True;
  12638. Break;
  12639. end;
  12640. if RegMatch then
  12641. Continue;
  12642. if taicpu(hp1).oper[0]^.typ = top_const then
  12643. begin
  12644. for Count := 0 to ConstCount - 1 do
  12645. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12646. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12647. begin
  12648. RegMatch := True;
  12649. { If it's in RegisterTracking, then this register is
  12650. being used more than once and hence has already had
  12651. its value defined (it gets added to UsedRegs through
  12652. AllocRegBetween below) }
  12653. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12654. begin
  12655. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12656. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12657. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12658. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12659. ConstMovs[Count] := hp_new;
  12660. end
  12661. else
  12662. { We just need an instruction between hp_prev and hp1
  12663. where we know the register is marked as in use }
  12664. hp_new := fFirstMovBlock;
  12665. { Keep track of largest write for this register so it can be optimised later }
  12666. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12667. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12668. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12669. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12670. Break;
  12671. end;
  12672. if not RegMatch then
  12673. InternalError(2021100412);
  12674. end;
  12675. taicpu(hp1).opcode := A_CMOVcc;
  12676. taicpu(hp1).condition := inverted_condition;
  12677. if (fState = tsDoubleBranchDifferent) then
  12678. begin
  12679. { Store these writes to search for duplicates later on }
  12680. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12681. Inc(Writes);
  12682. end;
  12683. end;
  12684. fOptimizer.GetNextInstruction(hp1, hp1);
  12685. until (hp1 = fFirstMovBlockStop);
  12686. { Update initialisation MOVs to the smallest possible size }
  12687. for Count := 0 to ConstCount - 1 do
  12688. if Assigned(ConstMovs[Count]) then
  12689. begin
  12690. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12691. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12692. end;
  12693. case fState of
  12694. tsSimple:
  12695. begin
  12696. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12697. { No branch to delete }
  12698. end;
  12699. tsDetour:
  12700. begin
  12701. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12702. { Preserve jump }
  12703. end;
  12704. tsBranching, tsDoubleBranchDifferent:
  12705. begin
  12706. if (fState = tsBranching) then
  12707. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12708. else
  12709. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12710. taicpu(fSecondJump).opcode := A_JCC;
  12711. taicpu(fSecondJump).condition := inverted_condition;
  12712. end;
  12713. tsDouble, tsDoubleBranchSame:
  12714. begin
  12715. if (fState = tsDouble) then
  12716. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12717. else
  12718. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12719. { Delete second jump }
  12720. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12721. fOptimizer.RemoveInstruction(fSecondJump);
  12722. end;
  12723. tsDoubleSecondBranching:
  12724. begin
  12725. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12726. { Delete second jump, preserve third jump as conditional }
  12727. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12728. fOptimizer.RemoveInstruction(fSecondJump);
  12729. taicpu(fThirdJump).opcode := A_JCC;
  12730. taicpu(fThirdJump).condition := condition;
  12731. end;
  12732. else
  12733. InternalError(2023110720);
  12734. end;
  12735. { Now we can safely decrement the reference count }
  12736. tasmlabel(fLabel).decrefs;
  12737. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12738. { Remove the original jump }
  12739. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12740. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12741. fState := tsProcessed;
  12742. end;
  12743. {$endif 8086}
  12744. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12745. var
  12746. hp1,hp2: tai;
  12747. carryadd_opcode : TAsmOp;
  12748. symbol: TAsmSymbol;
  12749. increg, tmpreg: TRegister;
  12750. {$ifndef i8086}
  12751. CMOVTracking: PCMOVTracking;
  12752. hp3,hp4,hp5: tai;
  12753. {$endif i8086}
  12754. TempBool: Boolean;
  12755. begin
  12756. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12757. DoJumpOptimizations(p, TempBool) then
  12758. Exit(True);
  12759. result:=false;
  12760. if GetNextInstruction(p,hp1) then
  12761. begin
  12762. if (hp1.typ=ait_label) then
  12763. begin
  12764. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12765. Exit;
  12766. end
  12767. else if (hp1.typ<>ait_instruction) then
  12768. Exit;
  12769. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12770. if (
  12771. (
  12772. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12773. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12774. (Taicpu(hp1).oper[0]^.val=1)
  12775. ) or
  12776. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12777. ) and
  12778. GetNextInstruction(hp1,hp2) and
  12779. FindLabel(TAsmLabel(symbol), hp2) then
  12780. { jb @@1 cmc
  12781. inc/dec operand --> adc/sbb operand,0
  12782. @@1:
  12783. ... and ...
  12784. jnb @@1
  12785. inc/dec operand --> adc/sbb operand,0
  12786. @@1: }
  12787. begin
  12788. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12789. begin
  12790. case taicpu(hp1).opcode of
  12791. A_INC,
  12792. A_ADD:
  12793. carryadd_opcode:=A_ADC;
  12794. A_DEC,
  12795. A_SUB:
  12796. carryadd_opcode:=A_SBB;
  12797. else
  12798. InternalError(2021011001);
  12799. end;
  12800. Taicpu(p).clearop(0);
  12801. Taicpu(p).ops:=0;
  12802. Taicpu(p).is_jmp:=false;
  12803. Taicpu(p).opcode:=A_CMC;
  12804. Taicpu(p).condition:=C_NONE;
  12805. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12806. Taicpu(hp1).ops:=2;
  12807. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12808. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12809. else
  12810. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12811. Taicpu(hp1).loadconst(0,0);
  12812. Taicpu(hp1).opcode:=carryadd_opcode;
  12813. result:=true;
  12814. exit;
  12815. end
  12816. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12817. begin
  12818. case taicpu(hp1).opcode of
  12819. A_INC,
  12820. A_ADD:
  12821. carryadd_opcode:=A_ADC;
  12822. A_DEC,
  12823. A_SUB:
  12824. carryadd_opcode:=A_SBB;
  12825. else
  12826. InternalError(2021011002);
  12827. end;
  12828. Taicpu(hp1).ops:=2;
  12829. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12830. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12831. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12832. else
  12833. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12834. Taicpu(hp1).loadconst(0,0);
  12835. Taicpu(hp1).opcode:=carryadd_opcode;
  12836. RemoveCurrentP(p, hp1);
  12837. result:=true;
  12838. exit;
  12839. end
  12840. {
  12841. jcc @@1 setcc tmpreg
  12842. inc/dec/add/sub operand -> (movzx tmpreg)
  12843. @@1: add/sub tmpreg,operand
  12844. While this increases code size slightly, it makes the code much faster if the
  12845. jump is unpredictable
  12846. }
  12847. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12848. begin
  12849. { search for an available register which is volatile }
  12850. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12851. if increg <> NR_NO then
  12852. begin
  12853. { We don't need to check if tmpreg is in hp1 or not, because
  12854. it will be marked as in use at p (if not, this is
  12855. indictive of a compiler bug). }
  12856. TAsmLabel(symbol).decrefs;
  12857. Taicpu(p).clearop(0);
  12858. Taicpu(p).ops:=1;
  12859. Taicpu(p).is_jmp:=false;
  12860. Taicpu(p).opcode:=A_SETcc;
  12861. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12862. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12863. Taicpu(p).loadreg(0,increg);
  12864. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12865. begin
  12866. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12867. R_SUBW:
  12868. begin
  12869. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12870. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12871. end;
  12872. R_SUBD:
  12873. begin
  12874. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12875. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12876. end;
  12877. {$ifdef x86_64}
  12878. R_SUBQ:
  12879. begin
  12880. { MOVZX doesn't have a 64-bit variant, because
  12881. the 32-bit version implicitly zeroes the
  12882. upper 32-bits of the destination register }
  12883. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12884. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12885. setsubreg(tmpreg, R_SUBQ);
  12886. end;
  12887. {$endif x86_64}
  12888. else
  12889. Internalerror(2020030601);
  12890. end;
  12891. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12892. asml.InsertAfter(hp2,p);
  12893. end
  12894. else
  12895. tmpreg := increg;
  12896. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12897. begin
  12898. Taicpu(hp1).ops:=2;
  12899. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12900. end;
  12901. Taicpu(hp1).loadreg(0,tmpreg);
  12902. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12903. Result := True;
  12904. { p is no longer a Jcc instruction, so exit }
  12905. Exit;
  12906. end;
  12907. end;
  12908. end;
  12909. { Detect the following:
  12910. jmp<cond> @Lbl1
  12911. jmp @Lbl2
  12912. ...
  12913. @Lbl1:
  12914. ret
  12915. Change to:
  12916. jmp<inv_cond> @Lbl2
  12917. ret
  12918. }
  12919. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12920. begin
  12921. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12922. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12923. MatchInstruction(hp2,A_RET,[S_NO]) then
  12924. begin
  12925. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12926. { Change label address to that of the unconditional jump }
  12927. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12928. TAsmLabel(symbol).DecRefs;
  12929. taicpu(hp1).opcode := A_RET;
  12930. taicpu(hp1).is_jmp := false;
  12931. taicpu(hp1).ops := taicpu(hp2).ops;
  12932. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12933. case taicpu(hp2).ops of
  12934. 0:
  12935. taicpu(hp1).clearop(0);
  12936. 1:
  12937. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12938. else
  12939. internalerror(2016041302);
  12940. end;
  12941. end;
  12942. {$ifndef i8086}
  12943. end
  12944. {
  12945. convert
  12946. j<c> .L1
  12947. mov 1,reg
  12948. jmp .L2
  12949. .L1
  12950. mov 0,reg
  12951. .L2
  12952. into
  12953. mov 0,reg
  12954. set<not(c)> reg
  12955. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12956. would destroy the flag contents
  12957. }
  12958. else if MatchInstruction(hp1,A_MOV,[]) and
  12959. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12960. {$ifdef i386}
  12961. (
  12962. { Under i386, ESI, EDI, EBP and ESP
  12963. don't have an 8-bit representation }
  12964. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12965. ) and
  12966. {$endif i386}
  12967. (taicpu(hp1).oper[0]^.val=1) and
  12968. GetNextInstruction(hp1,hp2) and
  12969. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12970. GetNextInstruction(hp2,hp3) and
  12971. (hp3.typ=ait_label) and
  12972. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12973. (tai_label(hp3).labsym.getrefs=1) and
  12974. GetNextInstruction(hp3,hp4) and
  12975. MatchInstruction(hp4,A_MOV,[]) and
  12976. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12977. (taicpu(hp4).oper[0]^.val=0) and
  12978. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12979. GetNextInstruction(hp4,hp5) and
  12980. (hp5.typ=ait_label) and
  12981. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12982. (tai_label(hp5).labsym.getrefs=1) then
  12983. begin
  12984. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12985. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12986. { remove last label }
  12987. RemoveInstruction(hp5);
  12988. { remove second label }
  12989. RemoveInstruction(hp3);
  12990. { remove jmp }
  12991. RemoveInstruction(hp2);
  12992. if taicpu(hp1).opsize=S_B then
  12993. RemoveInstruction(hp1)
  12994. else
  12995. taicpu(hp1).loadconst(0,0);
  12996. taicpu(hp4).opcode:=A_SETcc;
  12997. taicpu(hp4).opsize:=S_B;
  12998. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12999. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  13000. taicpu(hp4).opercnt:=1;
  13001. taicpu(hp4).ops:=1;
  13002. taicpu(hp4).freeop(1);
  13003. RemoveCurrentP(p);
  13004. Result:=true;
  13005. exit;
  13006. end
  13007. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  13008. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  13009. begin
  13010. { check for
  13011. jCC xxx
  13012. <several movs>
  13013. xxx:
  13014. Also spot:
  13015. Jcc xxx
  13016. <several movs>
  13017. jmp xxx
  13018. Change to:
  13019. <several cmovs with inverted condition>
  13020. jmp xxx (only for the 2nd case)
  13021. }
  13022. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  13023. if CMOVTracking^.State <> tsInvalid then
  13024. begin
  13025. CMovTracking^.Process(p);
  13026. Result := True;
  13027. end;
  13028. CMOVTracking^.Done;
  13029. {$endif i8086}
  13030. end;
  13031. end;
  13032. end;
  13033. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  13034. var
  13035. hp1,hp2,hp3: tai;
  13036. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  13037. NewSize: TOpSize;
  13038. NewRegSize: TSubRegister;
  13039. Limit: TCgInt;
  13040. SwapOper: POper;
  13041. begin
  13042. result:=false;
  13043. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  13044. GetNextInstruction(p,hp1) and
  13045. (hp1.typ = ait_instruction);
  13046. if reg_and_hp1_is_instr and
  13047. (
  13048. (taicpu(hp1).opcode <> A_LEA) or
  13049. { If the LEA instruction can be converted into an arithmetic instruction,
  13050. it may be possible to then fold it. }
  13051. (
  13052. { If the flags register is in use, don't change the instruction
  13053. to an ADD otherwise this will scramble the flags. [Kit] }
  13054. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13055. ConvertLEA(taicpu(hp1))
  13056. )
  13057. ) and
  13058. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  13059. GetNextInstruction(hp1,hp2) and
  13060. MatchInstruction(hp2,A_MOV,[]) and
  13061. (taicpu(hp2).oper[0]^.typ = top_reg) and
  13062. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  13063. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  13064. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  13065. {$ifdef i386}
  13066. { not all registers have byte size sub registers on i386 }
  13067. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  13068. {$endif i386}
  13069. (((taicpu(hp1).ops=2) and
  13070. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  13071. ((taicpu(hp1).ops=1) and
  13072. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  13073. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  13074. begin
  13075. { change movsX/movzX reg/ref, reg2
  13076. add/sub/or/... reg3/$const, reg2
  13077. mov reg2 reg/ref
  13078. to add/sub/or/... reg3/$const, reg/ref }
  13079. { by example:
  13080. movswl %si,%eax movswl %si,%eax p
  13081. decl %eax addl %edx,%eax hp1
  13082. movw %ax,%si movw %ax,%si hp2
  13083. ->
  13084. movswl %si,%eax movswl %si,%eax p
  13085. decw %eax addw %edx,%eax hp1
  13086. movw %ax,%si movw %ax,%si hp2
  13087. }
  13088. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  13089. {
  13090. ->
  13091. movswl %si,%eax movswl %si,%eax p
  13092. decw %si addw %dx,%si hp1
  13093. movw %ax,%si movw %ax,%si hp2
  13094. }
  13095. case taicpu(hp1).ops of
  13096. 1:
  13097. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  13098. 2:
  13099. begin
  13100. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  13101. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  13102. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  13103. end;
  13104. else
  13105. internalerror(2008042702);
  13106. end;
  13107. {
  13108. ->
  13109. decw %si addw %dx,%si p
  13110. }
  13111. DebugMsg(SPeepholeOptimization + 'var3',p);
  13112. RemoveCurrentP(p, hp1);
  13113. RemoveInstruction(hp2);
  13114. Result := True;
  13115. Exit;
  13116. end;
  13117. if reg_and_hp1_is_instr and
  13118. (taicpu(hp1).opcode = A_MOV) and
  13119. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13120. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13121. {$ifdef x86_64}
  13122. { check for implicit extension to 64 bit }
  13123. or
  13124. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13125. (taicpu(hp1).opsize=S_Q) and
  13126. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13127. )
  13128. {$endif x86_64}
  13129. )
  13130. then
  13131. begin
  13132. { change
  13133. movx %reg1,%reg2
  13134. mov %reg2,%reg3
  13135. dealloc %reg2
  13136. into
  13137. movx %reg,%reg3
  13138. }
  13139. TransferUsedRegs(TmpUsedRegs);
  13140. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13141. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13142. begin
  13143. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13144. {$ifdef x86_64}
  13145. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13146. (taicpu(hp1).opsize=S_Q) then
  13147. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13148. else
  13149. {$endif x86_64}
  13150. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13151. RemoveInstruction(hp1);
  13152. Result := True;
  13153. Exit;
  13154. end;
  13155. end;
  13156. if reg_and_hp1_is_instr and
  13157. ((taicpu(hp1).opcode=A_MOV) or
  13158. (taicpu(hp1).opcode=A_ADD) or
  13159. (taicpu(hp1).opcode=A_SUB) or
  13160. (taicpu(hp1).opcode=A_CMP) or
  13161. (taicpu(hp1).opcode=A_OR) or
  13162. (taicpu(hp1).opcode=A_XOR) or
  13163. (taicpu(hp1).opcode=A_AND)
  13164. ) and
  13165. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13166. begin
  13167. AndTest := (taicpu(hp1).opcode=A_AND) and
  13168. GetNextInstruction(hp1, hp2) and
  13169. (hp2.typ = ait_instruction) and
  13170. (
  13171. (
  13172. (taicpu(hp2).opcode=A_TEST) and
  13173. (
  13174. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13175. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13176. (
  13177. { If the AND and TEST instructions share a constant, this is also valid }
  13178. (taicpu(hp1).oper[0]^.typ = top_const) and
  13179. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13180. )
  13181. ) and
  13182. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13183. ) or
  13184. (
  13185. (taicpu(hp2).opcode=A_CMP) and
  13186. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13187. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13188. )
  13189. );
  13190. { change
  13191. movx (oper),%reg2
  13192. and $x,%reg2
  13193. test %reg2,%reg2
  13194. dealloc %reg2
  13195. into
  13196. op %reg1,%reg3
  13197. if the second op accesses only the bits stored in reg1
  13198. }
  13199. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13200. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13201. (taicpu(hp1).oper[0]^.typ = top_const) and
  13202. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13203. AndTest then
  13204. begin
  13205. { Check if the AND constant is in range }
  13206. case taicpu(p).opsize of
  13207. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13208. begin
  13209. NewSize := S_B;
  13210. Limit := $FF;
  13211. end;
  13212. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13213. begin
  13214. NewSize := S_W;
  13215. Limit := $FFFF;
  13216. end;
  13217. {$ifdef x86_64}
  13218. S_LQ:
  13219. begin
  13220. NewSize := S_L;
  13221. Limit := $FFFFFFFF;
  13222. end;
  13223. {$endif x86_64}
  13224. else
  13225. InternalError(2021120303);
  13226. end;
  13227. if (
  13228. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13229. { Check for negative operands }
  13230. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13231. ) and
  13232. GetNextInstruction(hp2,hp3) and
  13233. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13234. (taicpu(hp3).condition in [C_E,C_NE]) then
  13235. begin
  13236. TransferUsedRegs(TmpUsedRegs);
  13237. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13238. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13239. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13240. begin
  13241. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13242. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13243. taicpu(hp1).opcode := A_TEST;
  13244. taicpu(hp1).opsize := NewSize;
  13245. RemoveInstruction(hp2);
  13246. RemoveCurrentP(p, hp1);
  13247. Result:=true;
  13248. exit;
  13249. end;
  13250. end;
  13251. end;
  13252. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13253. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13254. (taicpu(hp1).opsize=S_B)) or
  13255. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13256. (taicpu(hp1).opsize=S_W))
  13257. {$ifdef x86_64}
  13258. or ((taicpu(p).opsize=S_LQ) and
  13259. (taicpu(hp1).opsize=S_L))
  13260. {$endif x86_64}
  13261. ) and
  13262. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13263. begin
  13264. { change
  13265. movx %reg1,%reg2
  13266. op %reg2,%reg3
  13267. dealloc %reg2
  13268. into
  13269. op %reg1,%reg3
  13270. if the second op accesses only the bits stored in reg1
  13271. }
  13272. TransferUsedRegs(TmpUsedRegs);
  13273. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13274. if AndTest then
  13275. begin
  13276. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13277. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13278. end
  13279. else
  13280. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13281. if not RegUsed then
  13282. begin
  13283. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13284. if taicpu(p).oper[0]^.typ=top_reg then
  13285. begin
  13286. case taicpu(hp1).opsize of
  13287. S_B:
  13288. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13289. S_W:
  13290. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13291. S_L:
  13292. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13293. else
  13294. Internalerror(2020102301);
  13295. end;
  13296. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13297. end
  13298. else
  13299. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13300. RemoveCurrentP(p);
  13301. if AndTest then
  13302. RemoveInstruction(hp2);
  13303. result:=true;
  13304. exit;
  13305. end;
  13306. end
  13307. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13308. (
  13309. { Bitwise operations only }
  13310. (taicpu(hp1).opcode=A_AND) or
  13311. (taicpu(hp1).opcode=A_TEST) or
  13312. (
  13313. (taicpu(hp1).oper[0]^.typ = top_const) and
  13314. (
  13315. (taicpu(hp1).opcode=A_OR) or
  13316. (taicpu(hp1).opcode=A_XOR)
  13317. )
  13318. )
  13319. ) and
  13320. (
  13321. (taicpu(hp1).oper[0]^.typ = top_const) or
  13322. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13323. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13324. ) then
  13325. begin
  13326. { change
  13327. movx %reg2,%reg2
  13328. op const,%reg2
  13329. into
  13330. op const,%reg2 (smaller version)
  13331. movx %reg2,%reg2
  13332. also change
  13333. movx %reg1,%reg2
  13334. and/test (oper),%reg2
  13335. dealloc %reg2
  13336. into
  13337. and/test (oper),%reg1
  13338. }
  13339. case taicpu(p).opsize of
  13340. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13341. begin
  13342. NewSize := S_B;
  13343. NewRegSize := R_SUBL;
  13344. Limit := $FF;
  13345. end;
  13346. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13347. begin
  13348. NewSize := S_W;
  13349. NewRegSize := R_SUBW;
  13350. Limit := $FFFF;
  13351. end;
  13352. {$ifdef x86_64}
  13353. S_LQ:
  13354. begin
  13355. NewSize := S_L;
  13356. NewRegSize := R_SUBD;
  13357. Limit := $FFFFFFFF;
  13358. end;
  13359. {$endif x86_64}
  13360. else
  13361. Internalerror(2021120302);
  13362. end;
  13363. TransferUsedRegs(TmpUsedRegs);
  13364. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13365. if AndTest then
  13366. begin
  13367. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13368. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13369. end
  13370. else
  13371. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13372. if
  13373. (
  13374. (taicpu(p).opcode = A_MOVZX) and
  13375. (
  13376. (taicpu(hp1).opcode=A_AND) or
  13377. (taicpu(hp1).opcode=A_TEST)
  13378. ) and
  13379. not (
  13380. { If both are references, then the final instruction will have
  13381. both operands as references, which is not allowed }
  13382. (taicpu(p).oper[0]^.typ = top_ref) and
  13383. (taicpu(hp1).oper[0]^.typ = top_ref)
  13384. ) and
  13385. not RegUsed
  13386. ) or
  13387. (
  13388. (
  13389. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13390. not RegUsed
  13391. ) and
  13392. (taicpu(p).oper[0]^.typ = top_reg) and
  13393. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13394. (taicpu(hp1).oper[0]^.typ = top_const) and
  13395. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13396. ) then
  13397. begin
  13398. {$if defined(i386) or defined(i8086)}
  13399. { If the target size is 8-bit, make sure we can actually encode it }
  13400. if (NewRegSize = R_SUBL) and (taicpu(hp1).oper[0]^.typ = top_reg) and not (GetSupReg(taicpu(hp1).oper[0]^.reg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  13401. Exit;
  13402. {$endif i386 or i8086}
  13403. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13404. taicpu(hp1).opsize := NewSize;
  13405. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13406. if AndTest then
  13407. begin
  13408. RemoveInstruction(hp2);
  13409. if not RegUsed then
  13410. begin
  13411. taicpu(hp1).opcode := A_TEST;
  13412. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13413. begin
  13414. { Make sure the reference is the second operand }
  13415. SwapOper := taicpu(hp1).oper[0];
  13416. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13417. taicpu(hp1).oper[1] := SwapOper;
  13418. end;
  13419. end;
  13420. end;
  13421. case taicpu(hp1).oper[0]^.typ of
  13422. top_reg:
  13423. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13424. top_const:
  13425. { For the AND/TEST case }
  13426. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13427. else
  13428. ;
  13429. end;
  13430. if RegUsed then
  13431. begin
  13432. AsmL.Remove(p);
  13433. AsmL.InsertAfter(p, hp1);
  13434. p := hp1;
  13435. end
  13436. else
  13437. RemoveCurrentP(p, hp1);
  13438. result:=true;
  13439. exit;
  13440. end;
  13441. end;
  13442. end;
  13443. if reg_and_hp1_is_instr and
  13444. (taicpu(p).oper[0]^.typ = top_reg) and
  13445. (
  13446. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13447. ) and
  13448. (taicpu(hp1).oper[0]^.typ = top_const) and
  13449. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13450. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13451. { Minimum shift value allowed is the bit difference between the sizes }
  13452. (taicpu(hp1).oper[0]^.val >=
  13453. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13454. 8 * (
  13455. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13456. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13457. )
  13458. ) then
  13459. begin
  13460. { For:
  13461. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13462. shl/sal ##, %reg1
  13463. Remove the movsx/movzx instruction if the shift overwrites the
  13464. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13465. }
  13466. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13467. RemoveCurrentP(p, hp1);
  13468. Result := True;
  13469. Exit;
  13470. end
  13471. else if reg_and_hp1_is_instr and
  13472. (taicpu(p).oper[0]^.typ = top_reg) and
  13473. (
  13474. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13475. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13476. ) and
  13477. (taicpu(hp1).oper[0]^.typ = top_const) and
  13478. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13479. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13480. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13481. (taicpu(hp1).oper[0]^.val <
  13482. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13483. 8 * (
  13484. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13485. )
  13486. ) then
  13487. begin
  13488. { For:
  13489. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13490. sar ##, %reg1 shr ##, %reg1
  13491. Move the shift to before the movx instruction if the shift value
  13492. is not too large.
  13493. }
  13494. asml.Remove(hp1);
  13495. asml.InsertBefore(hp1, p);
  13496. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13497. case taicpu(p).opsize of
  13498. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13499. taicpu(hp1).opsize := S_B;
  13500. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13501. taicpu(hp1).opsize := S_W;
  13502. {$ifdef x86_64}
  13503. S_LQ:
  13504. taicpu(hp1).opsize := S_L;
  13505. {$endif}
  13506. else
  13507. InternalError(2020112401);
  13508. end;
  13509. if (taicpu(hp1).opcode = A_SHR) then
  13510. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13511. else
  13512. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13513. Result := True;
  13514. end;
  13515. if reg_and_hp1_is_instr and
  13516. (taicpu(p).oper[0]^.typ = top_reg) and
  13517. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13518. (
  13519. (taicpu(hp1).opcode = taicpu(p).opcode)
  13520. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13521. {$ifdef x86_64}
  13522. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13523. {$endif x86_64}
  13524. ) then
  13525. begin
  13526. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13527. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13528. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13529. begin
  13530. {
  13531. For example:
  13532. movzbw %al,%ax
  13533. movzwl %ax,%eax
  13534. Compress into:
  13535. movzbl %al,%eax
  13536. }
  13537. RegUsed := False;
  13538. case taicpu(p).opsize of
  13539. S_BW:
  13540. case taicpu(hp1).opsize of
  13541. S_WL:
  13542. begin
  13543. taicpu(p).opsize := S_BL;
  13544. RegUsed := True;
  13545. end;
  13546. {$ifdef x86_64}
  13547. S_WQ:
  13548. begin
  13549. if taicpu(p).opcode = A_MOVZX then
  13550. begin
  13551. taicpu(p).opsize := S_BL;
  13552. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13553. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13554. end
  13555. else
  13556. taicpu(p).opsize := S_BQ;
  13557. RegUsed := True;
  13558. end;
  13559. {$endif x86_64}
  13560. else
  13561. ;
  13562. end;
  13563. {$ifdef x86_64}
  13564. S_BL:
  13565. case taicpu(hp1).opsize of
  13566. S_LQ:
  13567. begin
  13568. if taicpu(p).opcode = A_MOVZX then
  13569. begin
  13570. taicpu(p).opsize := S_BL;
  13571. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13572. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13573. end
  13574. else
  13575. taicpu(p).opsize := S_BQ;
  13576. RegUsed := True;
  13577. end;
  13578. else
  13579. ;
  13580. end;
  13581. S_WL:
  13582. case taicpu(hp1).opsize of
  13583. S_LQ:
  13584. begin
  13585. if taicpu(p).opcode = A_MOVZX then
  13586. begin
  13587. taicpu(p).opsize := S_WL;
  13588. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13589. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13590. end
  13591. else
  13592. taicpu(p).opsize := S_WQ;
  13593. RegUsed := True;
  13594. end;
  13595. else
  13596. ;
  13597. end;
  13598. {$endif x86_64}
  13599. else
  13600. ;
  13601. end;
  13602. if RegUsed then
  13603. begin
  13604. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13605. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13606. RemoveInstruction(hp1);
  13607. Result := True;
  13608. Exit;
  13609. end;
  13610. end;
  13611. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13612. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13613. GetNextInstruction(hp1, hp2) and
  13614. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13615. (
  13616. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13617. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13618. {$ifdef x86_64}
  13619. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13620. {$endif x86_64}
  13621. ) and
  13622. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13623. (
  13624. (
  13625. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13626. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13627. ) or
  13628. (
  13629. { Only allow the operands in reverse order for TEST instructions }
  13630. (taicpu(hp2).opcode = A_TEST) and
  13631. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13632. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13633. )
  13634. ) then
  13635. begin
  13636. {
  13637. For example:
  13638. movzbl %al,%eax
  13639. movzbl (ref),%edx
  13640. andl %edx,%eax
  13641. (%edx deallocated)
  13642. Change to:
  13643. andb (ref),%al
  13644. movzbl %al,%eax
  13645. Rules are:
  13646. - First two instructions have the same opcode and opsize
  13647. - First instruction's operands are the same super-register
  13648. - Second instruction operates on a different register
  13649. - Third instruction is AND, OR, XOR or TEST
  13650. - Third instruction's operands are the destination registers of the first two instructions
  13651. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13652. - Second instruction's destination register is deallocated afterwards
  13653. }
  13654. TransferUsedRegs(TmpUsedRegs);
  13655. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13656. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13657. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13658. begin
  13659. case taicpu(p).opsize of
  13660. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13661. NewSize := S_B;
  13662. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13663. NewSize := S_W;
  13664. {$ifdef x86_64}
  13665. S_LQ:
  13666. NewSize := S_L;
  13667. {$endif x86_64}
  13668. else
  13669. InternalError(2021120301);
  13670. end;
  13671. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13672. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13673. taicpu(hp2).opsize := NewSize;
  13674. RemoveInstruction(hp1);
  13675. { With TEST, it's best to keep the MOVX instruction at the top }
  13676. if (taicpu(hp2).opcode <> A_TEST) then
  13677. begin
  13678. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13679. asml.Remove(p);
  13680. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13681. asml.InsertAfter(p, hp2);
  13682. p := hp2;
  13683. end
  13684. else
  13685. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13686. Result := True;
  13687. Exit;
  13688. end;
  13689. end;
  13690. end;
  13691. if taicpu(p).opcode=A_MOVZX then
  13692. begin
  13693. { removes superfluous And's after movzx's }
  13694. if reg_and_hp1_is_instr and
  13695. (taicpu(hp1).opcode = A_AND) and
  13696. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13697. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13698. {$ifdef x86_64}
  13699. { check for implicit extension to 64 bit }
  13700. or
  13701. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13702. (taicpu(hp1).opsize=S_Q) and
  13703. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13704. )
  13705. {$endif x86_64}
  13706. )
  13707. then
  13708. begin
  13709. case taicpu(p).opsize Of
  13710. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13711. if (taicpu(hp1).oper[0]^.val = $ff) then
  13712. begin
  13713. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13714. RemoveInstruction(hp1);
  13715. Result:=true;
  13716. exit;
  13717. end;
  13718. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13719. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13720. begin
  13721. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13722. RemoveInstruction(hp1);
  13723. Result:=true;
  13724. exit;
  13725. end;
  13726. {$ifdef x86_64}
  13727. S_LQ:
  13728. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13729. begin
  13730. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13731. RemoveInstruction(hp1);
  13732. Result:=true;
  13733. exit;
  13734. end;
  13735. {$endif x86_64}
  13736. else
  13737. ;
  13738. end;
  13739. { we cannot get rid of the and, but can we get rid of the movz ?}
  13740. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13741. begin
  13742. case taicpu(p).opsize Of
  13743. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13744. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13745. begin
  13746. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13747. RemoveCurrentP(p,hp1);
  13748. Result:=true;
  13749. exit;
  13750. end;
  13751. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13752. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13753. begin
  13754. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13755. RemoveCurrentP(p,hp1);
  13756. Result:=true;
  13757. exit;
  13758. end;
  13759. {$ifdef x86_64}
  13760. S_LQ:
  13761. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13762. begin
  13763. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13764. RemoveCurrentP(p,hp1);
  13765. Result:=true;
  13766. exit;
  13767. end;
  13768. {$endif x86_64}
  13769. else
  13770. ;
  13771. end;
  13772. end;
  13773. end;
  13774. { changes some movzx constructs to faster synonyms (all examples
  13775. are given with eax/ax, but are also valid for other registers)}
  13776. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13777. begin
  13778. case taicpu(p).opsize of
  13779. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13780. (the machine code is equivalent to movzbl %al,%eax), but the
  13781. code generator still generates that assembler instruction and
  13782. it is silently converted. This should probably be checked.
  13783. [Kit] }
  13784. S_BW:
  13785. begin
  13786. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13787. (
  13788. not IsMOVZXAcceptable
  13789. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13790. or (
  13791. (cs_opt_size in current_settings.optimizerswitches) and
  13792. (taicpu(p).oper[1]^.reg = NR_AX)
  13793. )
  13794. ) then
  13795. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13796. begin
  13797. DebugMsg(SPeepholeOptimization + 'var7',p);
  13798. taicpu(p).opcode := A_AND;
  13799. taicpu(p).changeopsize(S_W);
  13800. taicpu(p).loadConst(0,$ff);
  13801. Result := True;
  13802. end
  13803. else if not IsMOVZXAcceptable and
  13804. GetNextInstruction(p, hp1) and
  13805. (tai(hp1).typ = ait_instruction) and
  13806. (taicpu(hp1).opcode = A_AND) and
  13807. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13808. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13809. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13810. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13811. begin
  13812. DebugMsg(SPeepholeOptimization + 'var8',p);
  13813. taicpu(p).opcode := A_MOV;
  13814. taicpu(p).changeopsize(S_W);
  13815. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13816. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13817. Result := True;
  13818. end;
  13819. end;
  13820. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13821. S_BL:
  13822. if not IsMOVZXAcceptable then
  13823. begin
  13824. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13825. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13826. begin
  13827. DebugMsg(SPeepholeOptimization + 'var9',p);
  13828. taicpu(p).opcode := A_AND;
  13829. taicpu(p).changeopsize(S_L);
  13830. taicpu(p).loadConst(0,$ff);
  13831. Result := True;
  13832. end
  13833. else if GetNextInstruction(p, hp1) and
  13834. (tai(hp1).typ = ait_instruction) and
  13835. (taicpu(hp1).opcode = A_AND) and
  13836. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13837. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13838. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13839. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13840. begin
  13841. DebugMsg(SPeepholeOptimization + 'var10',p);
  13842. taicpu(p).opcode := A_MOV;
  13843. taicpu(p).changeopsize(S_L);
  13844. { do not use R_SUBWHOLE
  13845. as movl %rdx,%eax
  13846. is invalid in assembler PM }
  13847. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13848. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13849. Result := True;
  13850. end;
  13851. end;
  13852. {$endif i8086}
  13853. S_WL:
  13854. if not IsMOVZXAcceptable then
  13855. begin
  13856. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13857. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13858. begin
  13859. DebugMsg(SPeepholeOptimization + 'var11',p);
  13860. taicpu(p).opcode := A_AND;
  13861. taicpu(p).changeopsize(S_L);
  13862. taicpu(p).loadConst(0,$ffff);
  13863. Result := True;
  13864. end
  13865. else if GetNextInstruction(p, hp1) and
  13866. (tai(hp1).typ = ait_instruction) and
  13867. (taicpu(hp1).opcode = A_AND) and
  13868. (taicpu(hp1).oper[0]^.typ = top_const) and
  13869. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13870. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13871. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13872. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13873. begin
  13874. DebugMsg(SPeepholeOptimization + 'var12',p);
  13875. taicpu(p).opcode := A_MOV;
  13876. taicpu(p).changeopsize(S_L);
  13877. { do not use R_SUBWHOLE
  13878. as movl %rdx,%eax
  13879. is invalid in assembler PM }
  13880. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13881. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13882. Result := True;
  13883. end;
  13884. end;
  13885. else
  13886. InternalError(2017050705);
  13887. end;
  13888. end
  13889. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13890. begin
  13891. if GetNextInstruction(p, hp1) and
  13892. (tai(hp1).typ = ait_instruction) and
  13893. (taicpu(hp1).opcode = A_AND) and
  13894. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13895. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13896. begin
  13897. case taicpu(p).opsize Of
  13898. S_BL:
  13899. if (taicpu(hp1).opsize <> S_L) or
  13900. (taicpu(hp1).oper[0]^.val > $FF) then
  13901. begin
  13902. DebugMsg(SPeepholeOptimization + 'var13',p);
  13903. taicpu(hp1).changeopsize(S_L);
  13904. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13905. Include(OptsToCheck, aoc_ForceNewIteration);
  13906. end;
  13907. S_WL:
  13908. if (taicpu(hp1).opsize <> S_L) or
  13909. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13910. begin
  13911. DebugMsg(SPeepholeOptimization + 'var14',p);
  13912. taicpu(hp1).changeopsize(S_L);
  13913. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13914. Include(OptsToCheck, aoc_ForceNewIteration);
  13915. end;
  13916. S_BW:
  13917. if (taicpu(hp1).opsize <> S_W) or
  13918. (taicpu(hp1).oper[0]^.val > $FF) then
  13919. begin
  13920. DebugMsg(SPeepholeOptimization + 'var15',p);
  13921. taicpu(hp1).changeopsize(S_W);
  13922. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13923. Include(OptsToCheck, aoc_ForceNewIteration);
  13924. end;
  13925. else
  13926. Internalerror(2017050704)
  13927. end;
  13928. end;
  13929. end;
  13930. end;
  13931. end;
  13932. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13933. var
  13934. hp1, hp2 : tai;
  13935. MaskLength : Cardinal;
  13936. MaskedBits : TCgInt;
  13937. ActiveReg : TRegister;
  13938. begin
  13939. Result:=false;
  13940. { There are no optimisations for reference targets }
  13941. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13942. Exit;
  13943. while GetNextInstruction(p, hp1) and
  13944. (hp1.typ = ait_instruction) do
  13945. begin
  13946. if (taicpu(p).oper[0]^.typ = top_const) then
  13947. begin
  13948. case taicpu(hp1).opcode of
  13949. A_AND:
  13950. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13951. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13952. { the second register must contain the first one, so compare their subreg types }
  13953. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13954. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13955. { change
  13956. and const1, reg
  13957. and const2, reg
  13958. to
  13959. and (const1 and const2), reg
  13960. }
  13961. begin
  13962. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13963. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13964. RemoveCurrentP(p, hp1);
  13965. Result:=true;
  13966. exit;
  13967. end;
  13968. A_CMP:
  13969. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13970. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13971. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13972. { Just check that the condition on the next instruction is compatible }
  13973. GetNextInstruction(hp1, hp2) and
  13974. (hp2.typ = ait_instruction) and
  13975. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13976. then
  13977. { change
  13978. and 2^n, reg
  13979. cmp 2^n, reg
  13980. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13981. to
  13982. and 2^n, reg
  13983. test reg, reg
  13984. j(~c) / set(~c) / cmov(~c)
  13985. }
  13986. begin
  13987. { Keep TEST instruction in, rather than remove it, because
  13988. it may trigger other optimisations such as MovAndTest2Test }
  13989. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13990. taicpu(hp1).opcode := A_TEST;
  13991. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13992. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13993. Result := True;
  13994. Exit;
  13995. end
  13996. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13997. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13998. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13999. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  14000. { change
  14001. and $ff/$ff/$ffff, reg
  14002. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  14003. dealloc reg
  14004. to
  14005. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  14006. }
  14007. begin
  14008. TransferUsedRegs(TmpUsedRegs);
  14009. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14010. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  14011. begin
  14012. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  14013. case taicpu(p).oper[0]^.val of
  14014. $ff:
  14015. begin
  14016. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  14017. taicpu(hp1).opsize:=S_B;
  14018. end;
  14019. $ffff:
  14020. begin
  14021. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  14022. taicpu(hp1).opsize:=S_W;
  14023. end;
  14024. $ffffffff:
  14025. begin
  14026. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  14027. taicpu(hp1).opsize:=S_L;
  14028. end;
  14029. else
  14030. Internalerror(2023030401);
  14031. end;
  14032. RemoveCurrentP(p);
  14033. Result := True;
  14034. Exit;
  14035. end;
  14036. end;
  14037. A_MOVZX:
  14038. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  14039. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  14040. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14041. (
  14042. (
  14043. (taicpu(p).opsize=S_W) and
  14044. (taicpu(hp1).opsize=S_BW)
  14045. ) or
  14046. (
  14047. (taicpu(p).opsize=S_L) and
  14048. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  14049. )
  14050. {$ifdef x86_64}
  14051. or
  14052. (
  14053. (taicpu(p).opsize=S_Q) and
  14054. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  14055. )
  14056. {$endif x86_64}
  14057. ) then
  14058. begin
  14059. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14060. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  14061. ) or
  14062. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14063. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  14064. then
  14065. begin
  14066. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  14067. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  14068. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  14069. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  14070. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  14071. }
  14072. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  14073. RemoveInstruction(hp1);
  14074. { See if there are other optimisations possible }
  14075. Continue;
  14076. end;
  14077. end;
  14078. A_SHL:
  14079. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14080. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  14081. begin
  14082. {$ifopt R+}
  14083. {$define RANGE_WAS_ON}
  14084. {$R-}
  14085. {$endif}
  14086. { get length of potential and mask }
  14087. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  14088. { really a mask? }
  14089. {$ifdef RANGE_WAS_ON}
  14090. {$R+}
  14091. {$endif}
  14092. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  14093. { unmasked part shifted out? }
  14094. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  14095. begin
  14096. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  14097. RemoveCurrentP(p, hp1);
  14098. Result:=true;
  14099. exit;
  14100. end;
  14101. end;
  14102. A_SHR:
  14103. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14104. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  14105. (taicpu(hp1).oper[0]^.val <= 63) then
  14106. begin
  14107. { Does SHR combined with the AND cover all the bits?
  14108. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  14109. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  14110. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  14111. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  14112. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  14113. begin
  14114. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  14115. RemoveCurrentP(p, hp1);
  14116. Result := True;
  14117. Exit;
  14118. end;
  14119. end;
  14120. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14121. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14122. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14123. begin
  14124. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14125. (
  14126. (
  14127. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14128. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14129. ) or (
  14130. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14131. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14132. {$ifdef x86_64}
  14133. ) or (
  14134. (taicpu(hp1).opsize = S_LQ) and
  14135. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14136. {$endif x86_64}
  14137. )
  14138. ) then
  14139. begin
  14140. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14141. begin
  14142. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14143. RemoveInstruction(hp1);
  14144. { See if there are other optimisations possible }
  14145. Continue;
  14146. end;
  14147. { The super-registers are the same though.
  14148. Note that this change by itself doesn't improve
  14149. code speed, but it opens up other optimisations. }
  14150. {$ifdef x86_64}
  14151. { Convert 64-bit register to 32-bit }
  14152. case taicpu(hp1).opsize of
  14153. S_BQ:
  14154. begin
  14155. taicpu(hp1).opsize := S_BL;
  14156. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14157. end;
  14158. S_WQ:
  14159. begin
  14160. taicpu(hp1).opsize := S_WL;
  14161. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14162. end
  14163. else
  14164. ;
  14165. end;
  14166. {$endif x86_64}
  14167. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14168. taicpu(hp1).opcode := A_MOVZX;
  14169. { See if there are other optimisations possible }
  14170. Continue;
  14171. end;
  14172. end;
  14173. else
  14174. ;
  14175. end;
  14176. end
  14177. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14178. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14179. begin
  14180. {$ifdef x86_64}
  14181. if (taicpu(p).opsize = S_Q) then
  14182. begin
  14183. { Never necessary }
  14184. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14185. RemoveCurrentP(p, hp1);
  14186. Result := True;
  14187. Exit;
  14188. end;
  14189. {$endif x86_64}
  14190. { Forward check to determine necessity of and %reg,%reg }
  14191. TransferUsedRegs(TmpUsedRegs);
  14192. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14193. { Saves on a bunch of dereferences }
  14194. ActiveReg := taicpu(p).oper[1]^.reg;
  14195. case taicpu(hp1).opcode of
  14196. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14197. if (
  14198. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14199. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14200. ) and
  14201. (
  14202. (taicpu(hp1).opcode <> A_MOV) or
  14203. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14204. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14205. ) and
  14206. not (
  14207. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14208. (taicpu(hp1).opcode = A_MOV) and
  14209. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14210. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14211. ) and
  14212. (
  14213. (
  14214. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14215. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14216. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14217. ) or
  14218. (
  14219. {$ifdef x86_64}
  14220. (
  14221. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14222. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14223. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14224. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14225. ) and
  14226. {$endif x86_64}
  14227. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14228. )
  14229. ) then
  14230. begin
  14231. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14232. RemoveCurrentP(p, hp1);
  14233. Result := True;
  14234. Exit;
  14235. end;
  14236. A_ADD,
  14237. A_AND,
  14238. A_BSF,
  14239. A_BSR,
  14240. A_BTC,
  14241. A_BTR,
  14242. A_BTS,
  14243. A_OR,
  14244. A_SUB,
  14245. A_XOR:
  14246. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14247. if (
  14248. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14249. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14250. ) and
  14251. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14252. begin
  14253. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14254. RemoveCurrentP(p, hp1);
  14255. Result := True;
  14256. Exit;
  14257. end;
  14258. A_CMP,
  14259. A_TEST:
  14260. if (
  14261. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14262. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14263. ) and
  14264. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14265. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14266. begin
  14267. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14268. RemoveCurrentP(p, hp1);
  14269. Result := True;
  14270. Exit;
  14271. end;
  14272. A_BSWAP,
  14273. A_NEG,
  14274. A_NOT:
  14275. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14276. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14277. begin
  14278. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14279. RemoveCurrentP(p, hp1);
  14280. Result := True;
  14281. Exit;
  14282. end;
  14283. else
  14284. ;
  14285. end;
  14286. end;
  14287. if (taicpu(hp1).is_jmp) and
  14288. (taicpu(hp1).opcode<>A_JMP) and
  14289. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14290. begin
  14291. { change
  14292. and x, reg
  14293. jxx
  14294. to
  14295. test x, reg
  14296. jxx
  14297. if reg is deallocated before the
  14298. jump, but only if it's a conditional jump (PFV)
  14299. }
  14300. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14301. taicpu(p).opcode := A_TEST;
  14302. Exit;
  14303. end;
  14304. Break;
  14305. end;
  14306. { Lone AND tests }
  14307. if (taicpu(p).oper[0]^.typ = top_const) then
  14308. begin
  14309. {
  14310. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14311. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14312. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14313. }
  14314. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14315. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14316. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14317. begin
  14318. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14319. if taicpu(p).opsize = S_L then
  14320. begin
  14321. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14322. Result := True;
  14323. end;
  14324. end;
  14325. end;
  14326. { Backward check to determine necessity of and %reg,%reg }
  14327. if (taicpu(p).oper[0]^.typ = top_reg) and
  14328. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14329. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14330. GetLastInstruction(p, hp2) and
  14331. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14332. { Check size of adjacent instruction to determine if the AND is
  14333. effectively a null operation }
  14334. (
  14335. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14336. { Note: Don't include S_Q }
  14337. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14338. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14339. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14340. ) then
  14341. begin
  14342. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14343. { If GetNextInstruction returned False, hp1 will be nil }
  14344. RemoveCurrentP(p, hp1);
  14345. Result := True;
  14346. Exit;
  14347. end;
  14348. end;
  14349. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14350. var
  14351. hp1, hp2: tai;
  14352. NewRef: TReference;
  14353. Distance: Cardinal;
  14354. TempTracking: TAllUsedRegs;
  14355. DoAddMov2Lea: Boolean;
  14356. { This entire nested function is used in an if-statement below, but we
  14357. want to avoid all the used reg transfers and GetNextInstruction calls
  14358. until we really have to check }
  14359. function MemRegisterNotUsedLater: Boolean; inline;
  14360. var
  14361. hp2: tai;
  14362. begin
  14363. TransferUsedRegs(TmpUsedRegs);
  14364. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14365. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14366. else
  14367. { p and hp1 will be adjacent }
  14368. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14369. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14370. end;
  14371. begin
  14372. Result := False;
  14373. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14374. (taicpu(p).oper[1]^.typ = top_reg) then
  14375. begin
  14376. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14377. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14378. (hp1.typ <> ait_instruction) or
  14379. not
  14380. (
  14381. (cs_opt_level3 in current_settings.optimizerswitches) or
  14382. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14383. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14384. ) then
  14385. Exit;
  14386. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14387. addq $x, %rax
  14388. movq %rax, %rdx
  14389. sarq $63, %rdx
  14390. (%rax still in use)
  14391. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14392. leaq $x(%rax),%rdx
  14393. addq $x, %rax
  14394. sarq $63, %rdx
  14395. ...which is okay since it breaks the dependency chain between
  14396. addq and movq, but if OptPass2MOV is called first:
  14397. addq $x, %rax
  14398. cqto
  14399. ...which is better in all ways, taking only 2 cycles to execute
  14400. and much smaller in code size.
  14401. }
  14402. { The extra register tracking is quite strenuous }
  14403. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14404. MatchInstruction(hp1, A_MOV, []) then
  14405. begin
  14406. { Update the register tracking to the MOV instruction }
  14407. CopyUsedRegs(TempTracking);
  14408. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14409. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14410. else
  14411. { p and hp1 will be adjacent }
  14412. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14413. hp2 := hp1;
  14414. if OptPass2MOV(hp1) then
  14415. Include(OptsToCheck, aoc_ForceNewIteration);
  14416. { Reset the tracking to the current instruction }
  14417. RestoreUsedRegs(TempTracking);
  14418. ReleaseUsedRegs(TempTracking);
  14419. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14420. OptPass2ADD get called again }
  14421. if (hp1 <> hp2) then
  14422. begin
  14423. Result := True;
  14424. Exit;
  14425. end;
  14426. end;
  14427. { Change:
  14428. add %reg2,%reg1
  14429. (%reg2 not modified in between)
  14430. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14431. To:
  14432. mov/s/z #(%reg1,%reg2),%reg1
  14433. }
  14434. if (taicpu(p).oper[0]^.typ = top_reg) and
  14435. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14436. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14437. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14438. (
  14439. (
  14440. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14441. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14442. { r/esp cannot be an index }
  14443. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14444. ) or (
  14445. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14446. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14447. )
  14448. ) and (
  14449. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14450. (
  14451. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14452. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14453. MemRegisterNotUsedLater
  14454. )
  14455. ) then
  14456. begin
  14457. if (
  14458. { Instructions are guaranteed to be adjacent on -O2 and under }
  14459. (cs_opt_level3 in current_settings.optimizerswitches) and
  14460. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14461. ) then
  14462. begin
  14463. { If the other register is used in between, move the MOV
  14464. instruction to right after the ADD instruction so a
  14465. saving can still be made }
  14466. Asml.Remove(hp1);
  14467. Asml.InsertAfter(hp1, p);
  14468. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14469. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14470. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14471. RemoveCurrentp(p, hp1);
  14472. end
  14473. else
  14474. begin
  14475. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14476. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14477. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14478. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14479. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14480. { hp1 may not be the immediate next instruction under -O3 }
  14481. RemoveCurrentp(p)
  14482. else
  14483. RemoveCurrentp(p, hp1);
  14484. end;
  14485. Result := True;
  14486. Exit;
  14487. end;
  14488. { Change:
  14489. addl/q $x,%reg1
  14490. movl/q %reg1,%reg2
  14491. To:
  14492. leal/q $x(%reg1),%reg2
  14493. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14494. Breaks the dependency chain.
  14495. }
  14496. if (taicpu(p).oper[0]^.typ = top_const) and
  14497. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14498. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14499. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14500. (
  14501. { Instructions are guaranteed to be adjacent on -O2 and under }
  14502. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14503. (
  14504. { If the flags are used, don't make the optimisation,
  14505. otherwise they will be scrambled. Fixes #41148 }
  14506. (
  14507. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14508. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14509. ) and
  14510. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14511. )
  14512. ) then
  14513. begin
  14514. TransferUsedRegs(TmpUsedRegs);
  14515. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14516. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14517. else
  14518. { p and hp1 will be adjacent }
  14519. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14520. if (
  14521. SetAndTest(
  14522. (
  14523. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14524. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14525. ),
  14526. DoAddMov2Lea
  14527. ) or
  14528. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14529. not (cs_opt_size in current_settings.optimizerswitches)
  14530. ) then
  14531. begin
  14532. { Change the MOV instruction to a LEA instruction, and update the
  14533. first operand }
  14534. reference_reset(NewRef, 1, []);
  14535. NewRef.base := taicpu(p).oper[1]^.reg;
  14536. NewRef.scalefactor := 1;
  14537. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14538. taicpu(hp1).opcode := A_LEA;
  14539. taicpu(hp1).loadref(0, NewRef);
  14540. if DoAddMov2Lea then
  14541. begin
  14542. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14543. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14544. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14545. { hp1 may not be the immediate next instruction under -O3 }
  14546. RemoveCurrentp(p)
  14547. else
  14548. RemoveCurrentp(p, hp1);
  14549. end
  14550. else
  14551. begin
  14552. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14553. { Move what is now the LEA instruction to before the ADD instruction }
  14554. Asml.Remove(hp1);
  14555. Asml.InsertBefore(hp1, p);
  14556. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14557. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14558. p := hp1;
  14559. end;
  14560. Result := True;
  14561. end;
  14562. end;
  14563. end;
  14564. end;
  14565. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14566. var
  14567. SubReg: TSubRegister;
  14568. hp1, hp2: tai;
  14569. CallJmp: Boolean;
  14570. begin
  14571. Result := False;
  14572. CallJmp := False;
  14573. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14574. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14575. with taicpu(p).oper[0]^.ref^ do
  14576. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14577. if (offset = 0) then
  14578. begin
  14579. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14580. begin
  14581. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14582. taicpu(p).opcode := A_ADD;
  14583. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14584. Result := True;
  14585. end
  14586. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14587. begin
  14588. if (base <> NR_NO) then
  14589. begin
  14590. if (scalefactor <= 1) then
  14591. begin
  14592. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14593. taicpu(p).opcode := A_ADD;
  14594. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14595. Result := True;
  14596. end;
  14597. end
  14598. else
  14599. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14600. if (scalefactor in [2, 4, 8]) then
  14601. begin
  14602. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14603. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14604. taicpu(p).opcode := A_SHL;
  14605. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14606. Result := True;
  14607. end;
  14608. end;
  14609. end
  14610. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14611. lot of latency, so break off the offset if %reg3 is used soon
  14612. afterwards }
  14613. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14614. { If 3-component addresses don't have additional latency, don't
  14615. perform this optimisation }
  14616. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14617. GetNextInstruction(p, hp1) and
  14618. (hp1.typ = ait_instruction) and
  14619. (
  14620. (
  14621. { Permit jumps and calls since they have a larger degree of overhead }
  14622. (
  14623. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14624. (
  14625. { ... unless the register specifies the location }
  14626. (taicpu(hp1).ops > 0) and
  14627. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14628. )
  14629. ) and
  14630. (
  14631. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14632. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14633. )
  14634. )
  14635. or
  14636. (
  14637. { Check up to two instructions ahead }
  14638. GetNextInstruction(hp1, hp2) and
  14639. (hp2.typ = ait_instruction) and
  14640. (
  14641. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14642. (
  14643. { Same as above }
  14644. (taicpu(hp2).ops > 0) and
  14645. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14646. )
  14647. ) and
  14648. (
  14649. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14650. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14651. )
  14652. )
  14653. ) then
  14654. begin
  14655. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14656. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14657. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14658. offset := 0;
  14659. if Assigned(symbol) or Assigned(relsymbol) then
  14660. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14661. else
  14662. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14663. { Inserting before the next instruction rather than after the
  14664. current instruction gives more accurate register tracking }
  14665. asml.InsertBefore(hp2, hp1);
  14666. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14667. Result := True;
  14668. end;
  14669. end;
  14670. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14671. var
  14672. hp1, hp2: tai;
  14673. NewRef: TReference;
  14674. Distance: Cardinal;
  14675. TempTracking: TAllUsedRegs;
  14676. DoSubMov2Lea: Boolean;
  14677. begin
  14678. Result := False;
  14679. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14680. MatchOpType(taicpu(p),top_const,top_reg) then
  14681. begin
  14682. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14683. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14684. (hp1.typ <> ait_instruction) or
  14685. not
  14686. (
  14687. (cs_opt_level3 in current_settings.optimizerswitches) or
  14688. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14689. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14690. ) then
  14691. Exit;
  14692. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14693. subq $x, %rax
  14694. movq %rax, %rdx
  14695. sarq $63, %rdx
  14696. (%rax still in use)
  14697. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14698. leaq $-x(%rax),%rdx
  14699. movq $x, %rax
  14700. sarq $63, %rdx
  14701. ...which is okay since it breaks the dependency chain between
  14702. subq and movq, but if OptPass2MOV is called first:
  14703. subq $x, %rax
  14704. cqto
  14705. ...which is better in all ways, taking only 2 cycles to execute
  14706. and much smaller in code size.
  14707. }
  14708. { The extra register tracking is quite strenuous }
  14709. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14710. MatchInstruction(hp1, A_MOV, []) then
  14711. begin
  14712. { Update the register tracking to the MOV instruction }
  14713. CopyUsedRegs(TempTracking);
  14714. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14715. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14716. else
  14717. { p and hp1 will be adjacent }
  14718. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14719. hp2 := hp1;
  14720. if OptPass2MOV(hp1) then
  14721. Include(OptsToCheck, aoc_ForceNewIteration);
  14722. { Reset the tracking to the current instruction }
  14723. RestoreUsedRegs(TempTracking);
  14724. ReleaseUsedRegs(TempTracking);
  14725. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14726. OptPass2SUB get called again }
  14727. if (hp1 <> hp2) then
  14728. begin
  14729. Result := True;
  14730. Exit;
  14731. end;
  14732. end;
  14733. { Change:
  14734. subl/q $x,%reg1
  14735. movl/q %reg1,%reg2
  14736. To:
  14737. leal/q $-x(%reg1),%reg2
  14738. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14739. Breaks the dependency chain and potentially permits the removal of
  14740. a CMP instruction if one follows.
  14741. }
  14742. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14743. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14744. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14745. (
  14746. { Instructions are guaranteed to be adjacent on -O2 and under }
  14747. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14748. (
  14749. { If the flags are used, don't make the optimisation,
  14750. otherwise they will be scrambled. Fixes #41148 }
  14751. (
  14752. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14753. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14754. ) and
  14755. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14756. )
  14757. ) then
  14758. begin
  14759. TransferUsedRegs(TmpUsedRegs);
  14760. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14761. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14762. else
  14763. { p and hp1 will be adjacent }
  14764. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14765. if (
  14766. SetAndTest(
  14767. (
  14768. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14769. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14770. ),
  14771. DoSubMov2Lea
  14772. ) or
  14773. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14774. not (cs_opt_size in current_settings.optimizerswitches)
  14775. ) then
  14776. begin
  14777. { Change the MOV instruction to a LEA instruction, and update the
  14778. first operand }
  14779. reference_reset(NewRef, 1, []);
  14780. NewRef.base := taicpu(p).oper[1]^.reg;
  14781. NewRef.scalefactor := 1;
  14782. NewRef.offset := -taicpu(p).oper[0]^.val;
  14783. taicpu(hp1).opcode := A_LEA;
  14784. taicpu(hp1).loadref(0, NewRef);
  14785. if DoSubMov2Lea then
  14786. begin
  14787. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14788. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14789. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14790. { hp1 may not be the immediate next instruction under -O3 }
  14791. RemoveCurrentp(p)
  14792. else
  14793. RemoveCurrentp(p, hp1);
  14794. end
  14795. else
  14796. begin
  14797. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14798. { Move what is now the LEA instruction to before the SUB instruction }
  14799. Asml.Remove(hp1);
  14800. Asml.InsertBefore(hp1, p);
  14801. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14802. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14803. p := hp1;
  14804. end;
  14805. Result := True;
  14806. end;
  14807. end;
  14808. end;
  14809. end;
  14810. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14811. begin
  14812. { we can skip all instructions not messing with the stack pointer }
  14813. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14814. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14815. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14816. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14817. ({(taicpu(hp1).ops=0) or }
  14818. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14819. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14820. ) and }
  14821. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14822. )
  14823. ) do
  14824. GetNextInstruction(hp1,hp1);
  14825. Result:=assigned(hp1);
  14826. end;
  14827. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14828. var
  14829. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14830. begin
  14831. Result:=false;
  14832. {$ifdef x86_64}
  14833. { Change:
  14834. lea x(%reg1d,%reg2d),%reg3d
  14835. To:
  14836. lea x(%reg1q,%reg2q),%reg3d
  14837. Reduces the number of bytes of machine code
  14838. }
  14839. if (getsubreg(taicpu(p).oper[1]^.reg)=R_SUBD) and
  14840. (
  14841. (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) or
  14842. (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD)
  14843. ) then
  14844. begin
  14845. DebugMsg(SPeepholeOptimization + 'Changed 32-bit registers in reference to 64-bit (reduces instruction size)', p);
  14846. if (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) then
  14847. setsubreg(taicpu(p).oper[0]^.ref^.base,R_SUBQ);
  14848. if (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD) then
  14849. setsubreg(taicpu(p).oper[0]^.ref^.index,R_SUBQ);
  14850. { No reason to set Result to true }
  14851. end;
  14852. {$endif x86_64}
  14853. hp5:=nil;
  14854. hp6:=nil;
  14855. hp7:=nil;
  14856. hp8:=nil;
  14857. { replace
  14858. leal(q) x(<stackpointer>),<stackpointer>
  14859. <optional .seh_stackalloc ...>
  14860. <optional .seh_endprologue ...>
  14861. call procname
  14862. <optional NOP>
  14863. leal(q) -x(<stackpointer>),<stackpointer>
  14864. <optional VZEROUPPER>
  14865. ret
  14866. by
  14867. jmp procname
  14868. but do it only on level 4 because it destroys stack back traces
  14869. }
  14870. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14871. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14872. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14873. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14874. { the -8, -24, -40 are not required, but bail out early if possible,
  14875. higher values are unlikely }
  14876. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14877. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14878. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14879. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14880. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14881. GetNextInstruction(p, hp1) and
  14882. { Take a copy of hp1 }
  14883. SetAndTest(hp1, hp4) and
  14884. { trick to skip label }
  14885. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14886. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14887. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14888. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14889. SkipSimpleInstructions(hp1) and
  14890. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14891. GetNextInstruction(hp1, hp2) and
  14892. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14893. { skip nop instruction on win64 }
  14894. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14895. SetAndTest(hp2,hp6) and
  14896. GetNextInstruction(hp2,hp2) and
  14897. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14898. ) and
  14899. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14900. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14901. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14902. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14903. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14904. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14905. { Segment register will be NR_NO }
  14906. GetNextInstruction(hp2, hp3) and
  14907. { trick to skip label }
  14908. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14909. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14910. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14911. SetAndTest(hp3,hp5) and
  14912. GetNextInstruction(hp3,hp3) and
  14913. MatchInstruction(hp3,A_RET,[S_NO])
  14914. )
  14915. ) and
  14916. (taicpu(hp3).ops=0) then
  14917. begin
  14918. taicpu(hp1).opcode := A_JMP;
  14919. taicpu(hp1).is_jmp := true;
  14920. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14921. { search for the stackalloc directive and remove it }
  14922. hp7:=tai(p.next);
  14923. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14924. begin
  14925. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14926. begin
  14927. { sanity check }
  14928. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14929. Internalerror(2024012201);
  14930. hp8:=tai(hp7.next);
  14931. RemoveInstruction(tai(hp7));
  14932. hp7:=hp8;
  14933. break;
  14934. end
  14935. else
  14936. hp7:=tai(hp7.next);
  14937. end;
  14938. RemoveCurrentP(p, hp4);
  14939. RemoveInstruction(hp2);
  14940. RemoveInstruction(hp3);
  14941. { if there is a vzeroupper instruction then move it before the jmp }
  14942. if Assigned(hp5) then
  14943. begin
  14944. AsmL.Remove(hp5);
  14945. ASmL.InsertBefore(hp5,hp1)
  14946. end;
  14947. { remove nop on win64 }
  14948. if Assigned(hp6) then
  14949. RemoveInstruction(hp6);
  14950. Result:=true;
  14951. end;
  14952. end;
  14953. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14954. {$ifdef x86_64}
  14955. var
  14956. hp1, hp2, hp3, hp4, hp5: tai;
  14957. {$endif x86_64}
  14958. begin
  14959. Result:=false;
  14960. {$ifdef x86_64}
  14961. hp5:=nil;
  14962. { replace
  14963. push %rax
  14964. call procname
  14965. pop %rcx
  14966. ret
  14967. by
  14968. jmp procname
  14969. but do it only on level 4 because it destroys stack back traces
  14970. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14971. for all supported calling conventions
  14972. }
  14973. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14974. MatchOpType(taicpu(p),top_reg) and
  14975. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14976. GetNextInstruction(p, hp1) and
  14977. { Take a copy of hp1 }
  14978. SetAndTest(hp1, hp4) and
  14979. { trick to skip label }
  14980. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14981. SkipSimpleInstructions(hp1) and
  14982. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14983. GetNextInstruction(hp1, hp2) and
  14984. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14985. MatchOpType(taicpu(hp2),top_reg) and
  14986. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14987. GetNextInstruction(hp2, hp3) and
  14988. { trick to skip label }
  14989. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14990. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14991. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14992. SetAndTest(hp3,hp5) and
  14993. GetNextInstruction(hp3,hp3) and
  14994. MatchInstruction(hp3,A_RET,[S_NO])
  14995. )
  14996. ) and
  14997. (taicpu(hp3).ops=0) then
  14998. begin
  14999. taicpu(hp1).opcode := A_JMP;
  15000. taicpu(hp1).is_jmp := true;
  15001. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  15002. RemoveCurrentP(p, hp4);
  15003. RemoveInstruction(hp2);
  15004. RemoveInstruction(hp3);
  15005. if Assigned(hp5) then
  15006. begin
  15007. AsmL.Remove(hp5);
  15008. ASmL.InsertBefore(hp5,hp1)
  15009. end;
  15010. Result:=true;
  15011. end;
  15012. {$endif x86_64}
  15013. end;
  15014. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  15015. var
  15016. Value, RegName: string;
  15017. hp1: tai;
  15018. begin
  15019. Result:=false;
  15020. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  15021. begin
  15022. case taicpu(p).oper[0]^.val of
  15023. 0:
  15024. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  15025. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15026. (
  15027. { See if we can still convert the instruction }
  15028. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15029. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15030. ) then
  15031. begin
  15032. { change "mov $0,%reg" into "xor %reg,%reg" }
  15033. taicpu(p).opcode := A_XOR;
  15034. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  15035. Result := True;
  15036. {$ifdef x86_64}
  15037. end
  15038. else if (taicpu(p).opsize = S_Q) then
  15039. begin
  15040. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15041. { The actual optimization }
  15042. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15043. taicpu(p).changeopsize(S_L);
  15044. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15045. Result := True;
  15046. end;
  15047. $1..$FFFFFFFF:
  15048. begin
  15049. { Code size reduction by J. Gareth "Kit" Moreton }
  15050. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  15051. case taicpu(p).opsize of
  15052. S_Q:
  15053. begin
  15054. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15055. Value := debug_tostr(taicpu(p).oper[0]^.val);
  15056. { The actual optimization }
  15057. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15058. taicpu(p).changeopsize(S_L);
  15059. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15060. Result := True;
  15061. end;
  15062. else
  15063. { Do nothing };
  15064. end;
  15065. {$endif x86_64}
  15066. end;
  15067. -1:
  15068. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  15069. if (cs_opt_size in current_settings.optimizerswitches) and
  15070. (taicpu(p).opsize <> S_B) and
  15071. (
  15072. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15073. (
  15074. { See if we can still convert the instruction }
  15075. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15076. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15077. )
  15078. ) then
  15079. begin
  15080. { change "mov $-1,%reg" into "or $-1,%reg" }
  15081. { NOTES:
  15082. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  15083. - This operation creates a false dependency on the register, so only do it when optimising for size
  15084. - It is possible to set memory operands using this method, but this creates an even greater false dependency, so don't do this at all
  15085. }
  15086. taicpu(p).opcode := A_OR;
  15087. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  15088. Result := True;
  15089. end;
  15090. else
  15091. { Do nothing };
  15092. end;
  15093. end;
  15094. end;
  15095. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  15096. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  15097. begin
  15098. Result := False;
  15099. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  15100. Exit;
  15101. { For sizes less than S_L, the byte size is equal or larger with BTx,
  15102. so don't bother optimising }
  15103. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  15104. Exit;
  15105. if (taicpu(p).oper[0]^.typ <> top_const) or
  15106. { If the value can fit into an 8-bit signed integer, a smaller
  15107. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  15108. falls within this range }
  15109. (
  15110. (taicpu(p).oper[0]^.val > -128) and
  15111. (taicpu(p).oper[0]^.val <= 127)
  15112. ) then
  15113. Exit;
  15114. { If we're optimising for size, this is acceptable }
  15115. if (cs_opt_size in current_settings.optimizerswitches) then
  15116. Exit(True);
  15117. if (taicpu(p).oper[1]^.typ = top_reg) and
  15118. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15119. Exit(True);
  15120. if (taicpu(p).oper[1]^.typ <> top_reg) and
  15121. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15122. Exit(True);
  15123. end;
  15124. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  15125. var
  15126. hp1: tai;
  15127. Value: TCGInt;
  15128. begin
  15129. Result := False;
  15130. if MatchOpType(taicpu(p), top_const, top_reg) then
  15131. begin
  15132. { Detect:
  15133. andw x, %ax (0 <= x < $8000)
  15134. ...
  15135. movzwl %ax,%eax
  15136. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15137. }
  15138. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15139. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15140. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15141. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15142. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15143. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15144. begin
  15145. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15146. taicpu(hp1).opcode := A_CWDE;
  15147. taicpu(hp1).clearop(0);
  15148. taicpu(hp1).clearop(1);
  15149. taicpu(hp1).ops := 0;
  15150. { A change was made, but not with p, so don't set Result, but
  15151. notify the compiler that a change was made }
  15152. Include(OptsToCheck, aoc_ForceNewIteration);
  15153. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15154. end;
  15155. end;
  15156. { If "not x" is a power of 2 (popcnt = 1), change:
  15157. and $x, %reg/ref
  15158. To:
  15159. btr lb(x), %reg/ref
  15160. }
  15161. if IsBTXAcceptable(p) and
  15162. (
  15163. { Make sure a TEST doesn't follow that plays with the register }
  15164. not GetNextInstruction(p, hp1) or
  15165. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15166. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15167. ) then
  15168. begin
  15169. {$push}{$R-}{$Q-}
  15170. { Value is a sign-extended 32-bit integer - just correct it
  15171. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15172. checks to see if this operand is an immediate. }
  15173. Value := not taicpu(p).oper[0]^.val;
  15174. {$pop}
  15175. {$ifdef x86_64}
  15176. if taicpu(p).opsize = S_L then
  15177. {$endif x86_64}
  15178. Value := Value and $FFFFFFFF;
  15179. if (PopCnt(QWord(Value)) = 1) then
  15180. begin
  15181. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15182. taicpu(p).opcode := A_BTR;
  15183. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15184. Result := True;
  15185. Exit;
  15186. end;
  15187. end;
  15188. end;
  15189. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15190. begin
  15191. Result := False;
  15192. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15193. Exit;
  15194. { Convert:
  15195. movswl %ax,%eax -> cwtl
  15196. movslq %eax,%rax -> cdqe
  15197. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15198. refer to the same opcode and depends only on the assembler's
  15199. current operand-size attribute. [Kit]
  15200. }
  15201. with taicpu(p) do
  15202. case opsize of
  15203. S_WL:
  15204. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15205. begin
  15206. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15207. opcode := A_CWDE;
  15208. clearop(0);
  15209. clearop(1);
  15210. ops := 0;
  15211. Result := True;
  15212. end;
  15213. {$ifdef x86_64}
  15214. S_LQ:
  15215. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15216. begin
  15217. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15218. opcode := A_CDQE;
  15219. clearop(0);
  15220. clearop(1);
  15221. ops := 0;
  15222. Result := True;
  15223. end;
  15224. {$endif x86_64}
  15225. else
  15226. ;
  15227. end;
  15228. end;
  15229. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15230. var
  15231. hp1: tai;
  15232. begin
  15233. Result := False;
  15234. { All these optimisations work on "shr const,%reg" }
  15235. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15236. Exit;
  15237. if HandleSHRMerge(p, True) then
  15238. begin
  15239. Result := True;
  15240. Exit;
  15241. end;
  15242. { Detect the following (looking backwards):
  15243. shr %cl,%reg
  15244. shr x, %reg
  15245. Swap the two SHR instructions to minimise a pipeline stall.
  15246. }
  15247. if GetLastInstruction(p, hp1) and
  15248. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15249. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15250. { First operand will be %cl }
  15251. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15252. { Just to be sure }
  15253. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15254. begin
  15255. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15256. { Moving the entries this way ensures the register tracking remains correct }
  15257. Asml.Remove(p);
  15258. Asml.InsertBefore(p, hp1);
  15259. p := hp1;
  15260. { Don't set Result to True because the current instruction is now
  15261. "shr %cl,%reg" and there's nothing more we can do with it }
  15262. end;
  15263. end;
  15264. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15265. var
  15266. hp1, hp2: tai;
  15267. Opposite, SecondOpposite: TAsmOp;
  15268. NewCond: TAsmCond;
  15269. begin
  15270. Result := False;
  15271. { Change:
  15272. add/sub 128,(dest)
  15273. To:
  15274. sub/add -128,(dest)
  15275. This generaally takes fewer bytes to encode because -128 can be stored
  15276. in a signed byte, whereas +128 cannot.
  15277. }
  15278. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15279. begin
  15280. if taicpu(p).opcode = A_ADD then
  15281. Opposite := A_SUB
  15282. else
  15283. Opposite := A_ADD;
  15284. { Be careful if the flags are in use, because the CF flag inverts
  15285. when changing from ADD to SUB and vice versa }
  15286. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15287. GetNextInstruction(p, hp1) then
  15288. begin
  15289. TransferUsedRegs(TmpUsedRegs);
  15290. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15291. hp2 := hp1;
  15292. { Scan ahead to check if everything's safe }
  15293. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15294. begin
  15295. if (hp1.typ <> ait_instruction) then
  15296. { Probably unsafe since the flags are still in use }
  15297. Exit;
  15298. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15299. { Stop searching at an unconditional jump }
  15300. Break;
  15301. if not
  15302. (
  15303. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15304. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15305. ) and
  15306. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15307. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15308. Exit;
  15309. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15310. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15311. { Move to the next instruction }
  15312. GetNextInstruction(hp1, hp1);
  15313. end;
  15314. while Assigned(hp2) and (hp2 <> hp1) do
  15315. begin
  15316. NewCond := C_None;
  15317. case taicpu(hp2).condition of
  15318. C_A, C_NBE:
  15319. NewCond := C_BE;
  15320. C_B, C_C, C_NAE:
  15321. NewCond := C_AE;
  15322. C_AE, C_NB, C_NC:
  15323. NewCond := C_B;
  15324. C_BE, C_NA:
  15325. NewCond := C_A;
  15326. else
  15327. { No change needed };
  15328. end;
  15329. if NewCond <> C_None then
  15330. begin
  15331. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15332. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15333. taicpu(hp2).condition := NewCond;
  15334. end
  15335. else
  15336. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15337. begin
  15338. { Because of the flipping of the carry bit, to ensure
  15339. the operation remains equivalent, ADC becomes SBB
  15340. and vice versa, and the constant is not-inverted.
  15341. If multiple ADCs or SBBs appear in a row, each one
  15342. changed causes the carry bit to invert, so they all
  15343. need to be flipped }
  15344. if taicpu(hp2).opcode = A_ADC then
  15345. SecondOpposite := A_SBB
  15346. else
  15347. SecondOpposite := A_ADC;
  15348. if taicpu(hp2).oper[0]^.typ <> top_const then
  15349. { Should have broken out of this optimisation already }
  15350. InternalError(2021112901);
  15351. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(hp2).opcode) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' -> ' +
  15352. debug_op2str(SecondOpposite) + debug_opsize2str(taicpu(hp2).opsize) + ' $' + debug_tostr(not taicpu(hp2).oper[0]^.val) + ',' + debug_operstr(taicpu(hp2).oper[1]^) + ' to accommodate inverted carry bit', hp2);
  15353. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15354. taicpu(hp2).opcode := SecondOpposite;
  15355. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15356. end;
  15357. { Move to the next instruction }
  15358. GetNextInstruction(hp2, hp2);
  15359. end;
  15360. if (hp2 <> hp1) then
  15361. InternalError(2021111501);
  15362. end;
  15363. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15364. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15365. taicpu(p).opcode := Opposite;
  15366. taicpu(p).oper[0]^.val := -128;
  15367. { No further optimisations can be made on this instruction, so move
  15368. onto the next one to save time }
  15369. p := tai(p.Next);
  15370. UpdateUsedRegs(p);
  15371. Result := True;
  15372. Exit;
  15373. end;
  15374. { Detect:
  15375. add/sub %reg2,(dest)
  15376. add/sub x, (dest)
  15377. (dest can be a register or a reference)
  15378. Swap the instructions to minimise a pipeline stall. This reverses the
  15379. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15380. optimisations could be made.
  15381. }
  15382. if (taicpu(p).oper[0]^.typ = top_reg) and
  15383. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15384. (
  15385. (
  15386. (taicpu(p).oper[1]^.typ = top_reg) and
  15387. { We can try searching further ahead if we're writing to a register }
  15388. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15389. ) or
  15390. (
  15391. (taicpu(p).oper[1]^.typ = top_ref) and
  15392. GetNextInstruction(p, hp1)
  15393. )
  15394. ) and
  15395. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15396. (taicpu(hp1).oper[0]^.typ = top_const) and
  15397. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15398. begin
  15399. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15400. TransferUsedRegs(TmpUsedRegs);
  15401. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15402. hp2 := p;
  15403. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15404. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15405. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15406. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15407. begin
  15408. asml.remove(hp1);
  15409. asml.InsertBefore(hp1, p);
  15410. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15411. Result := True;
  15412. end;
  15413. end;
  15414. end;
  15415. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15416. var
  15417. hp1: tai;
  15418. begin
  15419. Result:=false;
  15420. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15421. while GetNextInstruction(p, hp1) and
  15422. TrySwapMovCmp(p, hp1) do
  15423. begin
  15424. if MatchInstruction(hp1, A_MOV, []) then
  15425. begin
  15426. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15427. begin
  15428. { A little hacky, but since CMP doesn't read the flags, only
  15429. modify them, it's safe if they get scrambled by MOV -> XOR }
  15430. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15431. Result := PostPeepholeOptMov(hp1);
  15432. {$ifdef x86_64}
  15433. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15434. { Used to shrink instruction size }
  15435. PostPeepholeOptXor(hp1);
  15436. {$endif x86_64}
  15437. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15438. end
  15439. else
  15440. begin
  15441. Result := PostPeepholeOptMov(hp1);
  15442. {$ifdef x86_64}
  15443. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15444. { Used to shrink instruction size }
  15445. PostPeepholeOptXor(hp1);
  15446. {$endif x86_64}
  15447. end;
  15448. end;
  15449. { Enabling this flag is actually a null operation, but it marks
  15450. the code as 'modified' during this pass }
  15451. Include(OptsToCheck, aoc_ForceNewIteration);
  15452. end;
  15453. { change "cmp $0, %reg" to "test %reg, %reg" }
  15454. if MatchOpType(taicpu(p),top_const,top_reg) and
  15455. (taicpu(p).oper[0]^.val = 0) then
  15456. begin
  15457. taicpu(p).opcode := A_TEST;
  15458. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15459. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15460. Result:=true;
  15461. end;
  15462. end;
  15463. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15464. var
  15465. IsTestConstX, IsValid : Boolean;
  15466. hp1,hp2 : tai;
  15467. begin
  15468. Result:=false;
  15469. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15470. if (taicpu(p).opcode = A_TEST) then
  15471. while GetNextInstruction(p, hp1) and
  15472. TrySwapMovCmp(p, hp1) do
  15473. begin
  15474. if MatchInstruction(hp1, A_MOV, []) then
  15475. begin
  15476. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15477. begin
  15478. { A little hacky, but since TEST doesn't read the flags, only
  15479. modify them, it's safe if they get scrambled by MOV -> XOR }
  15480. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15481. Result := PostPeepholeOptMov(hp1);
  15482. {$ifdef x86_64}
  15483. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15484. { Used to shrink instruction size }
  15485. PostPeepholeOptXor(hp1);
  15486. {$endif x86_64}
  15487. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15488. end
  15489. else
  15490. begin
  15491. Result := PostPeepholeOptMov(hp1);
  15492. {$ifdef x86_64}
  15493. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15494. { Used to shrink instruction size }
  15495. PostPeepholeOptXor(hp1);
  15496. {$endif x86_64}
  15497. end;
  15498. end;
  15499. { Enabling this flag is actually a null operation, but it marks
  15500. the code as 'modified' during this pass }
  15501. Include(OptsToCheck, aoc_ForceNewIteration);
  15502. end;
  15503. { If x is a power of 2 (popcnt = 1), change:
  15504. or $x, %reg/ref
  15505. To:
  15506. bts lb(x), %reg/ref
  15507. }
  15508. if (taicpu(p).opcode = A_OR) and
  15509. IsBTXAcceptable(p) and
  15510. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15511. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15512. (
  15513. { Don't optimise if a test instruction follows }
  15514. not GetNextInstruction(p, hp1) or
  15515. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15516. ) then
  15517. begin
  15518. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  15519. taicpu(p).opcode := A_BTS;
  15520. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15521. Result := True;
  15522. Exit;
  15523. end;
  15524. { If x is a power of 2 (popcnt = 1), change:
  15525. test $x, %reg/ref
  15526. je / sete / cmove (or jne / setne)
  15527. To:
  15528. bt lb(x), %reg/ref
  15529. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15530. }
  15531. if (taicpu(p).opcode = A_TEST) and
  15532. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15533. (taicpu(p).oper[0]^.typ = top_const) and
  15534. (
  15535. (cs_opt_size in current_settings.optimizerswitches) or
  15536. (
  15537. (taicpu(p).oper[1]^.typ = top_reg) and
  15538. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15539. ) or
  15540. (
  15541. (taicpu(p).oper[1]^.typ <> top_reg) and
  15542. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15543. )
  15544. ) and
  15545. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15546. { For sizes less than S_L, the byte size is equal or larger with BT,
  15547. so don't bother optimising }
  15548. (taicpu(p).opsize >= S_L) then
  15549. begin
  15550. IsValid := True;
  15551. { Check the next set of instructions, watching the FLAGS register
  15552. and the conditions used }
  15553. TransferUsedRegs(TmpUsedRegs);
  15554. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15555. hp1 := p;
  15556. hp2 := nil;
  15557. while GetNextInstruction(hp1, hp1) do
  15558. begin
  15559. if not Assigned(hp2) then
  15560. { The first instruction after TEST }
  15561. hp2 := hp1;
  15562. if (hp1.typ <> ait_instruction) then
  15563. begin
  15564. { If the flags are no longer in use, everything is fine }
  15565. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15566. IsValid := False;
  15567. Break;
  15568. end;
  15569. case taicpu(hp1).condition of
  15570. C_None:
  15571. begin
  15572. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15573. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15574. { Something is not quite normal, so play safe and don't change }
  15575. IsValid := False;
  15576. Break;
  15577. end;
  15578. C_E, C_Z, C_NE, C_NZ:
  15579. { This is fine };
  15580. else
  15581. begin
  15582. { Unsupported condition }
  15583. IsValid := False;
  15584. Break;
  15585. end;
  15586. end;
  15587. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15588. end;
  15589. if IsValid then
  15590. begin
  15591. while hp2 <> hp1 do
  15592. begin
  15593. case taicpu(hp2).condition of
  15594. C_Z, C_E:
  15595. taicpu(hp2).condition := C_NC;
  15596. C_NZ, C_NE:
  15597. taicpu(hp2).condition := C_C;
  15598. else
  15599. { Should not get this by this point }
  15600. InternalError(2022110701);
  15601. end;
  15602. GetNextInstruction(hp2, hp2);
  15603. end;
  15604. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  15605. taicpu(p).opcode := A_BT;
  15606. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15607. Result := True;
  15608. Exit;
  15609. end;
  15610. end;
  15611. { removes the line marked with (x) from the sequence
  15612. and/or/xor/add/sub/... $x, %y
  15613. test/or %y, %y | test $-1, %y (x)
  15614. j(n)z _Label
  15615. as the first instruction already adjusts the ZF
  15616. %y operand may also be a reference }
  15617. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15618. MatchOperand(taicpu(p).oper[0]^,-1);
  15619. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15620. GetLastInstruction(p, hp1) and
  15621. (tai(hp1).typ = ait_instruction) and
  15622. GetNextInstruction(p,hp2) and
  15623. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15624. case taicpu(hp1).opcode Of
  15625. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15626. { These two instructions set the zero flag if the result is zero }
  15627. A_POPCNT, A_LZCNT:
  15628. begin
  15629. if (
  15630. { With POPCNT, an input of zero will set the zero flag
  15631. because the population count of zero is zero }
  15632. (taicpu(hp1).opcode = A_POPCNT) and
  15633. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15634. (
  15635. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15636. { Faster than going through the second half of the 'or'
  15637. condition below }
  15638. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15639. )
  15640. ) or (
  15641. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15642. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15643. { and in case of carry for A(E)/B(E)/C/NC }
  15644. (
  15645. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15646. (
  15647. (taicpu(hp1).opcode <> A_ADD) and
  15648. (taicpu(hp1).opcode <> A_SUB) and
  15649. (taicpu(hp1).opcode <> A_LZCNT)
  15650. )
  15651. )
  15652. ) then
  15653. begin
  15654. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15655. RemoveCurrentP(p, hp2);
  15656. Result:=true;
  15657. Exit;
  15658. end;
  15659. end;
  15660. A_SHL, A_SAL, A_SHR, A_SAR:
  15661. begin
  15662. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15663. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15664. { therefore, it's only safe to do this optimization for }
  15665. { shifts by a (nonzero) constant }
  15666. (taicpu(hp1).oper[0]^.typ = top_const) and
  15667. (taicpu(hp1).oper[0]^.val <> 0) and
  15668. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15669. { and in case of carry for A(E)/B(E)/C/NC }
  15670. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15671. begin
  15672. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15673. RemoveCurrentP(p, hp2);
  15674. Result:=true;
  15675. Exit;
  15676. end;
  15677. end;
  15678. A_DEC, A_INC, A_NEG:
  15679. begin
  15680. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15681. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15682. { and in case of carry for A(E)/B(E)/C/NC }
  15683. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15684. begin
  15685. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15686. RemoveCurrentP(p, hp2);
  15687. Result:=true;
  15688. Exit;
  15689. end;
  15690. end;
  15691. A_ANDN, A_BZHI:
  15692. begin
  15693. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15694. { Only the zero and sign flags are consistent with what the result is }
  15695. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15696. begin
  15697. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15698. RemoveCurrentP(p, hp2);
  15699. Result:=true;
  15700. Exit;
  15701. end;
  15702. end;
  15703. A_BEXTR:
  15704. begin
  15705. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15706. { Only the zero flag is set }
  15707. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15708. begin
  15709. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15710. RemoveCurrentP(p, hp2);
  15711. Result:=true;
  15712. Exit;
  15713. end;
  15714. end;
  15715. else
  15716. ;
  15717. end; { case }
  15718. { change "test $-1,%reg" into "test %reg,%reg" }
  15719. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15720. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15721. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15722. if MatchInstruction(p, A_OR, []) and
  15723. { Can only match if they're both registers }
  15724. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15725. begin
  15726. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15727. taicpu(p).opcode := A_TEST;
  15728. { No need to set Result to True, as we've done all the optimisations we can }
  15729. end;
  15730. end;
  15731. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15732. var
  15733. hp1,hp3 : tai;
  15734. {$ifndef x86_64}
  15735. hp2 : taicpu;
  15736. {$endif x86_64}
  15737. begin
  15738. Result:=false;
  15739. hp3:=nil;
  15740. {$ifndef x86_64}
  15741. { don't do this on modern CPUs, this really hurts them due to
  15742. broken call/ret pairing }
  15743. if (current_settings.optimizecputype < cpu_Pentium2) and
  15744. not(cs_create_pic in current_settings.moduleswitches) and
  15745. GetNextInstruction(p, hp1) and
  15746. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15747. MatchOpType(taicpu(hp1),top_ref) and
  15748. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15749. begin
  15750. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15751. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15752. InsertLLItem(p.previous, p, hp2);
  15753. taicpu(p).opcode := A_JMP;
  15754. taicpu(p).is_jmp := true;
  15755. RemoveInstruction(hp1);
  15756. Result:=true;
  15757. end
  15758. else
  15759. {$endif x86_64}
  15760. { replace
  15761. call procname
  15762. ret
  15763. by
  15764. jmp procname
  15765. but do it only on level 4 because it destroys stack back traces
  15766. else if the subroutine is marked as no return, remove the ret
  15767. }
  15768. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15769. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15770. GetNextInstruction(p, hp1) and
  15771. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15772. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15773. SetAndTest(hp1,hp3) and
  15774. GetNextInstruction(hp1,hp1) and
  15775. MatchInstruction(hp1,A_RET,[S_NO])
  15776. )
  15777. ) and
  15778. (taicpu(hp1).ops=0) then
  15779. begin
  15780. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15781. { we might destroy stack alignment here if we do not do a call }
  15782. (target_info.stackalign<=sizeof(SizeUInt)) then
  15783. begin
  15784. taicpu(p).opcode := A_JMP;
  15785. taicpu(p).is_jmp := true;
  15786. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15787. end
  15788. else
  15789. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15790. RemoveInstruction(hp1);
  15791. if Assigned(hp3) then
  15792. begin
  15793. AsmL.Remove(hp3);
  15794. AsmL.InsertBefore(hp3,p)
  15795. end;
  15796. Result:=true;
  15797. end;
  15798. end;
  15799. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15800. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15801. begin
  15802. case OpSize of
  15803. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15804. Result := (Val <= $FF) and (Val >= -128);
  15805. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15806. Result := (Val <= $FFFF) and (Val >= -32768);
  15807. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15808. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15809. else
  15810. Result := True;
  15811. end;
  15812. end;
  15813. var
  15814. hp1, hp2 : tai;
  15815. SizeChange: Boolean;
  15816. PreMessage: string;
  15817. begin
  15818. Result := False;
  15819. if (taicpu(p).oper[0]^.typ = top_reg) and
  15820. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15821. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15822. begin
  15823. { Change (using movzbl %al,%eax as an example):
  15824. movzbl %al, %eax movzbl %al, %eax
  15825. cmpl x, %eax testl %eax,%eax
  15826. To:
  15827. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15828. movzbl %al, %eax movzbl %al, %eax
  15829. Smaller instruction and minimises pipeline stall as the CPU
  15830. doesn't have to wait for the register to get zero-extended. [Kit]
  15831. Also allow if the smaller of the two registers is being checked,
  15832. as this still removes the false dependency.
  15833. }
  15834. if
  15835. (
  15836. (
  15837. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15838. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15839. ) or (
  15840. { If MatchOperand returns True, they must both be registers }
  15841. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15842. )
  15843. ) and
  15844. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15845. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15846. begin
  15847. PreMessage := debug_op2str(taicpu(hp1).opcode) + debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' -> ' + debug_op2str(taicpu(hp1).opcode);
  15848. asml.Remove(hp1);
  15849. asml.InsertBefore(hp1, p);
  15850. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15851. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15852. begin
  15853. taicpu(hp1).opcode := A_TEST;
  15854. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15855. end;
  15856. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15857. case taicpu(p).opsize of
  15858. S_BW, S_BL:
  15859. begin
  15860. SizeChange := taicpu(hp1).opsize <> S_B;
  15861. taicpu(hp1).changeopsize(S_B);
  15862. end;
  15863. S_WL:
  15864. begin
  15865. SizeChange := taicpu(hp1).opsize <> S_W;
  15866. taicpu(hp1).changeopsize(S_W);
  15867. end
  15868. else
  15869. InternalError(2020112701);
  15870. end;
  15871. UpdateUsedRegs(tai(p.Next));
  15872. { Check if the register is used aferwards - if not, we can
  15873. remove the movzx instruction completely }
  15874. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15875. begin
  15876. { Hp1 is a better position than p for debugging purposes }
  15877. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15878. RemoveCurrentp(p, hp1);
  15879. Result := True;
  15880. end;
  15881. if SizeChange then
  15882. DebugMsg(SPeepholeOptimization + PreMessage +
  15883. debug_opsize2str(taicpu(hp1).opsize) + ' ' + debug_operstr(taicpu(hp1).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (smaller and minimises pipeline stall - MovzxCmp2CmpMovzx)', hp1)
  15884. else
  15885. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15886. Exit;
  15887. end;
  15888. { Change (using movzwl %ax,%eax as an example):
  15889. movzwl %ax, %eax
  15890. movb %al, (dest) (Register is smaller than read register in movz)
  15891. To:
  15892. movb %al, (dest) (Move one back to avoid a false dependency)
  15893. movzwl %ax, %eax
  15894. }
  15895. if (taicpu(hp1).opcode = A_MOV) and
  15896. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15897. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15898. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15899. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15900. begin
  15901. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15902. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15903. asml.Remove(hp1);
  15904. asml.InsertBefore(hp1, p);
  15905. if taicpu(hp1).oper[1]^.typ = top_reg then
  15906. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15907. { Check if the register is used aferwards - if not, we can
  15908. remove the movzx instruction completely }
  15909. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15910. begin
  15911. { Hp1 is a better position than p for debugging purposes }
  15912. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15913. RemoveCurrentp(p, hp1);
  15914. Result := True;
  15915. end;
  15916. Exit;
  15917. end;
  15918. end;
  15919. end;
  15920. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15921. var
  15922. hp1: tai;
  15923. {$ifdef x86_64}
  15924. PreMessage, RegName: string;
  15925. {$endif x86_64}
  15926. begin
  15927. Result := False;
  15928. { If x is a power of 2 (popcnt = 1), change:
  15929. xor $x, %reg/ref
  15930. To:
  15931. btc lb(x), %reg/ref
  15932. }
  15933. if IsBTXAcceptable(p) and
  15934. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15935. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15936. (
  15937. { Don't optimise if a test instruction follows }
  15938. not GetNextInstruction(p, hp1) or
  15939. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15940. ) then
  15941. begin
  15942. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  15943. taicpu(p).opcode := A_BTC;
  15944. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15945. Result := True;
  15946. Exit;
  15947. end;
  15948. {$ifdef x86_64}
  15949. { Code size reduction by J. Gareth "Kit" Moreton }
  15950. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15951. as this removes the REX prefix }
  15952. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15953. Exit;
  15954. if taicpu(p).oper[0]^.typ <> top_reg then
  15955. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15956. InternalError(2018011500);
  15957. case taicpu(p).opsize of
  15958. S_Q:
  15959. begin
  15960. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15961. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15962. { The actual optimization }
  15963. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15964. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15965. taicpu(p).changeopsize(S_L);
  15966. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15967. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15968. end;
  15969. else
  15970. ;
  15971. end;
  15972. {$endif x86_64}
  15973. end;
  15974. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15975. var
  15976. XReg: TRegister;
  15977. begin
  15978. Result := False;
  15979. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15980. Smaller encoding and slightly faster on some platforms (also works for
  15981. ZMM-sized registers) }
  15982. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15983. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15984. begin
  15985. XReg := taicpu(p).oper[0]^.reg;
  15986. if (taicpu(p).oper[1]^.reg = XReg) then
  15987. begin
  15988. taicpu(p).changeopsize(S_XMM);
  15989. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15990. if (cs_opt_size in current_settings.optimizerswitches) then
  15991. begin
  15992. { Change input registers to %xmm0 to reduce size. Note that
  15993. there's a risk of a false dependency doing this, so only
  15994. optimise for size here }
  15995. XReg := NR_XMM0;
  15996. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15997. end
  15998. else
  15999. begin
  16000. setsubreg(XReg, R_SUBMMX);
  16001. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  16002. end;
  16003. taicpu(p).oper[0]^.reg := XReg;
  16004. taicpu(p).oper[1]^.reg := XReg;
  16005. Result := True;
  16006. end;
  16007. end;
  16008. end;
  16009. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  16010. var
  16011. hp1, p_new: tai;
  16012. begin
  16013. Result := False;
  16014. { Check for:
  16015. ret
  16016. .Lbl:
  16017. ret
  16018. Remove first 'ret'
  16019. }
  16020. if GetNextInstruction(p, hp1) and
  16021. { Remember where the label is }
  16022. SetAndTest(hp1, p_new) and
  16023. (hp1.typ in [ait_align, ait_label]) and
  16024. SkipLabels(hp1, hp1) and
  16025. MatchInstruction(hp1, A_RET, []) and
  16026. { To be safe, make sure the RET instructions are identical }
  16027. (taicpu(p).ops = taicpu(hp1).ops) and
  16028. (
  16029. (taicpu(p).ops = 0) or
  16030. (
  16031. (taicpu(p).ops = 1) and
  16032. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  16033. )
  16034. ) then
  16035. begin
  16036. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  16037. UpdateUsedRegs(tai(p.Next));
  16038. RemoveCurrentP(p, p_new);
  16039. Result := True;
  16040. Exit;
  16041. end;
  16042. end;
  16043. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  16044. var
  16045. OperIdx: Integer;
  16046. begin
  16047. for OperIdx := 0 to p.ops - 1 do
  16048. if p.oper[OperIdx]^.typ = top_ref then
  16049. optimize_ref(p.oper[OperIdx]^.ref^, False);
  16050. end;
  16051. end.