aoptx86.pas 764 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802
  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. exit;
  4161. end
  4162. else
  4163. begin
  4164. TransferUsedRegs(TmpUsedRegs);
  4165. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4166. if (taicpu(p).oper[1]^.typ = top_ref) and
  4167. { mov reg1, mem1
  4168. mov mem2, reg1 }
  4169. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4170. GetNextInstruction(hp1, hp2) and
  4171. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4172. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4173. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4174. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4175. { change to
  4176. mov reg1, mem1 mov reg1, mem1
  4177. mov mem2, reg1 cmp reg1, mem2
  4178. cmp mem1, reg1
  4179. }
  4180. begin
  4181. RemoveInstruction(hp2);
  4182. taicpu(hp1).opcode := A_CMP;
  4183. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4184. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4185. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4186. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4187. end;
  4188. end;
  4189. end
  4190. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4191. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4192. begin
  4193. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4194. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4195. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4196. end
  4197. else
  4198. begin
  4199. TransferUsedRegs(TmpUsedRegs);
  4200. if GetNextInstruction(hp1, hp2) and
  4201. MatchOpType(taicpu(p),top_ref,top_reg) and
  4202. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4203. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4204. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4205. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4206. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4207. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4208. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4209. { mov mem1, %reg1
  4210. mov %reg1, mem2
  4211. mov mem2, reg2
  4212. to:
  4213. mov mem1, reg2
  4214. mov reg2, mem2}
  4215. begin
  4216. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4217. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4218. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4219. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4220. RemoveInstruction(hp2);
  4221. Result := True;
  4222. end
  4223. {$ifdef i386}
  4224. { this is enabled for i386 only, as the rules to create the reg sets below
  4225. are too complicated for x86-64, so this makes this code too error prone
  4226. on x86-64
  4227. }
  4228. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4229. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4230. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4231. { mov mem1, reg1 mov mem1, reg1
  4232. mov reg1, mem2 mov reg1, mem2
  4233. mov mem2, reg2 mov mem2, reg1
  4234. to: to:
  4235. mov mem1, reg1 mov mem1, reg1
  4236. mov mem1, reg2 mov reg1, mem2
  4237. mov reg1, mem2
  4238. or (if mem1 depends on reg1
  4239. and/or if mem2 depends on reg2)
  4240. to:
  4241. mov mem1, reg1
  4242. mov reg1, mem2
  4243. mov reg1, reg2
  4244. }
  4245. begin
  4246. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4247. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4248. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4249. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4250. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4251. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4252. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4253. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4254. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4255. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4256. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4257. end
  4258. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4259. begin
  4260. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4261. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4262. end
  4263. else
  4264. begin
  4265. RemoveInstruction(hp2);
  4266. end
  4267. {$endif i386}
  4268. ;
  4269. end;
  4270. end
  4271. { movl [mem1],reg1
  4272. movl [mem1],reg2
  4273. to
  4274. movl [mem1],reg1
  4275. movl reg1,reg2
  4276. }
  4277. else if not CheckMovMov2MovMov2(p, hp1) and
  4278. { movl const1,[mem1]
  4279. movl [mem1],reg1
  4280. to
  4281. movl const1,reg1
  4282. movl reg1,[mem1]
  4283. }
  4284. MatchOpType(Taicpu(p),top_const,top_ref) and
  4285. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4286. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4287. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4288. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4289. begin
  4290. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4291. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4292. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4293. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4294. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4295. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4296. Result:=true;
  4297. exit;
  4298. end;
  4299. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4300. end;
  4301. { search further than the next instruction for a mov (as long as it's not a jump) }
  4302. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4303. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4304. (taicpu(p).oper[1]^.typ = top_reg) and
  4305. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4306. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4307. begin
  4308. { we work with hp2 here, so hp1 can be still used later on when
  4309. checking for GetNextInstruction_p }
  4310. hp3 := hp1;
  4311. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4312. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4313. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4314. TransferUsedRegs(TmpUsedRegs);
  4315. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4316. if NotFirstIteration then
  4317. JumpTracking := TLinkedList.Create
  4318. else
  4319. JumpTracking := nil;
  4320. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4321. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4322. (hp2.typ=ait_instruction) do
  4323. begin
  4324. case taicpu(hp2).opcode of
  4325. A_POP:
  4326. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4327. begin
  4328. if not CrossJump and
  4329. not RegUsedBetween(p_TargetReg, p, hp2) then
  4330. begin
  4331. { We can remove the original MOV since the register
  4332. wasn't used between it and its popping from the stack }
  4333. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4334. RemoveCurrentp(p, hp1);
  4335. Result := True;
  4336. JumpTracking.Free;
  4337. Exit;
  4338. end;
  4339. { Can't go any further }
  4340. Break;
  4341. end;
  4342. A_MOV:
  4343. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4344. ((taicpu(p).oper[0]^.typ=top_const) or
  4345. ((taicpu(p).oper[0]^.typ=top_reg) and
  4346. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4347. )
  4348. ) then
  4349. begin
  4350. { we have
  4351. mov x, %treg
  4352. mov %treg, y
  4353. }
  4354. { We don't need to call UpdateUsedRegs for every instruction between
  4355. p and hp2 because the register we're concerned about will not
  4356. become deallocated (otherwise GetNextInstructionUsingReg would
  4357. have stopped at an earlier instruction). [Kit] }
  4358. TempRegUsed :=
  4359. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4360. RegReadByInstruction(p_TargetReg, hp3) or
  4361. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4362. case taicpu(p).oper[0]^.typ Of
  4363. top_reg:
  4364. begin
  4365. { change
  4366. mov %reg, %treg
  4367. mov %treg, y
  4368. to
  4369. mov %reg, y
  4370. }
  4371. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4372. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4373. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4374. begin
  4375. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4376. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4377. if TempRegUsed then
  4378. begin
  4379. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4380. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4381. { Set the start of the next GetNextInstructionUsingRegCond search
  4382. to start at the entry right before hp2 (which is about to be removed) }
  4383. hp3 := tai(hp2.Previous);
  4384. RemoveInstruction(hp2);
  4385. Include(OptsToCheck, aoc_ForceNewIteration);
  4386. { See if there's more we can optimise }
  4387. Continue;
  4388. end
  4389. else
  4390. begin
  4391. RemoveInstruction(hp2);
  4392. { We can remove the original MOV too }
  4393. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4394. RemoveCurrentP(p, hp1);
  4395. Result:=true;
  4396. JumpTracking.Free;
  4397. Exit;
  4398. end;
  4399. end
  4400. else
  4401. begin
  4402. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4403. taicpu(hp2).loadReg(0, p_SourceReg);
  4404. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4405. { Check to see if the register also appears in the reference }
  4406. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4407. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4408. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4409. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4410. begin
  4411. { Don't remove the first instruction if the temporary register is in use }
  4412. if not TempRegUsed then
  4413. begin
  4414. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4415. RemoveCurrentP(p, hp1);
  4416. Result:=true;
  4417. JumpTracking.Free;
  4418. Exit;
  4419. end;
  4420. { No need to set Result to True here. If there's another instruction later
  4421. on that can be optimised, it will be detected when the main Pass 1 loop
  4422. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4423. hp3 := hp2;
  4424. Continue;
  4425. end;
  4426. end;
  4427. end;
  4428. top_const:
  4429. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4430. begin
  4431. { change
  4432. mov const, %treg
  4433. mov %treg, y
  4434. to
  4435. mov const, y
  4436. }
  4437. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4438. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4439. begin
  4440. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4441. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4442. if TempRegUsed then
  4443. begin
  4444. { Don't remove the first instruction if the temporary register is in use }
  4445. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4446. { No need to set Result to True. If there's another instruction later on
  4447. that can be optimised, it will be detected when the main Pass 1 loop
  4448. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4449. end
  4450. else
  4451. begin
  4452. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4453. RemoveCurrentP(p, hp1);
  4454. Result:=true;
  4455. Exit;
  4456. end;
  4457. end;
  4458. end;
  4459. else
  4460. Internalerror(2019103001);
  4461. end;
  4462. end
  4463. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4464. begin
  4465. if not CrossJump and
  4466. not RegUsedBetween(p_TargetReg, p, hp2) and
  4467. not RegReadByInstruction(p_TargetReg, hp2) then
  4468. begin
  4469. { Register is not used before it is overwritten }
  4470. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4471. RemoveCurrentp(p, hp1);
  4472. Result := True;
  4473. Exit;
  4474. end;
  4475. if (taicpu(p).oper[0]^.typ = top_const) and
  4476. (taicpu(hp2).oper[0]^.typ = top_const) then
  4477. begin
  4478. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4479. begin
  4480. { Same value - register hasn't changed }
  4481. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4482. RemoveInstruction(hp2);
  4483. Include(OptsToCheck, aoc_ForceNewIteration);
  4484. { See if there's more we can optimise }
  4485. Continue;
  4486. end;
  4487. end;
  4488. {$ifdef x86_64}
  4489. end
  4490. { Change:
  4491. movl %reg1l,%reg2l
  4492. ...
  4493. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4494. To:
  4495. movl %reg1l,%reg2l
  4496. ...
  4497. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4498. If %reg1 = %reg3, convert to:
  4499. movl %reg1l,%reg2l
  4500. ...
  4501. andl %reg1l,%reg1l
  4502. }
  4503. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4504. (taicpu(p).oper[0]^.typ = top_reg) and
  4505. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4506. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4507. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4508. begin
  4509. TempRegUsed :=
  4510. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4511. RegReadByInstruction(p_TargetReg, hp3) or
  4512. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4513. taicpu(hp2).opsize := S_L;
  4514. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4515. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4516. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4517. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4518. begin
  4519. { %reg1 = %reg3 }
  4520. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4521. taicpu(hp2).opcode := A_AND;
  4522. end
  4523. else
  4524. begin
  4525. { %reg1 <> %reg3 }
  4526. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4527. end;
  4528. if not TempRegUsed then
  4529. begin
  4530. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4531. RemoveCurrentP(p, hp1);
  4532. Result := True;
  4533. Exit;
  4534. end
  4535. else
  4536. begin
  4537. { Initial instruction wasn't actually changed }
  4538. Include(OptsToCheck, aoc_ForceNewIteration);
  4539. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4540. appears below since %reg1 has technically changed }
  4541. if taicpu(hp2).opcode = A_AND then
  4542. Break;
  4543. end;
  4544. {$endif x86_64}
  4545. end
  4546. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4547. GetNextInstruction(hp2, hp4) and
  4548. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4549. { Optimise the following first:
  4550. movl [mem1],reg1
  4551. movl [mem1],reg2
  4552. to
  4553. movl [mem1],reg1
  4554. movl reg1,reg2
  4555. If [mem1] contains the target register and reg1 is the
  4556. the source register, this optimisation will get missed
  4557. and produce less efficient code later on.
  4558. }
  4559. if CheckMovMov2MovMov2(hp2, hp4) then
  4560. { Initial instruction wasn't actually changed }
  4561. Include(OptsToCheck, aoc_ForceNewIteration);
  4562. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4563. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4564. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4565. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4566. begin
  4567. {
  4568. Change from:
  4569. mov ###, %reg
  4570. ...
  4571. movs/z %reg,%reg (Same register, just different sizes)
  4572. To:
  4573. movs/z ###, %reg (Longer version)
  4574. ...
  4575. (remove)
  4576. }
  4577. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4578. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4579. { Keep the first instruction as mov if ### is a constant }
  4580. if taicpu(p).oper[0]^.typ = top_const then
  4581. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4582. else
  4583. begin
  4584. taicpu(p).opcode := taicpu(hp2).opcode;
  4585. taicpu(p).opsize := taicpu(hp2).opsize;
  4586. end;
  4587. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4588. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4589. RemoveInstruction(hp2);
  4590. Result := True;
  4591. JumpTracking.Free;
  4592. Exit;
  4593. end;
  4594. else
  4595. { Move down to the if-block below };
  4596. end;
  4597. { Also catches MOV/S/Z instructions that aren't modified }
  4598. if taicpu(p).oper[0]^.typ = top_reg then
  4599. begin
  4600. p_SourceReg := taicpu(p).oper[0]^.reg;
  4601. if
  4602. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4603. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4604. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4605. begin
  4606. Result := True;
  4607. { Just in case something didn't get modified (e.g. an
  4608. implicit register). Also, if it does read from this
  4609. register, then there's no longer an advantage to
  4610. changing the register on subsequent instructions.}
  4611. if not RegReadByInstruction(p_TargetReg, hp2) then
  4612. begin
  4613. { If a conditional jump was crossed, do not delete
  4614. the original MOV no matter what }
  4615. if not CrossJump and
  4616. { RegEndOfLife returns True if the register is
  4617. deallocated before the next instruction or has
  4618. been loaded with a new value }
  4619. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4620. begin
  4621. { We can remove the original MOV }
  4622. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4623. RemoveCurrentp(p, hp1);
  4624. JumpTracking.Free;
  4625. Result := True;
  4626. Exit;
  4627. end;
  4628. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4629. begin
  4630. { See if there's more we can optimise }
  4631. hp3 := hp2;
  4632. Continue;
  4633. end;
  4634. end;
  4635. end;
  4636. end;
  4637. { Break out of the while loop under normal circumstances }
  4638. Break;
  4639. end;
  4640. JumpTracking.Free;
  4641. end;
  4642. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4643. (taicpu(p).oper[1]^.typ = top_reg) and
  4644. (taicpu(p).opsize = S_L) and
  4645. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4646. (hp2.typ = ait_instruction) and
  4647. (taicpu(hp2).opcode = A_AND) and
  4648. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4649. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4650. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4651. ) then
  4652. begin
  4653. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4654. begin
  4655. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4656. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4657. begin
  4658. { Optimize out:
  4659. mov x, %reg
  4660. and ffffffffh, %reg
  4661. }
  4662. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4663. RemoveInstruction(hp2);
  4664. Result:=true;
  4665. exit;
  4666. end;
  4667. end;
  4668. end;
  4669. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4670. x >= RetOffset) as it doesn't do anything (it writes either to a
  4671. parameter or to the temporary storage room for the function
  4672. result)
  4673. }
  4674. if IsExitCode(hp1) and
  4675. (taicpu(p).oper[1]^.typ = top_ref) and
  4676. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4677. (
  4678. (
  4679. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4680. not (
  4681. assigned(current_procinfo.procdef.funcretsym) and
  4682. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4683. )
  4684. ) or
  4685. { Also discard writes to the stack that are below the base pointer,
  4686. as this is temporary storage rather than a function result on the
  4687. stack, say. }
  4688. (
  4689. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4690. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4691. )
  4692. ) then
  4693. begin
  4694. RemoveCurrentp(p, hp1);
  4695. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4696. RemoveLastDeallocForFuncRes(p);
  4697. Result:=true;
  4698. exit;
  4699. end;
  4700. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4701. begin
  4702. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4703. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4704. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4705. begin
  4706. { change
  4707. mov reg1, mem1
  4708. test/cmp x, mem1
  4709. to
  4710. mov reg1, mem1
  4711. test/cmp x, reg1
  4712. }
  4713. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4714. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4715. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4716. Result := True;
  4717. Exit;
  4718. end;
  4719. if DoMovCmpMemOpt(p, hp1) then
  4720. begin
  4721. Result := True;
  4722. Exit;
  4723. end;
  4724. end;
  4725. if (taicpu(p).oper[1]^.typ = top_reg) and
  4726. (hp1.typ = ait_instruction) and
  4727. GetNextInstruction(hp1, hp2) and
  4728. MatchInstruction(hp2,A_MOV,[]) and
  4729. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4730. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4731. (
  4732. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4733. {$ifdef x86_64}
  4734. or
  4735. (
  4736. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4737. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4738. )
  4739. {$endif x86_64}
  4740. ) then
  4741. begin
  4742. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4743. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4744. { change movsX/movzX reg/ref, reg2
  4745. add/sub/or/... reg3/$const, reg2
  4746. mov reg2 reg/ref
  4747. dealloc reg2
  4748. to
  4749. add/sub/or/... reg3/$const, reg/ref }
  4750. begin
  4751. TransferUsedRegs(TmpUsedRegs);
  4752. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4753. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4754. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4755. begin
  4756. { by example:
  4757. movswl %si,%eax movswl %si,%eax p
  4758. decl %eax addl %edx,%eax hp1
  4759. movw %ax,%si movw %ax,%si hp2
  4760. ->
  4761. movswl %si,%eax movswl %si,%eax p
  4762. decw %eax addw %edx,%eax hp1
  4763. movw %ax,%si movw %ax,%si hp2
  4764. }
  4765. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4766. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4767. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4768. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4769. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4770. {
  4771. ->
  4772. movswl %si,%eax movswl %si,%eax p
  4773. decw %si addw %dx,%si hp1
  4774. movw %ax,%si movw %ax,%si hp2
  4775. }
  4776. case taicpu(hp1).ops of
  4777. 1:
  4778. begin
  4779. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4780. if taicpu(hp1).oper[0]^.typ=top_reg then
  4781. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4782. end;
  4783. 2:
  4784. begin
  4785. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4786. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4787. (taicpu(hp1).opcode<>A_SHL) and
  4788. (taicpu(hp1).opcode<>A_SHR) and
  4789. (taicpu(hp1).opcode<>A_SAR) then
  4790. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4791. end;
  4792. else
  4793. internalerror(2008042701);
  4794. end;
  4795. {
  4796. ->
  4797. decw %si addw %dx,%si p
  4798. }
  4799. RemoveInstruction(hp2);
  4800. RemoveCurrentP(p, hp1);
  4801. Result:=True;
  4802. Exit;
  4803. end;
  4804. end;
  4805. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4806. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4807. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4808. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4809. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4810. ) and
  4811. { if ref contains a symbol, we cannot change its size to a smaller size }
  4812. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4813. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4814. )
  4815. {$ifdef i386}
  4816. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4817. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4818. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4819. {$endif i386}
  4820. then
  4821. { change movsX/movzX reg/ref, reg2
  4822. add/sub/or/... regX/$const, reg2
  4823. mov reg2, reg3
  4824. dealloc reg2
  4825. to
  4826. movsX/movzX reg/ref, reg3
  4827. add/sub/or/... reg3/$const, reg3
  4828. }
  4829. begin
  4830. TransferUsedRegs(TmpUsedRegs);
  4831. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4832. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4833. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4834. begin
  4835. { by example:
  4836. movswl %si,%eax movswl %si,%eax p
  4837. decl %eax addl %edx,%eax hp1
  4838. movw %ax,%si movw %ax,%si hp2
  4839. ->
  4840. movswl %si,%eax movswl %si,%eax p
  4841. decw %eax addw %edx,%eax hp1
  4842. movw %ax,%si movw %ax,%si hp2
  4843. }
  4844. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4845. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4846. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4847. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4848. { limit size of constants as well to avoid assembler errors, but
  4849. check opsize to avoid overflow when left shifting the 1 }
  4850. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4851. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4852. {$ifdef x86_64}
  4853. { Be careful of, for example:
  4854. movl %reg1,%reg2
  4855. addl %reg3,%reg2
  4856. movq %reg2,%reg4
  4857. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4858. }
  4859. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4860. begin
  4861. taicpu(hp2).changeopsize(S_L);
  4862. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4863. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4864. end;
  4865. {$endif x86_64}
  4866. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4867. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4868. if taicpu(p).oper[0]^.typ=top_reg then
  4869. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4870. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4871. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4872. {
  4873. ->
  4874. movswl %si,%eax movswl %si,%eax p
  4875. decw %si addw %dx,%si hp1
  4876. movw %ax,%si movw %ax,%si hp2
  4877. }
  4878. case taicpu(hp1).ops of
  4879. 1:
  4880. begin
  4881. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4882. if taicpu(hp1).oper[0]^.typ=top_reg then
  4883. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4884. end;
  4885. 2:
  4886. begin
  4887. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4888. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4889. (taicpu(hp1).opcode<>A_SHL) and
  4890. (taicpu(hp1).opcode<>A_SHR) and
  4891. (taicpu(hp1).opcode<>A_SAR) then
  4892. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4893. end;
  4894. else
  4895. internalerror(2018111801);
  4896. end;
  4897. {
  4898. ->
  4899. decw %si addw %dx,%si p
  4900. }
  4901. RemoveInstruction(hp2);
  4902. end;
  4903. end;
  4904. end;
  4905. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4906. GetNextInstruction(hp1, hp2) and
  4907. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4908. MatchOperand(Taicpu(p).oper[0]^,0) and
  4909. (Taicpu(p).oper[1]^.typ = top_reg) and
  4910. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4911. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4912. { mov reg1,0
  4913. bts reg1,operand1 --> mov reg1,operand2
  4914. or reg1,operand2 bts reg1,operand1}
  4915. begin
  4916. Taicpu(hp2).opcode:=A_MOV;
  4917. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4918. asml.remove(hp1);
  4919. insertllitem(hp2,hp2.next,hp1);
  4920. RemoveCurrentp(p, hp1);
  4921. Result:=true;
  4922. exit;
  4923. end;
  4924. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4925. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4926. GetNextInstruction(hp1, hp2) and
  4927. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4928. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4929. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4930. { change
  4931. mov reg1,reg2
  4932. sub reg3,reg2
  4933. cmp reg3,reg1
  4934. into
  4935. mov reg1,reg2
  4936. sub reg3,reg2
  4937. }
  4938. begin
  4939. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4940. RemoveInstruction(hp2);
  4941. Result:=true;
  4942. exit;
  4943. end;
  4944. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4945. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4946. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4947. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4948. begin
  4949. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4950. {$ifdef x86_64}
  4951. { Convert:
  4952. movq x(ref),%reg64
  4953. shrq y,%reg64
  4954. To:
  4955. movl x+4(ref),%reg32
  4956. shrl y-32,%reg32 (Remove if y = 32)
  4957. }
  4958. if (taicpu(p).opsize = S_Q) and
  4959. (taicpu(hp1).opcode = A_SHR) and
  4960. (taicpu(hp1).oper[0]^.val >= 32) then
  4961. begin
  4962. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4963. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4964. { Convert to 32-bit }
  4965. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4966. taicpu(p).opsize := S_L;
  4967. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4968. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4969. if (taicpu(hp1).oper[0]^.val = 32) then
  4970. begin
  4971. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4972. RemoveInstruction(hp1);
  4973. end
  4974. else
  4975. begin
  4976. { This will potentially open up more arithmetic operations since
  4977. the peephole optimizer now has a big hint that only the lower
  4978. 32 bits are currently in use (and opcodes are smaller in size) }
  4979. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4980. taicpu(hp1).opsize := S_L;
  4981. Dec(taicpu(hp1).oper[0]^.val, 32);
  4982. DebugMsg(SPeepholeOptimization + PreMessage +
  4983. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4984. end;
  4985. Result := True;
  4986. Exit;
  4987. end;
  4988. {$endif x86_64}
  4989. { Convert:
  4990. movl x(ref),%reg
  4991. shrl $24,%reg
  4992. To:
  4993. movzbl x+3(ref),%reg
  4994. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4995. Also accept sar instead of shr, but convert to movsx instead of movzx
  4996. }
  4997. if taicpu(hp1).opcode = A_SHR then
  4998. MovUnaligned := A_MOVZX
  4999. else
  5000. MovUnaligned := A_MOVSX;
  5001. NewSize := S_NO;
  5002. NewOffset := 0;
  5003. case taicpu(p).opsize of
  5004. S_B:
  5005. { No valid combinations };
  5006. S_W:
  5007. if (taicpu(hp1).oper[0]^.val = 8) then
  5008. begin
  5009. NewSize := S_BW;
  5010. NewOffset := 1;
  5011. end;
  5012. S_L:
  5013. case taicpu(hp1).oper[0]^.val of
  5014. 16:
  5015. begin
  5016. NewSize := S_WL;
  5017. NewOffset := 2;
  5018. end;
  5019. 24:
  5020. begin
  5021. NewSize := S_BL;
  5022. NewOffset := 3;
  5023. end;
  5024. else
  5025. ;
  5026. end;
  5027. {$ifdef x86_64}
  5028. S_Q:
  5029. case taicpu(hp1).oper[0]^.val of
  5030. 32:
  5031. begin
  5032. if taicpu(hp1).opcode = A_SAR then
  5033. begin
  5034. { 32-bit to 64-bit is a distinct instruction }
  5035. MovUnaligned := A_MOVSXD;
  5036. NewSize := S_LQ;
  5037. NewOffset := 4;
  5038. end
  5039. else
  5040. { Should have been handled by MovShr2Mov above }
  5041. InternalError(2022081811);
  5042. end;
  5043. 48:
  5044. begin
  5045. NewSize := S_WQ;
  5046. NewOffset := 6;
  5047. end;
  5048. 56:
  5049. begin
  5050. NewSize := S_BQ;
  5051. NewOffset := 7;
  5052. end;
  5053. else
  5054. ;
  5055. end;
  5056. {$endif x86_64}
  5057. else
  5058. InternalError(2022081810);
  5059. end;
  5060. if (NewSize <> S_NO) and
  5061. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5062. begin
  5063. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5064. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5065. debug_op2str(MovUnaligned);
  5066. {$ifdef x86_64}
  5067. if MovUnaligned <> A_MOVSXD then
  5068. { Don't add size suffix for MOVSXD }
  5069. {$endif x86_64}
  5070. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5071. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5072. taicpu(p).opcode := MovUnaligned;
  5073. taicpu(p).opsize := NewSize;
  5074. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5075. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5076. RemoveInstruction(hp1);
  5077. Result := True;
  5078. Exit;
  5079. end;
  5080. end;
  5081. { Backward optimisation shared with OptPass2MOV }
  5082. if FuncMov2Func(p, hp1) then
  5083. begin
  5084. Result := True;
  5085. Exit;
  5086. end;
  5087. end;
  5088. function TX86AsmOptimizer.OptPass1MOVD(var p : tai) : boolean;
  5089. { This function also handles the 64-bit version, MOVQ }
  5090. var
  5091. hp1: tai;
  5092. begin
  5093. Result:=false;
  5094. { Change:
  5095. movd/q %xmm0, %reg
  5096. ...
  5097. movl/q %reg, (ref)
  5098. (dealloc %reg)
  5099. To:
  5100. movd/q %xmm0, (ref)
  5101. }
  5102. if MatchOpType(taicpu(p),top_reg,top_reg) and
  5103. (GetRegType(taicpu(p).oper[0]^.reg)=R_MMREGISTER) and
  5104. (GetRegType(taicpu(p).oper[1]^.reg)=R_INTREGISTER) and
  5105. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  5106. MatchInstruction(hp1, A_MOV, []) and
  5107. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  5108. (taicpu(hp1).oper[1]^.typ=top_ref) and
  5109. not RegInRef(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.ref^) then
  5110. begin
  5111. TransferUsedRegs(TmpUsedRegs);
  5112. UpdateUsedRegsBetween(TmpUsedRegs,p,hp1);
  5113. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  5114. begin
  5115. if (
  5116. { Instructions are always adjacent under -O2 and under }
  5117. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5118. (
  5119. (
  5120. (taicpu(hp1).oper[1]^.ref^.base=NR_NO) or
  5121. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.base,p,hp1)
  5122. ) and
  5123. (
  5124. (taicpu(hp1).oper[1]^.ref^.index=NR_NO) or
  5125. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.index,p,hp1)
  5126. )
  5127. )
  5128. ) then
  5129. begin
  5130. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1a)',p);
  5131. taicpu(p).loadref(1,taicpu(hp1).oper[1]^.ref^);
  5132. { loadref increases the reference count, so decrement it again }
  5133. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5134. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5135. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5136. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5137. RemoveInstruction(hp1);
  5138. Include(OptsToCheck, aoc_ForceNewIteration);
  5139. end
  5140. else if not RegModifiedBetween(taicpu(p).oper[0]^.reg,p,hp1) then
  5141. begin
  5142. { Still possible to optimise if hp1 is converted instead }
  5143. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1b)',hp1);
  5144. { Decrement the reference prior to replacing it }
  5145. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5146. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5147. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5148. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5149. taicpu(hp1).opcode:=taicpu(p).opcode;
  5150. taicpu(hp1).opsize:=taicpu(p).opsize;
  5151. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  5152. TransferUsedRegs(TmpUsedRegs);
  5153. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,TmpUsedRegs);
  5154. RemoveCurrentP(p);
  5155. Result:=True;
  5156. Exit;
  5157. end;
  5158. end;
  5159. end;
  5160. end;
  5161. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5162. var
  5163. hp1 : tai;
  5164. begin
  5165. Result:=false;
  5166. if taicpu(p).ops <> 2 then
  5167. exit;
  5168. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5169. GetNextInstruction(p,hp1) then
  5170. begin
  5171. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5172. (taicpu(hp1).ops = 2) then
  5173. begin
  5174. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5175. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5176. { movXX reg1, mem1 or movXX mem1, reg1
  5177. movXX mem2, reg2 movXX reg2, mem2}
  5178. begin
  5179. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5180. { movXX reg1, mem1 or movXX mem1, reg1
  5181. movXX mem2, reg1 movXX reg2, mem1}
  5182. begin
  5183. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5184. begin
  5185. { Removes the second statement from
  5186. movXX reg1, mem1/reg2
  5187. movXX mem1/reg2, reg1
  5188. }
  5189. if taicpu(p).oper[0]^.typ=top_reg then
  5190. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5191. { Removes the second statement from
  5192. movXX mem1/reg1, reg2
  5193. movXX reg2, mem1/reg1
  5194. }
  5195. if (taicpu(p).oper[1]^.typ=top_reg) and
  5196. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5197. begin
  5198. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5199. RemoveInstruction(hp1);
  5200. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5201. Result:=true;
  5202. exit;
  5203. end
  5204. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5205. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5206. begin
  5207. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5208. RemoveInstruction(hp1);
  5209. Result:=true;
  5210. exit;
  5211. end;
  5212. end
  5213. end;
  5214. end;
  5215. end;
  5216. end;
  5217. end;
  5218. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5219. var
  5220. hp1 : tai;
  5221. begin
  5222. result:=false;
  5223. { replace
  5224. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5225. MovX %mreg2,%mreg1
  5226. dealloc %mreg2
  5227. by
  5228. <Op>X %mreg2,%mreg1
  5229. ?
  5230. }
  5231. if GetNextInstruction(p,hp1) and
  5232. { we mix single and double opperations here because we assume that the compiler
  5233. generates vmovapd only after double operations and vmovaps only after single operations }
  5234. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5235. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5236. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5237. (taicpu(p).oper[0]^.typ=top_reg) then
  5238. begin
  5239. TransferUsedRegs(TmpUsedRegs);
  5240. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5241. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5242. begin
  5243. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5244. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5245. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5246. RemoveInstruction(hp1);
  5247. result:=true;
  5248. end;
  5249. end;
  5250. end;
  5251. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5252. var
  5253. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5254. JumpLabel, JumpLabel_dist: TAsmLabel;
  5255. FirstValue, SecondValue: TCGInt;
  5256. function OptimizeJump(var InputP: tai): Boolean;
  5257. var
  5258. TempBool: Boolean;
  5259. begin
  5260. Result := False;
  5261. TempBool := True;
  5262. if DoJumpOptimizations(InputP, TempBool) or
  5263. not TempBool then
  5264. begin
  5265. Result := True;
  5266. if Assigned(InputP) then
  5267. begin
  5268. { CollapseZeroDistJump will be set to the label or an align
  5269. before it after the jump if it optimises, whether or not
  5270. the label is live or dead }
  5271. if (InputP.typ = ait_align) or
  5272. (
  5273. (InputP.typ = ait_label) and
  5274. not (tai_label(InputP).labsym.is_used)
  5275. ) then
  5276. GetNextInstruction(InputP, InputP);
  5277. end;
  5278. Exit;
  5279. end;
  5280. end;
  5281. begin
  5282. Result := False;
  5283. if (taicpu(p).oper[0]^.typ = top_const) and
  5284. (taicpu(p).oper[0]^.val <> -1) then
  5285. begin
  5286. { Convert unsigned maximum constants to -1 to aid optimisation }
  5287. case taicpu(p).opsize of
  5288. S_B:
  5289. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5290. begin
  5291. taicpu(p).oper[0]^.val := -1;
  5292. Result := True;
  5293. Exit;
  5294. end;
  5295. S_W:
  5296. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5297. begin
  5298. taicpu(p).oper[0]^.val := -1;
  5299. Result := True;
  5300. Exit;
  5301. end;
  5302. S_L:
  5303. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5304. begin
  5305. taicpu(p).oper[0]^.val := -1;
  5306. Result := True;
  5307. Exit;
  5308. end;
  5309. {$ifdef x86_64}
  5310. S_Q:
  5311. { Storing anything greater than $7FFFFFFF is not possible so do
  5312. nothing };
  5313. {$endif x86_64}
  5314. else
  5315. InternalError(2021121001);
  5316. end;
  5317. end;
  5318. if GetNextInstruction(p, hp1) and
  5319. TrySwapMovCmp(p, hp1) then
  5320. begin
  5321. Result := True;
  5322. Exit;
  5323. end;
  5324. p_label := nil;
  5325. JumpLabel := nil;
  5326. if MatchInstruction(hp1, A_Jcc, []) then
  5327. begin
  5328. if OptimizeJump(hp1) then
  5329. begin
  5330. Result := True;
  5331. if Assigned(hp1) then
  5332. begin
  5333. { CollapseZeroDistJump will be set to the label or an align
  5334. before it after the jump if it optimises, whether or not
  5335. the label is live or dead }
  5336. if (hp1.typ = ait_align) or
  5337. (
  5338. (hp1.typ = ait_label) and
  5339. not (tai_label(hp1).labsym.is_used)
  5340. ) then
  5341. GetNextInstruction(hp1, hp1);
  5342. end;
  5343. TransferUsedRegs(TmpUsedRegs);
  5344. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5345. if not Assigned(hp1) or
  5346. (
  5347. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5348. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5349. ) then
  5350. begin
  5351. { No more conditional jumps; conditional statement is no longer required }
  5352. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5353. RemoveCurrentP(p);
  5354. end;
  5355. Exit;
  5356. end;
  5357. if IsJumpToLabel(taicpu(hp1)) then
  5358. begin
  5359. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5360. if Assigned(JumpLabel) then
  5361. p_label := getlabelwithsym(JumpLabel);
  5362. end;
  5363. end;
  5364. { Search for:
  5365. test $x,(reg/ref)
  5366. jne @lbl1
  5367. test $y,(reg/ref) (same register or reference)
  5368. jne @lbl1
  5369. Change to:
  5370. test $(x or y),(reg/ref)
  5371. jne @lbl1
  5372. (Note, this doesn't work with je instead of jne)
  5373. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5374. Also search for:
  5375. test $x,(reg/ref)
  5376. je @lbl1
  5377. ...
  5378. test $y,(reg/ref)
  5379. je/jne @lbl2
  5380. If (x or y) = x, then the second jump is deterministic
  5381. }
  5382. if (
  5383. (
  5384. (taicpu(p).oper[0]^.typ = top_const) or
  5385. (
  5386. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5387. (taicpu(p).oper[0]^.typ = top_reg) and
  5388. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5389. )
  5390. ) and
  5391. MatchInstruction(hp1, A_JCC, [])
  5392. ) then
  5393. begin
  5394. if (taicpu(p).oper[0]^.typ = top_reg) and
  5395. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5396. FirstValue := -1
  5397. else
  5398. FirstValue := taicpu(p).oper[0]^.val;
  5399. { If we have several test/jne's in a row, it might be the case that
  5400. the second label doesn't go to the same location, but the one
  5401. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5402. so accommodate for this with a while loop.
  5403. }
  5404. hp1_last := hp1;
  5405. while (
  5406. (
  5407. (taicpu(p).oper[1]^.typ = top_reg) and
  5408. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5409. ) or GetNextInstruction(hp1_last, p_dist)
  5410. ) and (p_dist.typ = ait_instruction) do
  5411. begin
  5412. if (
  5413. (
  5414. (taicpu(p_dist).opcode = A_TEST) and
  5415. (
  5416. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5417. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5418. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5419. )
  5420. ) or
  5421. (
  5422. { cmp 0,%reg = test %reg,%reg }
  5423. (taicpu(p_dist).opcode = A_CMP) and
  5424. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5425. )
  5426. ) and
  5427. { Make sure the destination operands are actually the same }
  5428. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5429. GetNextInstruction(p_dist, hp1_dist) and
  5430. MatchInstruction(hp1_dist, A_JCC, []) then
  5431. begin
  5432. if OptimizeJump(hp1_dist) then
  5433. begin
  5434. Result := True;
  5435. Exit;
  5436. end;
  5437. if
  5438. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5439. (
  5440. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5441. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5442. ) then
  5443. SecondValue := -1
  5444. else
  5445. SecondValue := taicpu(p_dist).oper[0]^.val;
  5446. { If both of the TEST constants are identical, delete the
  5447. second TEST that is unnecessary (be careful though, just
  5448. in case the flags are modified in between) }
  5449. if (FirstValue = SecondValue) then
  5450. begin
  5451. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5452. begin
  5453. { Since the second jump's condition is a subset of the first, we
  5454. know it will never branch because the first jump dominates it.
  5455. Get it out of the way now rather than wait for the jump
  5456. optimisations for a speed boost. }
  5457. if IsJumpToLabel(taicpu(hp1_dist)) then
  5458. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5459. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5460. RemoveInstruction(hp1_dist);
  5461. Result := True;
  5462. end
  5463. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5464. begin
  5465. { If the inverse of the first condition is a subset of the second,
  5466. the second one will definitely branch if the first one doesn't }
  5467. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5468. { We can remove the TEST instruction too }
  5469. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5470. RemoveInstruction(p_dist);
  5471. MakeUnconditional(taicpu(hp1_dist));
  5472. RemoveDeadCodeAfterJump(hp1_dist);
  5473. { Since the jump is now unconditional, we can't
  5474. continue any further with this particular
  5475. optimisation. The original TEST is still intact
  5476. though, so there might be something else we can
  5477. do }
  5478. Include(OptsToCheck, aoc_ForceNewIteration);
  5479. Break;
  5480. end;
  5481. if Result or
  5482. { If a jump wasn't removed or made unconditional, only
  5483. remove the identical TEST instruction if the flags
  5484. weren't modified }
  5485. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5486. begin
  5487. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5488. RemoveInstruction(p_dist);
  5489. { If the jump was removed or made unconditional, we
  5490. don't need to allocate NR_DEFAULTFLAGS over the
  5491. entire range }
  5492. if not Result then
  5493. begin
  5494. { Mark the flags as 'in use' over the entire range }
  5495. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5496. { Speed gain - continue search from the Jcc instruction }
  5497. hp1_last := hp1_dist;
  5498. { Only the TEST instruction was removed, and the
  5499. original was unchanged, so we can safely do
  5500. another iteration of the while loop }
  5501. Include(OptsToCheck, aoc_ForceNewIteration);
  5502. Continue;
  5503. end;
  5504. Exit;
  5505. end;
  5506. end;
  5507. hp1_last := nil;
  5508. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5509. (
  5510. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5511. { Always adjacent under -O2 and under }
  5512. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5513. (
  5514. GetNextInstruction(hp1, hp1_last) and
  5515. (hp1_last = p_dist)
  5516. )
  5517. ) and
  5518. (
  5519. (
  5520. { Test the following variant:
  5521. test $x,(reg/ref)
  5522. jne @lbl1
  5523. test $y,(reg/ref)
  5524. je @lbl2
  5525. @lbl1:
  5526. Becomes:
  5527. test $(x or y),(reg/ref)
  5528. je @lbl2
  5529. @lbl1: (may become a dead label)
  5530. }
  5531. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5532. GetNextInstruction(hp1_dist, hp1_last) and
  5533. (hp1_last = p_label)
  5534. ) or
  5535. (
  5536. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5537. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5538. then the second jump will never branch, so it can also be
  5539. removed regardless of where it goes }
  5540. (
  5541. (FirstValue = -1) or
  5542. (SecondValue = -1) or
  5543. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5544. )
  5545. )
  5546. ) then
  5547. begin
  5548. { Same jump location... can be a register since nothing's changed }
  5549. { If any of the entries are equivalent to test %reg,%reg, then the
  5550. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5551. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5552. if (hp1_last = p_label) then
  5553. begin
  5554. { Variant }
  5555. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5556. RemoveInstruction(p_dist);
  5557. if Assigned(JumpLabel) then
  5558. JumpLabel.decrefs;
  5559. RemoveInstruction(hp1);
  5560. end
  5561. else
  5562. begin
  5563. { Only remove the second test if no jumps or other conditional instructions follow }
  5564. TransferUsedRegs(TmpUsedRegs);
  5565. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5567. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5568. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5569. begin
  5570. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5571. RemoveInstruction(p_dist);
  5572. { Remove the first jump, not the second, to keep
  5573. any register deallocations between the second
  5574. TEST/JNE pair in the same place. Aids future
  5575. optimisation. }
  5576. if Assigned(JumpLabel) then
  5577. JumpLabel.decrefs;
  5578. RemoveInstruction(hp1);
  5579. end
  5580. else
  5581. begin
  5582. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5583. if IsJumpToLabel(taicpu(hp1_dist)) then
  5584. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5585. { Remove second jump in this instance }
  5586. RemoveInstruction(hp1_dist);
  5587. end;
  5588. end;
  5589. Result := True;
  5590. Exit;
  5591. end;
  5592. end;
  5593. if { If -O2 and under, it may stop on any old instruction }
  5594. (cs_opt_level3 in current_settings.optimizerswitches) and
  5595. (taicpu(p).oper[1]^.typ = top_reg) and
  5596. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5597. begin
  5598. hp1_last := p_dist;
  5599. Continue;
  5600. end;
  5601. Break;
  5602. end;
  5603. end;
  5604. { Search for:
  5605. test %reg,%reg
  5606. j(c1) @lbl1
  5607. ...
  5608. @lbl:
  5609. test %reg,%reg (same register)
  5610. j(c2) @lbl2
  5611. If c2 is a subset of c1, change to:
  5612. test %reg,%reg
  5613. j(c1) @lbl2
  5614. (@lbl1 may become a dead label as a result)
  5615. }
  5616. if (taicpu(p).oper[1]^.typ = top_reg) and
  5617. (taicpu(p).oper[0]^.typ = top_reg) and
  5618. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5619. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5620. Assigned(p_label) and
  5621. GetNextInstruction(p_label, p_dist) and
  5622. MatchInstruction(p_dist, A_TEST, []) and
  5623. { It's fine if the second test uses smaller sub-registers }
  5624. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5625. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5626. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5627. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5628. GetNextInstruction(p_dist, hp1_dist) and
  5629. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5630. begin
  5631. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5632. if JumpLabel = JumpLabel_dist then
  5633. { This is an infinite loop }
  5634. Exit;
  5635. { Best optimisation when the first condition is a subset (or equal) of the second }
  5636. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5637. begin
  5638. { Any registers used here will already be allocated }
  5639. if Assigned(JumpLabel) then
  5640. JumpLabel.DecRefs;
  5641. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5642. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5643. Result := True;
  5644. Exit;
  5645. end;
  5646. end;
  5647. end;
  5648. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5649. var
  5650. hp1, hp2: tai;
  5651. ActiveReg: TRegister;
  5652. OldOffset: asizeint;
  5653. ThisConst: TCGInt;
  5654. function RegDeallocated: Boolean;
  5655. begin
  5656. TransferUsedRegs(TmpUsedRegs);
  5657. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5658. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5659. end;
  5660. begin
  5661. result:=false;
  5662. hp1 := nil;
  5663. { replace
  5664. addX const,%reg1
  5665. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5666. dealloc %reg1
  5667. by
  5668. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5669. }
  5670. if MatchOpType(taicpu(p),top_const,top_reg) then
  5671. begin
  5672. ActiveReg := taicpu(p).oper[1]^.reg;
  5673. { Ensures the entire register was updated }
  5674. if (taicpu(p).opsize >= S_L) and
  5675. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5676. MatchInstruction(hp1,A_LEA,[]) and
  5677. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5678. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5679. (
  5680. { Cover the case where the register in the reference is also the destination register }
  5681. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5682. (
  5683. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5684. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5685. RegDeallocated
  5686. )
  5687. ) then
  5688. begin
  5689. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5690. {$push}
  5691. {$R-}{$Q-}
  5692. { Explicitly disable overflow checking for these offset calculation
  5693. as those do not matter for the final result }
  5694. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5695. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5696. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5697. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5698. {$pop}
  5699. {$ifdef x86_64}
  5700. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5701. begin
  5702. { Overflow; abort }
  5703. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5704. end
  5705. else
  5706. {$endif x86_64}
  5707. begin
  5708. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5709. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5710. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5711. RemoveCurrentP(p, hp1)
  5712. else
  5713. RemoveCurrentP(p);
  5714. result:=true;
  5715. Exit;
  5716. end;
  5717. end;
  5718. if (
  5719. { Save calling GetNextInstructionUsingReg again }
  5720. Assigned(hp1) or
  5721. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5722. ) and
  5723. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5724. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5725. begin
  5726. { Make sure the flags aren't in use by the second operation }
  5727. TransferUsedRegs(TmpUsedRegs);
  5728. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5729. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5730. begin
  5731. if taicpu(hp1).oper[0]^.typ = top_const then
  5732. begin
  5733. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5734. if taicpu(hp1).opcode = A_ADD then
  5735. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5736. else
  5737. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5738. Result := True;
  5739. { Handle any overflows }
  5740. case taicpu(p).opsize of
  5741. S_B:
  5742. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5743. S_W:
  5744. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5745. S_L:
  5746. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5747. {$ifdef x86_64}
  5748. S_Q:
  5749. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5750. { Overflow; abort }
  5751. Result := False
  5752. else
  5753. taicpu(p).oper[0]^.val := ThisConst;
  5754. {$endif x86_64}
  5755. else
  5756. InternalError(2021102610);
  5757. end;
  5758. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5759. if Result then
  5760. begin
  5761. if (taicpu(p).oper[0]^.val < 0) and
  5762. (
  5763. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5764. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5765. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5766. ) then
  5767. begin
  5768. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5769. taicpu(p).opcode := A_SUB;
  5770. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5771. end
  5772. else
  5773. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5774. RemoveInstruction(hp1);
  5775. end;
  5776. end
  5777. else
  5778. begin
  5779. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5780. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5781. Asml.Remove(p);
  5782. Asml.InsertAfter(p, hp1);
  5783. p := hp1;
  5784. Result := True;
  5785. Exit;
  5786. end;
  5787. end;
  5788. end;
  5789. if DoArithCombineOpt(p) then
  5790. Result:=true;
  5791. end;
  5792. end;
  5793. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5794. var
  5795. hp1, hp2: tai;
  5796. ref: Integer;
  5797. saveref: treference;
  5798. offsetcalc: Int64;
  5799. TempReg: TRegister;
  5800. Multiple: TCGInt;
  5801. Adjacent, IntermediateRegDiscarded: Boolean;
  5802. begin
  5803. Result:=false;
  5804. { play save and throw an error if LEA uses a seg register prefix,
  5805. this is most likely an error somewhere else }
  5806. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5807. internalerror(2022022001);
  5808. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5809. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5810. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5811. (
  5812. { do not mess with leas accessing the stack pointer
  5813. unless it's a null operation }
  5814. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5815. (
  5816. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5817. (taicpu(p).oper[0]^.ref^.offset = 0)
  5818. )
  5819. ) and
  5820. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5821. begin
  5822. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5823. begin
  5824. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5825. begin
  5826. taicpu(p).opcode := A_MOV;
  5827. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5828. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5829. end
  5830. else
  5831. begin
  5832. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5833. RemoveCurrentP(p);
  5834. end;
  5835. Result:=true;
  5836. exit;
  5837. end
  5838. else if (
  5839. { continue to use lea to adjust the stack pointer,
  5840. it is the recommended way, but only if not optimizing for size }
  5841. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5842. (cs_opt_size in current_settings.optimizerswitches)
  5843. ) and
  5844. { If the flags register is in use, don't change the instruction
  5845. to an ADD otherwise this will scramble the flags. [Kit] }
  5846. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5847. ConvertLEA(taicpu(p)) then
  5848. begin
  5849. Result:=true;
  5850. exit;
  5851. end;
  5852. end;
  5853. { Don't optimise if the stack or frame pointer is the destination register }
  5854. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5855. Exit;
  5856. if GetNextInstruction(p,hp1) and
  5857. (hp1.typ=ait_instruction) then
  5858. begin
  5859. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5860. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5861. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5862. begin
  5863. TransferUsedRegs(TmpUsedRegs);
  5864. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5865. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5866. begin
  5867. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5868. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5869. RemoveInstruction(hp1);
  5870. result:=true;
  5871. exit;
  5872. end;
  5873. end;
  5874. { changes
  5875. lea <ref1>, reg1
  5876. <op> ...,<ref. with reg1>,...
  5877. to
  5878. <op> ...,<ref1>,... }
  5879. { find a reference which uses reg1 }
  5880. 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
  5881. ref:=0
  5882. 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
  5883. ref:=1
  5884. else
  5885. ref:=-1;
  5886. if (ref<>-1) and
  5887. { reg1 must be either the base or the index }
  5888. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5889. begin
  5890. { reg1 can be removed from the reference }
  5891. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5892. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5893. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5894. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5895. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5896. else
  5897. Internalerror(2019111201);
  5898. { check if the can insert all data of the lea into the second instruction }
  5899. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5900. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5901. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5902. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5903. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5904. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5905. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5906. {$ifdef x86_64}
  5907. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5908. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5909. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5910. )
  5911. {$endif x86_64}
  5912. then
  5913. begin
  5914. { reg1 might not used by the second instruction after it is remove from the reference }
  5915. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5916. begin
  5917. TransferUsedRegs(TmpUsedRegs);
  5918. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5919. { reg1 is not updated so it might not be used afterwards }
  5920. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5921. begin
  5922. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5923. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5924. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5925. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5926. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5927. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5928. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5929. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5930. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5931. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5932. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5933. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5934. RemoveCurrentP(p, hp1);
  5935. result:=true;
  5936. exit;
  5937. end
  5938. end;
  5939. end;
  5940. { recover }
  5941. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5942. end;
  5943. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5944. if Adjacent or
  5945. { Check further ahead (up to 2 instructions ahead for -O2) }
  5946. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5947. begin
  5948. { Check common LEA/LEA conditions }
  5949. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5950. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5951. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5952. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5953. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5954. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5955. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5956. (
  5957. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5958. calling it (since it calls GetNextInstruction) }
  5959. Adjacent or
  5960. (
  5961. (
  5962. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5963. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5964. ) and (
  5965. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5966. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5967. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5968. )
  5969. )
  5970. ) then
  5971. begin
  5972. TransferUsedRegs(TmpUsedRegs);
  5973. hp2 := p;
  5974. repeat
  5975. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5976. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5977. IntermediateRegDiscarded :=
  5978. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5979. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5980. { changes
  5981. lea offset1(regX,scale), reg1
  5982. lea offset2(reg1,reg1), reg2
  5983. to
  5984. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5985. and
  5986. lea offset1(regX,scale1), reg1
  5987. lea offset2(reg1,scale2), reg2
  5988. to
  5989. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5990. and
  5991. lea offset1(regX,scale1), reg1
  5992. lea offset2(reg3,reg1,scale2), reg2
  5993. to
  5994. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5995. ... so long as the final scale does not exceed 8
  5996. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5997. }
  5998. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5999. (
  6000. { Don't optimise if size is a concern and the intermediate register remains in use }
  6001. IntermediateRegDiscarded or
  6002. (
  6003. not (cs_opt_size in current_settings.optimizerswitches) and
  6004. { If the intermediate register is not discarded, it must not
  6005. appear in the first LEA's reference. (Fixes #41166) }
  6006. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6007. )
  6008. ) and
  6009. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6010. (
  6011. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  6012. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6013. ) and (
  6014. (
  6015. { lea (reg1,scale2), reg2 variant }
  6016. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  6017. (
  6018. Adjacent or
  6019. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  6020. ) and
  6021. (
  6022. (
  6023. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  6024. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  6025. ) or (
  6026. { lea (regX,regX), reg1 variant }
  6027. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  6028. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  6029. )
  6030. )
  6031. ) or (
  6032. { lea (reg1,reg1), reg1 variant }
  6033. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6034. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  6035. )
  6036. ) then
  6037. begin
  6038. { Make everything homogeneous to make calculations easier }
  6039. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  6040. begin
  6041. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  6042. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  6043. taicpu(p).oper[0]^.ref^.scalefactor := 2
  6044. else
  6045. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  6046. taicpu(p).oper[0]^.ref^.base := NR_NO;
  6047. end;
  6048. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6049. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6050. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6051. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6052. begin
  6053. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6054. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  6055. begin
  6056. { Put the register to change in the index register }
  6057. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  6058. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  6059. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  6060. end;
  6061. { Change lea (reg,reg) to lea(,reg,2) }
  6062. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  6063. begin
  6064. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  6065. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  6066. end;
  6067. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  6068. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6069. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  6070. { Just to prevent miscalculations }
  6071. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  6072. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  6073. else
  6074. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  6075. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6076. if IntermediateRegDiscarded then
  6077. begin
  6078. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  6079. RemoveCurrentP(p);
  6080. end
  6081. else
  6082. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  6083. result:=true;
  6084. exit;
  6085. end;
  6086. end;
  6087. { changes
  6088. lea offset1(regX), reg1
  6089. lea offset2(reg1), reg2
  6090. to
  6091. lea offset1+offset2(regX), reg2 }
  6092. if (
  6093. { Don't optimise if size is a concern and the intermediate register remains in use }
  6094. IntermediateRegDiscarded or
  6095. (
  6096. not (cs_opt_size in current_settings.optimizerswitches) and
  6097. { If the intermediate register is not discarded, it must not
  6098. appear in the first LEA's reference. (Fixes #41166) }
  6099. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6100. )
  6101. ) and
  6102. (
  6103. (
  6104. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6105. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6106. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6107. ) or (
  6108. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6109. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6110. (
  6111. (
  6112. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6113. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6114. ) or (
  6115. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6116. (
  6117. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6118. (
  6119. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6120. (
  6121. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6122. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6123. )
  6124. )
  6125. )
  6126. )
  6127. )
  6128. )
  6129. ) then
  6130. begin
  6131. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6132. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6133. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6134. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6135. begin
  6136. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6137. begin
  6138. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6139. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6140. { if the register is used as index and base, we have to increase for base as well
  6141. and adapt base }
  6142. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6143. begin
  6144. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6145. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6146. end;
  6147. end
  6148. else
  6149. begin
  6150. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6151. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6152. end;
  6153. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6154. begin
  6155. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6156. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6157. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6158. { Catch the situation where the base = index
  6159. and treat this as *2. The scalefactor of
  6160. p will be 0 or 1 due to the conditional
  6161. checks above. Fixes i40647 }
  6162. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6163. else
  6164. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6165. end;
  6166. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6167. if IntermediateRegDiscarded then
  6168. begin
  6169. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6170. RemoveCurrentP(p);
  6171. end
  6172. else
  6173. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6174. result:=true;
  6175. exit;
  6176. end;
  6177. end;
  6178. end;
  6179. { Change:
  6180. leal/q $x(%reg1),%reg2
  6181. ...
  6182. shll/q $y,%reg2
  6183. To:
  6184. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6185. }
  6186. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6187. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6188. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6189. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6190. (taicpu(hp1).oper[0]^.val <= 3) then
  6191. begin
  6192. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6193. TransferUsedRegs(TmpUsedRegs);
  6194. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6195. if
  6196. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6197. (this works even if scalefactor is zero) }
  6198. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6199. { Ensure offset doesn't go out of bounds }
  6200. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6201. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6202. (
  6203. (
  6204. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6205. (
  6206. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6207. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6208. (
  6209. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6210. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6211. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6212. )
  6213. )
  6214. ) or (
  6215. (
  6216. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6217. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6218. ) and
  6219. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6220. )
  6221. ) then
  6222. begin
  6223. repeat
  6224. with taicpu(p).oper[0]^.ref^ do
  6225. begin
  6226. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6227. if index = base then
  6228. begin
  6229. if Multiple > 4 then
  6230. { Optimisation will no longer work because resultant
  6231. scale factor will exceed 8 }
  6232. Break;
  6233. base := NR_NO;
  6234. scalefactor := 2;
  6235. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6236. end
  6237. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6238. begin
  6239. { Scale factor only works on the index register }
  6240. index := base;
  6241. base := NR_NO;
  6242. end;
  6243. { For safety }
  6244. if scalefactor <= 1 then
  6245. begin
  6246. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6247. scalefactor := Multiple;
  6248. end
  6249. else
  6250. begin
  6251. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6252. scalefactor := scalefactor * Multiple;
  6253. end;
  6254. offset := offset * Multiple;
  6255. end;
  6256. RemoveInstruction(hp1);
  6257. Result := True;
  6258. Exit;
  6259. { This repeat..until loop exists for the benefit of Break }
  6260. until True;
  6261. end;
  6262. end;
  6263. end;
  6264. end;
  6265. end;
  6266. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6267. var
  6268. hp1 : tai;
  6269. SubInstr: Boolean;
  6270. ThisConst: TCGInt;
  6271. const
  6272. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6273. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6274. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6275. begin
  6276. Result := False;
  6277. if taicpu(p).oper[0]^.typ <> top_const then
  6278. { Should have been confirmed before calling }
  6279. InternalError(2021102601);
  6280. SubInstr := (taicpu(p).opcode = A_SUB);
  6281. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6282. GetLastInstruction(p, hp1) and
  6283. (hp1.typ = ait_instruction) and
  6284. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6285. begin
  6286. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6287. { Bad size }
  6288. InternalError(2022042001);
  6289. case taicpu(hp1).opcode Of
  6290. A_INC:
  6291. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6292. begin
  6293. if SubInstr then
  6294. ThisConst := taicpu(p).oper[0]^.val - 1
  6295. else
  6296. ThisConst := taicpu(p).oper[0]^.val + 1;
  6297. end
  6298. else
  6299. Exit;
  6300. A_DEC:
  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_SUB:
  6311. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6312. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6313. begin
  6314. if SubInstr then
  6315. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6316. else
  6317. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6318. end
  6319. else
  6320. Exit;
  6321. A_ADD:
  6322. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6323. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6324. begin
  6325. if SubInstr then
  6326. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6327. else
  6328. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6329. end
  6330. else
  6331. Exit;
  6332. else
  6333. Exit;
  6334. end;
  6335. { Check that the values are in range }
  6336. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6337. { Overflow; abort }
  6338. Exit;
  6339. if (ThisConst = 0) then
  6340. begin
  6341. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6342. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6343. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6344. RemoveInstruction(hp1);
  6345. hp1 := tai(p.next);
  6346. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6347. if not GetLastInstruction(hp1, p) then
  6348. p := hp1;
  6349. end
  6350. else
  6351. begin
  6352. if taicpu(hp1).opercnt=1 then
  6353. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6354. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6355. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6356. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6357. else
  6358. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6359. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6360. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6361. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6362. RemoveInstruction(hp1);
  6363. taicpu(p).loadconst(0, ThisConst);
  6364. end;
  6365. Result := True;
  6366. end;
  6367. end;
  6368. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6369. begin
  6370. Result := False;
  6371. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6372. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6373. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6374. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6375. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6376. (
  6377. (
  6378. (taicpu(hp1).opcode = A_TEST)
  6379. ) or (
  6380. (taicpu(hp1).opcode = A_CMP) and
  6381. { A sanity check more than anything }
  6382. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6383. )
  6384. ) then
  6385. begin
  6386. { change
  6387. mov mem, %reg
  6388. ...
  6389. cmp/test x, %reg / test %reg,%reg
  6390. (reg deallocated)
  6391. to
  6392. cmp/test x, mem / cmp 0, mem
  6393. }
  6394. TransferUsedRegs(TmpUsedRegs);
  6395. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6396. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6397. begin
  6398. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6399. if (taicpu(hp1).opcode = A_TEST) and
  6400. (
  6401. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6402. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6403. ) then
  6404. begin
  6405. taicpu(hp1).opcode := A_CMP;
  6406. taicpu(hp1).loadconst(0, 0);
  6407. end;
  6408. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6409. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6410. RemoveCurrentP(p);
  6411. if (p <> hp1) then
  6412. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6413. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6414. { Make sure the flags are allocated across the CMP instruction }
  6415. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6416. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6417. Result := True;
  6418. Exit;
  6419. end;
  6420. end;
  6421. end;
  6422. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6423. var
  6424. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6425. ThisReg, SecondReg: TRegister;
  6426. JumpLoc: TAsmLabel;
  6427. NewSize: TOpSize;
  6428. begin
  6429. Result := False;
  6430. {
  6431. Convert:
  6432. j<c> .L1
  6433. .L2:
  6434. mov 1,reg
  6435. jmp .L3 (or ret, although it might not be a RET yet)
  6436. .L1:
  6437. mov 0,reg
  6438. jmp .L3 (or ret)
  6439. ( As long as .L3 <> .L1 or .L2)
  6440. To:
  6441. mov 0,reg
  6442. set<not(c)> reg
  6443. jmp .L3 (or ret)
  6444. .L2:
  6445. mov 1,reg
  6446. jmp .L3 (or ret)
  6447. .L1:
  6448. mov 0,reg
  6449. jmp .L3 (or ret)
  6450. }
  6451. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6452. Exit;
  6453. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6454. if GetNextInstruction(hp_label, hp2) and
  6455. MatchInstruction(hp2,A_MOV,[]) and
  6456. (taicpu(hp2).oper[0]^.typ = top_const) and
  6457. (
  6458. (
  6459. (taicpu(hp2).oper[1]^.typ = top_reg)
  6460. {$ifdef i386}
  6461. { Under i386, ESI, EDI, EBP and ESP
  6462. don't have an 8-bit representation }
  6463. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6464. {$endif i386}
  6465. ) or (
  6466. {$ifdef i386}
  6467. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6468. {$endif i386}
  6469. (taicpu(hp2).opsize = S_B)
  6470. )
  6471. ) and
  6472. GetNextInstruction(hp2, hp3) and
  6473. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6474. (
  6475. (taicpu(hp3).opcode=A_RET) or
  6476. (
  6477. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6478. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6479. )
  6480. ) and
  6481. GetNextInstruction(hp3, hp4) and
  6482. FindLabel(JumpLoc, hp4) and
  6483. (
  6484. not (cs_opt_size in current_settings.optimizerswitches) or
  6485. { If the initial jump is the label's only reference, then it will
  6486. become a dead label if the other conditions are met and hence
  6487. remove at least 2 instructions, including a jump }
  6488. (JumpLoc.getrefs = 1)
  6489. ) and
  6490. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6491. that will be optimised out }
  6492. GetNextInstruction(hp4, hp5) and
  6493. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6494. (taicpu(hp5).oper[0]^.typ = top_const) and
  6495. (
  6496. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6497. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6498. ) and
  6499. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6500. GetNextInstruction(hp5,hp6) and
  6501. (
  6502. not (hp6.typ in [ait_align, ait_label]) or
  6503. SkipLabels(hp6, hp6)
  6504. ) and
  6505. (hp6.typ=ait_instruction) then
  6506. begin
  6507. { First, let's look at the two jumps that are hp3 and hp6 }
  6508. if not
  6509. (
  6510. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6511. (
  6512. (taicpu(hp6).opcode=A_RET) or
  6513. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6514. )
  6515. ) then
  6516. { If condition is False, then the JMP/RET instructions matched conventionally }
  6517. begin
  6518. { See if one of the jumps can be instantly converted into a RET }
  6519. if (taicpu(hp3).opcode=A_JMP) then
  6520. begin
  6521. { Reuse hp5 }
  6522. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6523. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6524. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6525. Exit;
  6526. if MatchInstruction(hp5, A_RET, []) then
  6527. begin
  6528. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6529. ConvertJumpToRET(hp3, hp5);
  6530. Result := True;
  6531. end
  6532. else
  6533. Exit;
  6534. end;
  6535. if (taicpu(hp6).opcode=A_JMP) then
  6536. begin
  6537. { Reuse hp5 }
  6538. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6539. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6540. Exit;
  6541. if MatchInstruction(hp5, A_RET, []) then
  6542. begin
  6543. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6544. ConvertJumpToRET(hp6, hp5);
  6545. Result := True;
  6546. end
  6547. else
  6548. Exit;
  6549. end;
  6550. if not
  6551. (
  6552. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6553. (
  6554. (taicpu(hp6).opcode=A_RET) or
  6555. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6556. )
  6557. ) then
  6558. { Still doesn't match }
  6559. Exit;
  6560. end;
  6561. if (taicpu(hp2).oper[0]^.val = 1) then
  6562. begin
  6563. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6564. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6565. end
  6566. else
  6567. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6568. if taicpu(hp2).opsize=S_B then
  6569. begin
  6570. if taicpu(hp2).oper[1]^.typ = top_reg then
  6571. begin
  6572. SecondReg := taicpu(hp2).oper[1]^.reg;
  6573. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6574. end
  6575. else
  6576. begin
  6577. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6578. SecondReg := NR_NO;
  6579. end;
  6580. hp_pos := p;
  6581. hp_allocstart := hp4;
  6582. end
  6583. else
  6584. begin
  6585. { Will be a register because the size can't be S_B otherwise }
  6586. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6587. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6588. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6589. if (cs_opt_size in current_settings.optimizerswitches) then
  6590. begin
  6591. { Favour using MOVZX when optimising for size }
  6592. case taicpu(hp2).opsize of
  6593. S_W:
  6594. NewSize := S_BW;
  6595. S_L:
  6596. NewSize := S_BL;
  6597. {$ifdef x86_64}
  6598. S_Q:
  6599. begin
  6600. NewSize := S_BL;
  6601. { Will implicitly zero-extend to 64-bit }
  6602. setsubreg(SecondReg, R_SUBD);
  6603. end;
  6604. {$endif x86_64}
  6605. else
  6606. InternalError(2022101301);
  6607. end;
  6608. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6609. { Inserting it right before p will guarantee that the flags are also tracked }
  6610. Asml.InsertBefore(hp5, p);
  6611. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6612. hp_pos := hp5;
  6613. hp_allocstart := hp4;
  6614. end
  6615. else
  6616. begin
  6617. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6618. { Inserting it right before p will guarantee that the flags are also tracked }
  6619. Asml.InsertBefore(hp5, p);
  6620. hp_pos := p;
  6621. hp_allocstart := hp5;
  6622. end;
  6623. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6624. end;
  6625. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6626. taicpu(hp4).condition := taicpu(p).condition;
  6627. asml.InsertBefore(hp4, hp_pos);
  6628. if taicpu(hp3).is_jmp then
  6629. begin
  6630. JumpLoc.decrefs;
  6631. MakeUnconditional(taicpu(p));
  6632. { This also increases the reference count }
  6633. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6634. end
  6635. else
  6636. ConvertJumpToRET(p, hp3);
  6637. if SecondReg <> NR_NO then
  6638. { Ensure the destination register is allocated over this region }
  6639. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6640. if (JumpLoc.getrefs = 0) then
  6641. RemoveDeadCodeAfterJump(hp3);
  6642. Result:=true;
  6643. exit;
  6644. end;
  6645. end;
  6646. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6647. var
  6648. hp1, hp2: tai;
  6649. ActiveReg: TRegister;
  6650. OldOffset: asizeint;
  6651. ThisConst: TCGInt;
  6652. function RegDeallocated: Boolean;
  6653. begin
  6654. TransferUsedRegs(TmpUsedRegs);
  6655. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6656. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6657. end;
  6658. begin
  6659. Result:=false;
  6660. hp1 := nil;
  6661. { replace
  6662. subX const,%reg1
  6663. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6664. dealloc %reg1
  6665. by
  6666. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6667. }
  6668. if MatchOpType(taicpu(p),top_const,top_reg) then
  6669. begin
  6670. ActiveReg := taicpu(p).oper[1]^.reg;
  6671. { Ensures the entire register was updated }
  6672. if (taicpu(p).opsize >= S_L) and
  6673. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6674. MatchInstruction(hp1,A_LEA,[]) and
  6675. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6676. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6677. (
  6678. { Cover the case where the register in the reference is also the destination register }
  6679. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6680. (
  6681. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6682. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6683. RegDeallocated
  6684. )
  6685. ) then
  6686. begin
  6687. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6688. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6689. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6690. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6691. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6692. {$ifdef x86_64}
  6693. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6694. begin
  6695. { Overflow; abort }
  6696. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6697. end
  6698. else
  6699. {$endif x86_64}
  6700. begin
  6701. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6702. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6703. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6704. RemoveCurrentP(p, hp1)
  6705. else
  6706. RemoveCurrentP(p);
  6707. result:=true;
  6708. Exit;
  6709. end;
  6710. end;
  6711. if (
  6712. { Save calling GetNextInstructionUsingReg again }
  6713. Assigned(hp1) or
  6714. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6715. ) and
  6716. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6717. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6718. begin
  6719. { Make sure the flags aren't in use by the second operation }
  6720. TransferUsedRegs(TmpUsedRegs);
  6721. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6722. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6723. begin
  6724. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6725. begin
  6726. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6727. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6728. Result := True;
  6729. { Handle any overflows }
  6730. case taicpu(p).opsize of
  6731. S_B:
  6732. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6733. S_W:
  6734. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6735. S_L:
  6736. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6737. {$ifdef x86_64}
  6738. S_Q:
  6739. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6740. { Overflow; abort }
  6741. Result := False
  6742. else
  6743. taicpu(p).oper[0]^.val := ThisConst;
  6744. {$endif x86_64}
  6745. else
  6746. InternalError(2021102611);
  6747. end;
  6748. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6749. if Result then
  6750. begin
  6751. if (taicpu(p).oper[0]^.val < 0) and
  6752. (
  6753. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6754. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6755. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6756. ) then
  6757. begin
  6758. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6759. taicpu(p).opcode := A_SUB;
  6760. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6761. end
  6762. else
  6763. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6764. RemoveInstruction(hp1);
  6765. end;
  6766. end
  6767. else
  6768. begin
  6769. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6770. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6771. Asml.Remove(p);
  6772. Asml.InsertAfter(p, hp1);
  6773. p := hp1;
  6774. Result := True;
  6775. Exit;
  6776. end;
  6777. end;
  6778. end;
  6779. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6780. { * change "sub/add const1, reg" or "dec reg" followed by
  6781. "sub const2, reg" to one "sub ..., reg" }
  6782. {$ifdef i386}
  6783. if (taicpu(p).oper[0]^.val = 2) and
  6784. (ActiveReg = NR_ESP) and
  6785. { Don't do the sub/push optimization if the sub }
  6786. { comes from setting up the stack frame (JM) }
  6787. (not(GetLastInstruction(p,hp1)) or
  6788. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6789. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6790. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6791. begin
  6792. hp1 := tai(p.next);
  6793. while Assigned(hp1) and
  6794. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6795. not RegReadByInstruction(NR_ESP,hp1) and
  6796. not RegModifiedByInstruction(NR_ESP,hp1) do
  6797. hp1 := tai(hp1.next);
  6798. if Assigned(hp1) and
  6799. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6800. begin
  6801. taicpu(hp1).changeopsize(S_L);
  6802. if taicpu(hp1).oper[0]^.typ=top_reg then
  6803. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6804. hp1 := tai(p.next);
  6805. RemoveCurrentp(p, hp1);
  6806. Result:=true;
  6807. exit;
  6808. end;
  6809. end;
  6810. {$endif i386}
  6811. if DoArithCombineOpt(p) then
  6812. Result:=true;
  6813. end;
  6814. end;
  6815. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6816. var
  6817. TmpBool1,TmpBool2 : Boolean;
  6818. tmpref : treference;
  6819. hp1,hp2: tai;
  6820. mask, shiftval: tcgint;
  6821. begin
  6822. Result:=false;
  6823. { All these optimisations work on "shl/sal const,%reg" }
  6824. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6825. Exit;
  6826. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6827. (taicpu(p).oper[0]^.val <= 3) then
  6828. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6829. begin
  6830. { should we check the next instruction? }
  6831. TmpBool1 := True;
  6832. { have we found an add/sub which could be
  6833. integrated in the lea? }
  6834. TmpBool2 := False;
  6835. reference_reset(tmpref,2,[]);
  6836. TmpRef.index := taicpu(p).oper[1]^.reg;
  6837. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6838. while TmpBool1 and
  6839. GetNextInstruction(p, hp1) and
  6840. (tai(hp1).typ = ait_instruction) and
  6841. ((((taicpu(hp1).opcode = A_ADD) or
  6842. (taicpu(hp1).opcode = A_SUB)) and
  6843. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6844. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6845. (((taicpu(hp1).opcode = A_INC) or
  6846. (taicpu(hp1).opcode = A_DEC)) and
  6847. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6848. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6849. ((taicpu(hp1).opcode = A_LEA) and
  6850. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6851. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6852. (not GetNextInstruction(hp1,hp2) or
  6853. not instrReadsFlags(hp2)) Do
  6854. begin
  6855. TmpBool1 := False;
  6856. if taicpu(hp1).opcode=A_LEA then
  6857. begin
  6858. if (TmpRef.base = NR_NO) and
  6859. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6860. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6861. { Segment register isn't a concern here }
  6862. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6863. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6864. begin
  6865. TmpBool1 := True;
  6866. TmpBool2 := True;
  6867. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6868. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6869. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6870. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6871. RemoveInstruction(hp1);
  6872. end
  6873. end
  6874. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6875. begin
  6876. TmpBool1 := True;
  6877. TmpBool2 := True;
  6878. case taicpu(hp1).opcode of
  6879. A_ADD:
  6880. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6881. A_SUB:
  6882. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6883. else
  6884. internalerror(2019050536);
  6885. end;
  6886. RemoveInstruction(hp1);
  6887. end
  6888. else
  6889. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6890. (((taicpu(hp1).opcode = A_ADD) and
  6891. (TmpRef.base = NR_NO)) or
  6892. (taicpu(hp1).opcode = A_INC) or
  6893. (taicpu(hp1).opcode = A_DEC)) then
  6894. begin
  6895. TmpBool1 := True;
  6896. TmpBool2 := True;
  6897. case taicpu(hp1).opcode of
  6898. A_ADD:
  6899. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6900. A_INC:
  6901. inc(TmpRef.offset);
  6902. A_DEC:
  6903. dec(TmpRef.offset);
  6904. else
  6905. internalerror(2019050535);
  6906. end;
  6907. RemoveInstruction(hp1);
  6908. end;
  6909. end;
  6910. if TmpBool2
  6911. {$ifndef x86_64}
  6912. or
  6913. ((current_settings.optimizecputype < cpu_Pentium2) and
  6914. (taicpu(p).oper[0]^.val <= 3) and
  6915. not(cs_opt_size in current_settings.optimizerswitches))
  6916. {$endif x86_64}
  6917. then
  6918. begin
  6919. if not(TmpBool2) and
  6920. (taicpu(p).oper[0]^.val=1) then
  6921. begin
  6922. taicpu(p).opcode := A_ADD;
  6923. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6924. end
  6925. else
  6926. begin
  6927. taicpu(p).opcode := A_LEA;
  6928. taicpu(p).loadref(0, TmpRef);
  6929. end;
  6930. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6931. Result := True;
  6932. end;
  6933. end
  6934. {$ifndef x86_64}
  6935. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6936. begin
  6937. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6938. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6939. (unlike shl, which is only Tairable in the U pipe) }
  6940. if taicpu(p).oper[0]^.val=1 then
  6941. begin
  6942. taicpu(p).opcode := A_ADD;
  6943. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6944. Result := True;
  6945. end
  6946. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6947. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6948. else if (taicpu(p).opsize = S_L) and
  6949. (taicpu(p).oper[0]^.val<= 3) then
  6950. begin
  6951. reference_reset(tmpref,2,[]);
  6952. TmpRef.index := taicpu(p).oper[1]^.reg;
  6953. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6954. taicpu(p).opcode := A_LEA;
  6955. taicpu(p).loadref(0, TmpRef);
  6956. Result := True;
  6957. end;
  6958. end
  6959. {$endif x86_64}
  6960. else if
  6961. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6962. (
  6963. (
  6964. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6965. SetAndTest(hp1, hp2)
  6966. {$ifdef x86_64}
  6967. ) or
  6968. (
  6969. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6970. GetNextInstruction(hp1, hp2) and
  6971. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6972. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6973. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6974. {$endif x86_64}
  6975. )
  6976. ) and
  6977. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6978. begin
  6979. { Change:
  6980. shl x, %reg1
  6981. mov -(1<<x), %reg2
  6982. and %reg2, %reg1
  6983. Or:
  6984. shl x, %reg1
  6985. and -(1<<x), %reg1
  6986. To just:
  6987. shl x, %reg1
  6988. Since the and operation only zeroes bits that are already zero from the shl operation
  6989. }
  6990. case taicpu(p).oper[0]^.val of
  6991. 8:
  6992. mask:=$FFFFFFFFFFFFFF00;
  6993. 16:
  6994. mask:=$FFFFFFFFFFFF0000;
  6995. 32:
  6996. mask:=$FFFFFFFF00000000;
  6997. 63:
  6998. { Constant pre-calculated to prevent overflow errors with Int64 }
  6999. mask:=$8000000000000000;
  7000. else
  7001. begin
  7002. if taicpu(p).oper[0]^.val >= 64 then
  7003. { Shouldn't happen realistically, since the register
  7004. is guaranteed to be set to zero at this point }
  7005. mask := 0
  7006. else
  7007. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  7008. end;
  7009. end;
  7010. if taicpu(hp1).oper[0]^.val = mask then
  7011. begin
  7012. { Everything checks out, perform the optimisation, as long as
  7013. the FLAGS register isn't being used}
  7014. TransferUsedRegs(TmpUsedRegs);
  7015. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7016. {$ifdef x86_64}
  7017. if (hp1 <> hp2) then
  7018. begin
  7019. { "shl/mov/and" version }
  7020. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7021. { Don't do the optimisation if the FLAGS register is in use }
  7022. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  7023. begin
  7024. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  7025. { Don't remove the 'mov' instruction if its register is used elsewhere }
  7026. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  7027. begin
  7028. RemoveInstruction(hp1);
  7029. Result := True;
  7030. end;
  7031. { Only set Result to True if the 'mov' instruction was removed }
  7032. RemoveInstruction(hp2);
  7033. end;
  7034. end
  7035. else
  7036. {$endif x86_64}
  7037. begin
  7038. { "shl/and" version }
  7039. { Don't do the optimisation if the FLAGS register is in use }
  7040. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  7041. begin
  7042. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  7043. RemoveInstruction(hp1);
  7044. Result := True;
  7045. end;
  7046. end;
  7047. Exit;
  7048. end
  7049. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  7050. begin
  7051. { Even if the mask doesn't allow for its removal, we might be
  7052. able to optimise the mask for the "shl/and" version, which
  7053. may permit other peephole optimisations }
  7054. {$ifdef DEBUG_AOPTCPU}
  7055. mask := taicpu(hp1).oper[0]^.val and mask;
  7056. if taicpu(hp1).oper[0]^.val <> mask then
  7057. begin
  7058. DebugMsg(
  7059. SPeepholeOptimization +
  7060. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  7061. ' to $' + debug_tostr(mask) +
  7062. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  7063. taicpu(hp1).oper[0]^.val := mask;
  7064. end;
  7065. {$else DEBUG_AOPTCPU}
  7066. { If debugging is off, just set the operand even if it's the same }
  7067. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  7068. {$endif DEBUG_AOPTCPU}
  7069. end;
  7070. end;
  7071. {
  7072. change
  7073. shl/sal const,reg
  7074. <op> ...(...,reg,1),...
  7075. into
  7076. <op> ...(...,reg,1 shl const),...
  7077. if const in 1..3
  7078. }
  7079. if MatchOpType(taicpu(p), top_const, top_reg) and
  7080. (taicpu(p).oper[0]^.val in [1..3]) and
  7081. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7082. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  7083. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  7084. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  7085. MatchOpType(taicpu(hp1),top_ref))
  7086. ) and
  7087. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  7088. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  7089. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  7090. begin
  7091. TransferUsedRegs(TmpUsedRegs);
  7092. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7093. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  7094. begin
  7095. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7096. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7097. RemoveCurrentP(p);
  7098. Result:=true;
  7099. exit;
  7100. end;
  7101. end;
  7102. if MatchOpType(taicpu(p), top_const, top_reg) and
  7103. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7104. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7105. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7106. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7107. begin
  7108. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7109. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7110. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7111. {$ifdef x86_64}
  7112. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7113. {$endif x86_64}
  7114. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7115. begin
  7116. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7117. taicpu(hp1).opcode:=A_MOV;
  7118. taicpu(hp1).oper[0]^.val:=0;
  7119. end
  7120. else
  7121. begin
  7122. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7123. taicpu(hp1).oper[0]^.val:=shiftval;
  7124. end;
  7125. RemoveCurrentP(p);
  7126. Result:=true;
  7127. exit;
  7128. end;
  7129. end;
  7130. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7131. begin
  7132. case shr_size of
  7133. S_B:
  7134. { No valid combinations }
  7135. Result := False;
  7136. S_W:
  7137. Result := (Shift >= 8) and (movz_size = S_BW);
  7138. S_L:
  7139. Result :=
  7140. (Shift >= 24) { Any opsize is valid for this shift } or
  7141. ((Shift >= 16) and (movz_size = S_WL));
  7142. {$ifdef x86_64}
  7143. S_Q:
  7144. Result :=
  7145. (Shift >= 56) { Any opsize is valid for this shift } or
  7146. ((Shift >= 48) and (movz_size = S_WL));
  7147. {$endif x86_64}
  7148. else
  7149. InternalError(2022081510);
  7150. end;
  7151. end;
  7152. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7153. var
  7154. hp1, hp2: tai;
  7155. IdentityMask, Shift: TCGInt;
  7156. LimitSize: Topsize;
  7157. DoNotMerge: Boolean;
  7158. begin
  7159. if not MatchInstruction(p, A_SHR, []) then
  7160. InternalError(2025040301);
  7161. Result := False;
  7162. DoNotMerge := False;
  7163. Shift := taicpu(p).oper[0]^.val;
  7164. LimitSize := taicpu(p).opsize;
  7165. hp1 := p;
  7166. repeat
  7167. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7168. Exit;
  7169. case taicpu(hp1).opcode of
  7170. A_AND:
  7171. { Detect:
  7172. shr x, %reg
  7173. and y, %reg
  7174. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7175. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7176. (Post-peephole only)
  7177. }
  7178. if PostPeephole and
  7179. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7180. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7181. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7182. begin
  7183. { Make sure the FLAGS register isn't in use }
  7184. TransferUsedRegs(TmpUsedRegs);
  7185. hp2 := p;
  7186. repeat
  7187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7188. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7189. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7190. begin
  7191. { Generate the identity mask }
  7192. case taicpu(p).opsize of
  7193. S_B:
  7194. IdentityMask := $FF shr Shift;
  7195. S_W:
  7196. IdentityMask := $FFFF shr Shift;
  7197. S_L:
  7198. IdentityMask := $FFFFFFFF shr Shift;
  7199. {$ifdef x86_64}
  7200. S_Q:
  7201. { We need to force the operands to be unsigned 64-bit
  7202. integers otherwise the wrong value is generated }
  7203. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7204. {$endif x86_64}
  7205. else
  7206. InternalError(2022081501);
  7207. end;
  7208. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7209. begin
  7210. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7211. { All the possible 1 bits are covered, so we can remove the AND }
  7212. hp2 := tai(hp1.Previous);
  7213. RemoveInstruction(hp1);
  7214. { p wasn't actually changed, so don't set Result to True,
  7215. but a change was nonetheless made elsewhere }
  7216. Include(OptsToCheck, aoc_ForceNewIteration);
  7217. { Do another pass in case other AND or MOVZX instructions
  7218. follow }
  7219. hp1 := hp2;
  7220. Continue;
  7221. end;
  7222. end;
  7223. end;
  7224. A_TEST, A_CMP:
  7225. { Skip over relevant comparisons, but shift instructions must
  7226. now not be merged since the original value is being read }
  7227. begin
  7228. DoNotMerge := True;
  7229. Continue;
  7230. end;
  7231. A_Jcc:
  7232. { Skip over conditional jumps and relevant comparisons }
  7233. Continue;
  7234. A_MOVZX:
  7235. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7236. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7237. begin
  7238. { Since the original register is being read as is, subsequent
  7239. SHRs must not be merged at this point }
  7240. DoNotMerge := True;
  7241. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7242. begin
  7243. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7244. begin
  7245. { If the MOVZX instruction reads and writes the same register,
  7246. defer this to the post-peephole optimisation stage }
  7247. if PostPeephole then
  7248. begin
  7249. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7250. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7251. hp2 := tai(hp1.Previous);
  7252. RemoveInstruction(hp1);
  7253. hp1 := hp2;
  7254. end;
  7255. end
  7256. else { Different register target }
  7257. begin
  7258. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7259. taicpu(hp1).opcode := A_MOV;
  7260. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7261. case taicpu(hp1).opsize of
  7262. S_BW:
  7263. taicpu(hp1).opsize := S_W;
  7264. S_BL, S_WL:
  7265. taicpu(hp1).opsize := S_L;
  7266. else
  7267. InternalError(2022081503);
  7268. end;
  7269. { p itself hasn't changed, so no need to set Result to True }
  7270. Include(OptsToCheck, aoc_ForceNewIteration);
  7271. { See if there's anything afterwards that can be
  7272. optimised, since the input register hasn't changed }
  7273. Continue;
  7274. end;
  7275. Exit;
  7276. end
  7277. else if PostPeephole and
  7278. (Shift > 0) and
  7279. (taicpu(p).opsize = S_W) and
  7280. (taicpu(hp1).opsize = S_WL) and
  7281. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7282. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7283. begin
  7284. { Detect:
  7285. shr x, %ax (x > 0)
  7286. ...
  7287. movzwl %ax,%eax
  7288. -
  7289. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7290. But first, check to see if movzwl %ax,%eax can be removed...
  7291. }
  7292. hp2 := tai(hp1.Previous);
  7293. TransferUsedRegs(TmpUsedRegs);
  7294. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7295. if PostPeepholeOptMovZX(hp1) then
  7296. hp1 := hp2
  7297. else
  7298. begin
  7299. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7300. taicpu(hp1).opcode := A_CWDE;
  7301. taicpu(hp1).clearop(0);
  7302. taicpu(hp1).clearop(1);
  7303. taicpu(hp1).ops := 0;
  7304. end;
  7305. RestoreUsedRegs(TmpUsedRegs);
  7306. { Don't need to set aoc_ForceNewIteration if
  7307. PostPeepholeOptMovZX returned True because it's the
  7308. post-peephole stage }
  7309. end;
  7310. { Move onto the next instruction }
  7311. Continue;
  7312. end;
  7313. A_SHL, A_SAL, A_SHR:
  7314. if (taicpu(hp1).opsize <= LimitSize) and
  7315. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7316. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7317. begin
  7318. { Make sure the sizes don't exceed the register size limit
  7319. (measured by the shift value falling below the limit) }
  7320. if taicpu(hp1).opsize < LimitSize then
  7321. LimitSize := taicpu(hp1).opsize;
  7322. if taicpu(hp1).opcode = A_SHR then
  7323. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7324. else
  7325. begin
  7326. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7327. DoNotMerge := True;
  7328. end;
  7329. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7330. Exit;
  7331. { Since we've established that the combined shift is within
  7332. limits, we can actually combine the adjacent SHR
  7333. instructions even if they're different sizes }
  7334. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7335. begin
  7336. hp2 := tai(hp1.Previous);
  7337. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7338. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7339. RemoveInstruction(hp1);
  7340. hp1 := hp2;
  7341. { Though p has changed, only the constant has, and its
  7342. effects can still be detected on the next iteration of
  7343. the repeat..until loop }
  7344. Include(OptsToCheck, aoc_ForceNewIteration);
  7345. end;
  7346. { Move onto the next instruction }
  7347. Continue;
  7348. end;
  7349. else
  7350. ;
  7351. end;
  7352. { If the register isn't actually modified, move onto the next instruction,
  7353. but set DoNotMerge to True since the register is being read }
  7354. if (
  7355. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7356. the next instruction, whether or not it contains the register }
  7357. (cs_opt_level3 in current_settings.optimizerswitches) or
  7358. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7359. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7360. begin
  7361. DoNotMerge := True;
  7362. Continue;
  7363. end;
  7364. Break;
  7365. until False;
  7366. end;
  7367. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7368. begin
  7369. Result := False;
  7370. { All these optimisations work on "shr const,%reg" }
  7371. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7372. Exit;
  7373. Result := HandleSHRMerge(p, False);
  7374. end;
  7375. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7376. var
  7377. CurrentRef: TReference;
  7378. FullReg: TRegister;
  7379. hp1, hp2: tai;
  7380. begin
  7381. Result := False;
  7382. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7383. Exit;
  7384. { We assume you've checked if the operand is actually a reference by
  7385. this point. If it isn't, you'll most likely get an access violation }
  7386. CurrentRef := first_mov.oper[1]^.ref^;
  7387. { Memory must be aligned }
  7388. if (CurrentRef.offset mod 4) <> 0 then
  7389. Exit;
  7390. Inc(CurrentRef.offset);
  7391. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7392. if MatchOperand(second_mov.oper[0]^, 0) and
  7393. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7394. GetNextInstruction(second_mov, hp1) and
  7395. (hp1.typ = ait_instruction) and
  7396. (taicpu(hp1).opcode = A_MOV) and
  7397. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7398. (taicpu(hp1).oper[0]^.val = 0) then
  7399. begin
  7400. Inc(CurrentRef.offset);
  7401. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7402. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7403. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7404. begin
  7405. case taicpu(hp1).opsize of
  7406. S_B:
  7407. if GetNextInstruction(hp1, hp2) and
  7408. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7409. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7410. (taicpu(hp2).oper[0]^.val = 0) then
  7411. begin
  7412. Inc(CurrentRef.offset);
  7413. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7414. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7415. (taicpu(hp2).opsize = S_B) then
  7416. begin
  7417. RemoveInstruction(hp1);
  7418. RemoveInstruction(hp2);
  7419. first_mov.opsize := S_L;
  7420. if first_mov.oper[0]^.typ = top_reg then
  7421. begin
  7422. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7423. { Reuse second_mov as a MOVZX instruction }
  7424. second_mov.opcode := A_MOVZX;
  7425. second_mov.opsize := S_BL;
  7426. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7427. second_mov.loadreg(1, FullReg);
  7428. first_mov.oper[0]^.reg := FullReg;
  7429. asml.Remove(second_mov);
  7430. asml.InsertBefore(second_mov, first_mov);
  7431. end
  7432. else
  7433. { It's a value }
  7434. begin
  7435. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7436. RemoveInstruction(second_mov);
  7437. end;
  7438. Result := True;
  7439. Exit;
  7440. end;
  7441. end;
  7442. S_W:
  7443. begin
  7444. RemoveInstruction(hp1);
  7445. first_mov.opsize := S_L;
  7446. if first_mov.oper[0]^.typ = top_reg then
  7447. begin
  7448. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7449. { Reuse second_mov as a MOVZX instruction }
  7450. second_mov.opcode := A_MOVZX;
  7451. second_mov.opsize := S_BL;
  7452. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7453. second_mov.loadreg(1, FullReg);
  7454. first_mov.oper[0]^.reg := FullReg;
  7455. asml.Remove(second_mov);
  7456. asml.InsertBefore(second_mov, first_mov);
  7457. end
  7458. else
  7459. { It's a value }
  7460. begin
  7461. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7462. RemoveInstruction(second_mov);
  7463. end;
  7464. Result := True;
  7465. Exit;
  7466. end;
  7467. else
  7468. ;
  7469. end;
  7470. end;
  7471. end;
  7472. end;
  7473. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7474. { returns true if a "continue" should be done after this optimization }
  7475. var
  7476. hp1, hp2, hp3: tai;
  7477. begin
  7478. Result := false;
  7479. hp3 := nil;
  7480. if MatchOpType(taicpu(p),top_ref) and
  7481. GetNextInstruction(p, hp1) and
  7482. (hp1.typ = ait_instruction) and
  7483. (((taicpu(hp1).opcode = A_FLD) and
  7484. (taicpu(p).opcode = A_FSTP)) or
  7485. ((taicpu(p).opcode = A_FISTP) and
  7486. (taicpu(hp1).opcode = A_FILD))) and
  7487. MatchOpType(taicpu(hp1),top_ref) and
  7488. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7489. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7490. begin
  7491. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7492. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7493. GetNextInstruction(hp1, hp2) and
  7494. (((hp2.typ = ait_instruction) and
  7495. IsExitCode(hp2) and
  7496. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7497. not(assigned(current_procinfo.procdef.funcretsym) and
  7498. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7499. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7500. { fstp <temp>
  7501. fld <temp>
  7502. <dealloc> <temp>
  7503. }
  7504. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7505. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7506. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7507. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7508. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7509. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7510. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7511. )
  7512. )
  7513. ) then
  7514. begin
  7515. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7516. RemoveInstruction(hp1);
  7517. RemoveCurrentP(p, hp2);
  7518. { first case: exit code }
  7519. if hp2.typ = ait_instruction then
  7520. RemoveLastDeallocForFuncRes(p);
  7521. Result := true;
  7522. end
  7523. else
  7524. { we can do this only in fast math mode as fstp is rounding ...
  7525. ... still disabled as it breaks the compiler and/or rtl }
  7526. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7527. { ... or if another fstp equal to the first one follows }
  7528. GetNextInstruction(hp1,hp2) and
  7529. (hp2.typ = ait_instruction) and
  7530. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7531. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7532. begin
  7533. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7534. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7535. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7536. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7537. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7538. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7539. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7540. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7541. ) then
  7542. begin
  7543. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7544. RemoveCurrentP(p,hp2);
  7545. RemoveInstruction(hp1);
  7546. Result := true;
  7547. end
  7548. else if { fst can't store an extended/comp value }
  7549. (taicpu(p).opsize <> S_FX) and
  7550. (taicpu(p).opsize <> S_IQ) then
  7551. begin
  7552. if (taicpu(p).opcode = A_FSTP) then
  7553. taicpu(p).opcode := A_FST
  7554. else
  7555. taicpu(p).opcode := A_FIST;
  7556. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7557. RemoveInstruction(hp1);
  7558. Result := true;
  7559. end;
  7560. end;
  7561. end;
  7562. end;
  7563. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7564. var
  7565. hp1, hp2, hp3: tai;
  7566. begin
  7567. result:=false;
  7568. if MatchOpType(taicpu(p),top_reg) and
  7569. GetNextInstruction(p, hp1) and
  7570. (hp1.typ = Ait_Instruction) and
  7571. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7572. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7573. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7574. { change to
  7575. fld reg fxxx reg,st
  7576. fxxxp st, st1 (hp1)
  7577. Remark: non commutative operations must be reversed!
  7578. }
  7579. begin
  7580. case taicpu(hp1).opcode Of
  7581. A_FMULP,A_FADDP,
  7582. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7583. begin
  7584. case taicpu(hp1).opcode Of
  7585. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7586. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7587. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7588. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7589. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7590. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7591. else
  7592. internalerror(2019050534);
  7593. end;
  7594. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7595. taicpu(hp1).oper[1]^.reg := NR_ST;
  7596. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7597. RemoveCurrentP(p, hp1);
  7598. Result:=true;
  7599. exit;
  7600. end;
  7601. else
  7602. ;
  7603. end;
  7604. end
  7605. else
  7606. if MatchOpType(taicpu(p),top_ref) and
  7607. GetNextInstruction(p, hp2) and
  7608. (hp2.typ = Ait_Instruction) and
  7609. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7610. (taicpu(p).opsize in [S_FS, S_FL]) and
  7611. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7612. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7613. if GetLastInstruction(p, hp1) and
  7614. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7615. MatchOpType(taicpu(hp1),top_ref) and
  7616. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7617. if ((taicpu(hp2).opcode = A_FMULP) or
  7618. (taicpu(hp2).opcode = A_FADDP)) then
  7619. { change to
  7620. fld/fst mem1 (hp1) fld/fst mem1
  7621. fld mem1 (p) fadd/
  7622. faddp/ fmul st, st
  7623. fmulp st, st1 (hp2) }
  7624. begin
  7625. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7626. RemoveCurrentP(p, hp1);
  7627. if (taicpu(hp2).opcode = A_FADDP) then
  7628. taicpu(hp2).opcode := A_FADD
  7629. else
  7630. taicpu(hp2).opcode := A_FMUL;
  7631. taicpu(hp2).oper[1]^.reg := NR_ST;
  7632. end
  7633. else
  7634. { change to
  7635. fld/fst mem1 (hp1) fld/fst mem1
  7636. fld mem1 (p) fld st
  7637. }
  7638. begin
  7639. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7640. taicpu(p).changeopsize(S_FL);
  7641. taicpu(p).loadreg(0,NR_ST);
  7642. end
  7643. else
  7644. begin
  7645. case taicpu(hp2).opcode Of
  7646. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7647. { change to
  7648. fld/fst mem1 (hp1) fld/fst mem1
  7649. fld mem2 (p) fxxx mem2
  7650. fxxxp st, st1 (hp2) }
  7651. begin
  7652. case taicpu(hp2).opcode Of
  7653. A_FADDP: taicpu(p).opcode := A_FADD;
  7654. A_FMULP: taicpu(p).opcode := A_FMUL;
  7655. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7656. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7657. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7658. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7659. else
  7660. internalerror(2019050533);
  7661. end;
  7662. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7663. RemoveInstruction(hp2);
  7664. end
  7665. else
  7666. ;
  7667. end
  7668. end
  7669. end;
  7670. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7671. begin
  7672. Result := condition_in(cond1, cond2) or
  7673. { Not strictly subsets due to the actual flags checked, but because we're
  7674. comparing integers, E is a subset of AE and GE and their aliases }
  7675. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7676. end;
  7677. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7678. var
  7679. v: TCGInt;
  7680. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7681. FirstMatch, TempBool: Boolean;
  7682. NewReg: TRegister;
  7683. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7684. begin
  7685. Result:=false;
  7686. { All these optimisations need a next instruction }
  7687. if not GetNextInstruction(p, hp1) then
  7688. Exit;
  7689. true_hp1 := hp1;
  7690. { Search for:
  7691. cmp ###,###
  7692. j(c1) @lbl1
  7693. ...
  7694. @lbl:
  7695. cmp ###,### (same comparison as above)
  7696. j(c2) @lbl2
  7697. If c1 is a subset of c2, change to:
  7698. cmp ###,###
  7699. j(c1) @lbl2
  7700. (@lbl1 may become a dead label as a result)
  7701. }
  7702. { Also handle cases where there are multiple jumps in a row }
  7703. p_jump := hp1;
  7704. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7705. begin
  7706. Prefetch(p_jump.Next);
  7707. if IsJumpToLabel(taicpu(p_jump)) then
  7708. begin
  7709. { Do jump optimisations first in case the condition becomes
  7710. unnecessary }
  7711. TempBool := True;
  7712. if DoJumpOptimizations(p_jump, TempBool) or
  7713. not TempBool then
  7714. begin
  7715. if Assigned(p_jump) then
  7716. begin
  7717. { CollapseZeroDistJump will be set to the label or an align
  7718. before it after the jump if it optimises, whether or not
  7719. the label is live or dead }
  7720. if (p_jump.typ = ait_align) or
  7721. (
  7722. (p_jump.typ = ait_label) and
  7723. not (tai_label(p_jump).labsym.is_used)
  7724. ) then
  7725. GetNextInstruction(p_jump, p_jump);
  7726. end;
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7729. if not Assigned(p_jump) or
  7730. (
  7731. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7732. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7733. ) then
  7734. begin
  7735. { No more conditional jumps; conditional statement is no longer required }
  7736. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7737. RemoveCurrentP(p);
  7738. Result := True;
  7739. Exit;
  7740. end;
  7741. hp1 := p_jump;
  7742. Include(OptsToCheck, aoc_ForceNewIteration);
  7743. Continue;
  7744. end;
  7745. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7746. if GetNextInstruction(p_jump, hp2) and
  7747. (
  7748. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7749. not TempBool
  7750. ) then
  7751. begin
  7752. hp1 := p_jump;
  7753. Include(OptsToCheck, aoc_ForceNewIteration);
  7754. Continue;
  7755. end;
  7756. p_label := nil;
  7757. if Assigned(JumpLabel) then
  7758. p_label := getlabelwithsym(JumpLabel);
  7759. if Assigned(p_label) and
  7760. GetNextInstruction(p_label, p_dist) and
  7761. MatchInstruction(p_dist, A_CMP, []) and
  7762. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7763. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7764. GetNextInstruction(p_dist, hp1_dist) and
  7765. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7766. begin
  7767. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7768. if JumpLabel = JumpLabel_dist then
  7769. { This is an infinite loop }
  7770. Exit;
  7771. { Best optimisation when the first condition is a subset (or equal) of the second }
  7772. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7773. begin
  7774. { Any registers used here will already be allocated }
  7775. if Assigned(JumpLabel) then
  7776. JumpLabel.DecRefs;
  7777. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7778. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7779. Include(OptsToCheck, aoc_ForceNewIteration);
  7780. { Don't exit yet. Since p and p_jump haven't actually been
  7781. removed, we can check for more on this iteration }
  7782. end
  7783. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7784. GetNextInstruction(hp1_dist, hp1_label) and
  7785. (hp1_label.typ = ait_label) then
  7786. begin
  7787. JumpLabel_far := tai_label(hp1_label).labsym;
  7788. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7789. { This is an infinite loop }
  7790. Exit;
  7791. if Assigned(JumpLabel_far) then
  7792. begin
  7793. { In this situation, if the first jump branches, the second one will never,
  7794. branch so change the destination label to after the second jump }
  7795. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7796. if Assigned(JumpLabel) then
  7797. JumpLabel.DecRefs;
  7798. JumpLabel_far.IncRefs;
  7799. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7800. Result := True;
  7801. { Don't exit yet. Since p and p_jump haven't actually been
  7802. removed, we can check for more on this iteration }
  7803. Continue;
  7804. end;
  7805. end;
  7806. end;
  7807. end;
  7808. { Search for:
  7809. cmp ###,###
  7810. j(c1) @lbl1
  7811. cmp ###,### (same as first)
  7812. Remove second cmp
  7813. }
  7814. if GetNextInstruction(p_jump, hp2) and
  7815. (
  7816. (
  7817. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7818. (
  7819. (
  7820. MatchOpType(taicpu(p), top_const, top_reg) and
  7821. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7822. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7823. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7824. ) or (
  7825. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7826. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7827. )
  7828. )
  7829. ) or (
  7830. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7831. MatchOperand(taicpu(p).oper[0]^, 0) and
  7832. (taicpu(p).oper[1]^.typ = top_reg) and
  7833. MatchInstruction(hp2, A_TEST, []) and
  7834. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7835. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7836. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7837. )
  7838. ) then
  7839. begin
  7840. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7841. TransferUsedRegs(TmpUsedRegs);
  7842. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7843. RemoveInstruction(hp2);
  7844. Result := True;
  7845. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7846. end
  7847. else
  7848. begin
  7849. { hp2 is the next instruction, so save time and just set p_jump
  7850. to it instead of calling GetNextInstruction below }
  7851. p_jump := hp2;
  7852. Continue;
  7853. end;
  7854. GetNextInstruction(p_jump, p_jump);
  7855. end;
  7856. if (
  7857. { Don't call GetNextInstruction again if we already have it }
  7858. (true_hp1 = p_jump) or
  7859. GetNextInstruction(p, hp1)
  7860. ) and
  7861. MatchInstruction(hp1, A_Jcc, []) and
  7862. IsJumpToLabel(taicpu(hp1)) and
  7863. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7864. GetNextInstruction(hp1, hp2) then
  7865. begin
  7866. {
  7867. cmp x, y (or "cmp y, x")
  7868. je @lbl
  7869. mov x, y
  7870. @lbl:
  7871. (x and y can be constants, registers or references)
  7872. Change to:
  7873. mov x, y (x and y will always be equal in the end)
  7874. @lbl: (may beceome a dead label)
  7875. Also:
  7876. cmp x, y (or "cmp y, x")
  7877. jne @lbl
  7878. mov x, y
  7879. @lbl:
  7880. (x and y can be constants, registers or references)
  7881. Change to:
  7882. Absolutely nothing! (Except @lbl if it's still live)
  7883. }
  7884. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7885. (
  7886. (
  7887. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7888. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7889. ) or (
  7890. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7891. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7892. )
  7893. ) and
  7894. GetNextInstruction(hp2, hp1_label) and
  7895. (hp1_label.typ = ait_label) and
  7896. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7897. begin
  7898. tai_label(hp1_label).labsym.DecRefs;
  7899. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7900. begin
  7901. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7902. RemoveInstruction(hp2);
  7903. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7904. end
  7905. else
  7906. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7907. RemoveInstruction(hp1);
  7908. RemoveCurrentp(p, hp2);
  7909. Result := True;
  7910. Exit;
  7911. end;
  7912. {
  7913. Try to optimise the following:
  7914. cmp $x,### ($x and $y can be registers or constants)
  7915. je @lbl1 (only reference)
  7916. cmp $y,### (### are identical)
  7917. @Lbl:
  7918. sete %reg1
  7919. Change to:
  7920. cmp $x,###
  7921. sete %reg2 (allocate new %reg2)
  7922. cmp $y,###
  7923. sete %reg1
  7924. orb %reg2,%reg1
  7925. (dealloc %reg2)
  7926. This adds an instruction (so don't perform under -Os), but it removes
  7927. a conditional branch.
  7928. }
  7929. if not (cs_opt_size in current_settings.optimizerswitches) and
  7930. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7931. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7932. { The first operand of CMP instructions can only be a register or
  7933. immediate anyway, so no need to check }
  7934. GetNextInstruction(hp2, p_label) and
  7935. (p_label.typ = ait_label) and
  7936. (tai_label(p_label).labsym.getrefs = 1) and
  7937. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7938. GetNextInstruction(p_label, p_dist) and
  7939. MatchInstruction(p_dist, A_SETcc, []) and
  7940. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7941. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7942. begin
  7943. TransferUsedRegs(TmpUsedRegs);
  7944. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7945. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7946. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7947. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7948. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7949. { Get the instruction after the SETcc instruction so we can
  7950. allocate a new register over the entire range }
  7951. GetNextInstruction(p_dist, hp1_dist) then
  7952. begin
  7953. { Register can appear in p if it's not used afterwards, so only
  7954. allocate between hp1 and hp1_dist }
  7955. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7956. if NewReg <> NR_NO then
  7957. begin
  7958. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7959. { Change the jump instruction into a SETcc instruction }
  7960. taicpu(hp1).opcode := A_SETcc;
  7961. taicpu(hp1).opsize := S_B;
  7962. taicpu(hp1).loadreg(0, NewReg);
  7963. { This is now a dead label }
  7964. tai_label(p_label).labsym.decrefs;
  7965. { Prefer adding before the next instruction so the FLAGS
  7966. register is deallicated first }
  7967. AsmL.InsertBefore(
  7968. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7969. hp1_dist
  7970. );
  7971. Result := True;
  7972. { Don't exit yet, as p wasn't changed and hp1, while
  7973. modified, is still intact and might be optimised by the
  7974. SETcc optimisation below }
  7975. end;
  7976. end;
  7977. end;
  7978. end;
  7979. if (taicpu(p).oper[0]^.typ = top_const) and
  7980. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7981. begin
  7982. if (taicpu(p).oper[0]^.val = 0) and
  7983. (taicpu(p).oper[1]^.typ = top_reg) then
  7984. begin
  7985. hp2 := p;
  7986. FirstMatch := True;
  7987. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7988. anything meaningful once it's converted to "test %reg,%reg";
  7989. additionally, some jumps will always (or never) branch, so
  7990. evaluate every jump immediately following the
  7991. comparison, optimising the conditions if possible.
  7992. Similarly with SETcc... those that are always set to 0 or 1
  7993. are changed to MOV instructions }
  7994. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7995. (
  7996. GetNextInstruction(hp2, hp1) and
  7997. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7998. ) do
  7999. begin
  8000. Prefetch(hp1.Next);
  8001. FirstMatch := False;
  8002. case taicpu(hp1).condition of
  8003. C_B, C_C, C_NAE, C_O:
  8004. { For B/NAE:
  8005. Will never branch since an unsigned integer can never be below zero
  8006. For C/O:
  8007. Result cannot overflow because 0 is being subtracted
  8008. }
  8009. begin
  8010. if taicpu(hp1).opcode = A_Jcc then
  8011. begin
  8012. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  8013. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  8014. RemoveInstruction(hp1);
  8015. { Since hp1 was deleted, hp2 must not be updated }
  8016. Continue;
  8017. end
  8018. else
  8019. begin
  8020. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  8021. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  8022. taicpu(hp1).opcode := A_MOV;
  8023. taicpu(hp1).ops := 2;
  8024. taicpu(hp1).condition := C_None;
  8025. taicpu(hp1).opsize := S_B;
  8026. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8027. taicpu(hp1).loadconst(0, 0);
  8028. end;
  8029. end;
  8030. C_BE, C_NA:
  8031. begin
  8032. { Will only branch if equal to zero }
  8033. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  8034. taicpu(hp1).condition := C_E;
  8035. end;
  8036. C_A, C_NBE:
  8037. begin
  8038. { Will only branch if not equal to zero }
  8039. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  8040. taicpu(hp1).condition := C_NE;
  8041. end;
  8042. C_AE, C_NB, C_NC, C_NO:
  8043. begin
  8044. { Will always branch }
  8045. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  8046. if taicpu(hp1).opcode = A_Jcc then
  8047. begin
  8048. MakeUnconditional(taicpu(hp1));
  8049. { Any jumps/set that follow will now be dead code }
  8050. RemoveDeadCodeAfterJump(taicpu(hp1));
  8051. Break;
  8052. end
  8053. else
  8054. begin
  8055. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  8056. taicpu(hp1).opcode := A_MOV;
  8057. taicpu(hp1).ops := 2;
  8058. taicpu(hp1).condition := C_None;
  8059. taicpu(hp1).opsize := S_B;
  8060. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8061. taicpu(hp1).loadconst(0, 1);
  8062. end;
  8063. end;
  8064. C_None:
  8065. InternalError(2020012201);
  8066. C_P, C_PE, C_NP, C_PO:
  8067. { We can't handle parity checks and they should never be generated
  8068. after a general-purpose CMP (it's used in some floating-point
  8069. comparisons that don't use CMP) }
  8070. InternalError(2020012202);
  8071. else
  8072. { Zero/Equality, Sign, their complements and all of the
  8073. signed comparisons do not need to be converted };
  8074. end;
  8075. hp2 := hp1;
  8076. end;
  8077. { Convert the instruction to a TEST }
  8078. taicpu(p).opcode := A_TEST;
  8079. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8080. Result := True;
  8081. Exit;
  8082. end
  8083. else
  8084. begin
  8085. TransferUsedRegs(TmpUsedRegs);
  8086. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8087. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8088. begin
  8089. if (taicpu(p).oper[0]^.val = 1) and
  8090. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  8091. begin
  8092. { Convert; To:
  8093. cmp $1,r/m cmp $0,r/m
  8094. jl @lbl jle @lbl
  8095. (Also do inverted conditions)
  8096. }
  8097. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8098. taicpu(p).oper[0]^.val := 0;
  8099. if taicpu(hp1).condition in [C_L, C_NGE] then
  8100. taicpu(hp1).condition := C_LE
  8101. else
  8102. taicpu(hp1).condition := C_NLE;
  8103. { If the instruction is now "cmp $0,%reg", convert it to a
  8104. TEST (and effectively do the work of the "cmp $0,%reg" in
  8105. the block above)
  8106. }
  8107. if (taicpu(p).oper[1]^.typ = top_reg) then
  8108. begin
  8109. taicpu(p).opcode := A_TEST;
  8110. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8111. end;
  8112. Result := True;
  8113. Exit;
  8114. end
  8115. else if (taicpu(p).oper[1]^.typ = top_reg)
  8116. {$ifdef x86_64}
  8117. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8118. {$endif x86_64}
  8119. then
  8120. begin
  8121. { cmp register,$8000 neg register
  8122. je target --> jo target
  8123. .... only if register is deallocated before jump.}
  8124. case Taicpu(p).opsize of
  8125. S_B: v:=$80;
  8126. S_W: v:=$8000;
  8127. S_L: v:=qword($80000000);
  8128. else
  8129. internalerror(2013112905);
  8130. end;
  8131. if (taicpu(p).oper[0]^.val=v) and
  8132. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8133. begin
  8134. TransferUsedRegs(TmpUsedRegs);
  8135. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8136. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8137. begin
  8138. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8139. Taicpu(p).opcode:=A_NEG;
  8140. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8141. Taicpu(p).clearop(1);
  8142. Taicpu(p).ops:=1;
  8143. if Taicpu(hp1).condition=C_E then
  8144. Taicpu(hp1).condition:=C_O
  8145. else
  8146. Taicpu(hp1).condition:=C_NO;
  8147. Result:=true;
  8148. exit;
  8149. end;
  8150. end;
  8151. end;
  8152. end;
  8153. end;
  8154. end;
  8155. if TrySwapMovCmp(p, hp1) then
  8156. begin
  8157. Result := True;
  8158. Exit;
  8159. end;
  8160. end;
  8161. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8162. var
  8163. hp1: tai;
  8164. begin
  8165. {
  8166. remove the second (v)pxor from
  8167. pxor reg,reg
  8168. ...
  8169. pxor reg,reg
  8170. }
  8171. Result:=false;
  8172. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8173. MatchOpType(taicpu(p),top_reg,top_reg) and
  8174. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8175. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8176. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8177. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8178. begin
  8179. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8180. RemoveInstruction(hp1);
  8181. Result:=true;
  8182. Exit;
  8183. end
  8184. {
  8185. replace
  8186. pxor reg1,reg1
  8187. movapd/s reg1,reg2
  8188. dealloc reg1
  8189. by
  8190. pxor reg2,reg2
  8191. }
  8192. else if GetNextInstruction(p,hp1) and
  8193. { we mix single and double opperations here because we assume that the compiler
  8194. generates vmovapd only after double operations and vmovaps only after single operations }
  8195. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8196. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8197. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8198. (taicpu(p).oper[0]^.typ=top_reg) then
  8199. begin
  8200. TransferUsedRegs(TmpUsedRegs);
  8201. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8202. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8203. begin
  8204. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8205. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8206. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8207. RemoveInstruction(hp1);
  8208. result:=true;
  8209. end;
  8210. end;
  8211. end;
  8212. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8213. var
  8214. hp1: tai;
  8215. begin
  8216. {
  8217. remove the second (v)pxor from
  8218. (v)pxor reg,reg
  8219. ...
  8220. (v)pxor reg,reg
  8221. }
  8222. Result:=false;
  8223. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8224. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8225. begin
  8226. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8227. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8228. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8229. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8230. begin
  8231. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8232. RemoveInstruction(hp1);
  8233. Result:=true;
  8234. Exit;
  8235. end;
  8236. {$ifdef x86_64}
  8237. {
  8238. replace
  8239. vpxor reg1,reg1,reg1
  8240. vmov reg,mem
  8241. by
  8242. movq $0,mem
  8243. }
  8244. if GetNextInstruction(p,hp1) and
  8245. MatchInstruction(hp1,A_VMOVSD,[]) and
  8246. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8247. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8248. begin
  8249. TransferUsedRegs(TmpUsedRegs);
  8250. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8251. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8252. begin
  8253. taicpu(hp1).loadconst(0,0);
  8254. taicpu(hp1).opcode:=A_MOV;
  8255. taicpu(hp1).opsize:=S_Q;
  8256. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8257. RemoveCurrentP(p);
  8258. result:=true;
  8259. Exit;
  8260. end;
  8261. end;
  8262. {$endif x86_64}
  8263. end
  8264. {
  8265. replace
  8266. vpxor reg1,reg1,reg2
  8267. by
  8268. vpxor reg2,reg2,reg2
  8269. to avoid unncessary data dependencies
  8270. }
  8271. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8272. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8273. begin
  8274. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8275. { avoid unncessary data dependency }
  8276. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8277. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8278. result:=true;
  8279. exit;
  8280. end;
  8281. Result:=OptPass1VOP(p);
  8282. end;
  8283. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8284. var
  8285. hp1 : tai;
  8286. begin
  8287. result:=false;
  8288. { replace
  8289. IMul const,%mreg1,%mreg2
  8290. Mov %reg2,%mreg3
  8291. dealloc %mreg3
  8292. by
  8293. Imul const,%mreg1,%mreg23
  8294. }
  8295. if (taicpu(p).ops=3) and
  8296. GetNextInstruction(p,hp1) and
  8297. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8298. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8299. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8300. begin
  8301. TransferUsedRegs(TmpUsedRegs);
  8302. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8303. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8304. begin
  8305. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8306. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8307. RemoveInstruction(hp1);
  8308. result:=true;
  8309. end;
  8310. end;
  8311. end;
  8312. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8313. var
  8314. hp1 : tai;
  8315. begin
  8316. result:=false;
  8317. { replace
  8318. IMul %reg0,%reg1,%reg2
  8319. Mov %reg2,%reg3
  8320. dealloc %reg2
  8321. by
  8322. Imul %reg0,%reg1,%reg3
  8323. }
  8324. if GetNextInstruction(p,hp1) and
  8325. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8326. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8327. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8328. begin
  8329. TransferUsedRegs(TmpUsedRegs);
  8330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8331. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8332. begin
  8333. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8334. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8335. RemoveInstruction(hp1);
  8336. result:=true;
  8337. end;
  8338. end;
  8339. end;
  8340. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8341. var
  8342. hp1: tai;
  8343. begin
  8344. Result:=false;
  8345. { get rid of
  8346. (v)cvtss2sd reg0,<reg1,>reg2
  8347. (v)cvtss2sd reg2,<reg2,>reg0
  8348. }
  8349. if GetNextInstruction(p,hp1) and
  8350. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8351. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8352. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8353. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8354. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8355. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8356. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8357. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8358. )
  8359. ) then
  8360. begin
  8361. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8362. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8363. begin
  8364. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8365. RemoveCurrentP(p);
  8366. RemoveInstruction(hp1);
  8367. end
  8368. else
  8369. begin
  8370. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8371. if taicpu(hp1).opcode=A_CVTSD2SS then
  8372. begin
  8373. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8374. taicpu(p).opcode:=A_MOVAPS;
  8375. end
  8376. else
  8377. begin
  8378. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8379. taicpu(p).opcode:=A_VMOVAPS;
  8380. end;
  8381. taicpu(p).ops:=2;
  8382. RemoveInstruction(hp1);
  8383. end;
  8384. Result:=true;
  8385. Exit;
  8386. end;
  8387. end;
  8388. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8389. var
  8390. hp1, hp2, hp3, hp4, hp5: tai;
  8391. ThisReg: TRegister;
  8392. begin
  8393. Result := False;
  8394. if not GetNextInstruction(p,hp1) then
  8395. Exit;
  8396. {
  8397. convert
  8398. j<c> .L1
  8399. mov 1,reg
  8400. jmp .L2
  8401. .L1
  8402. mov 0,reg
  8403. .L2
  8404. into
  8405. mov 0,reg
  8406. set<not(c)> reg
  8407. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8408. would destroy the flag contents
  8409. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8410. executed at the same time as a previous comparison.
  8411. set<not(c)> reg
  8412. movzx reg, reg
  8413. }
  8414. if MatchInstruction(hp1,A_MOV,[]) and
  8415. (taicpu(hp1).oper[0]^.typ = top_const) and
  8416. (
  8417. (
  8418. (taicpu(hp1).oper[1]^.typ = top_reg)
  8419. {$ifdef i386}
  8420. { Under i386, ESI, EDI, EBP and ESP
  8421. don't have an 8-bit representation }
  8422. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8423. {$endif i386}
  8424. ) or (
  8425. {$ifdef i386}
  8426. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8427. {$endif i386}
  8428. (taicpu(hp1).opsize = S_B)
  8429. )
  8430. ) and
  8431. GetNextInstruction(hp1,hp2) and
  8432. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8433. GetNextInstruction(hp2,hp3) and
  8434. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8435. GetNextInstruction(hp3,hp4) and
  8436. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8437. (taicpu(hp4).oper[0]^.typ = top_const) and
  8438. (
  8439. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8440. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8441. ) and
  8442. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8443. GetNextInstruction(hp4,hp5) and
  8444. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8445. begin
  8446. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8447. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8448. tai_label(hp3).labsym.DecRefs;
  8449. { If this isn't the only reference to the middle label, we can
  8450. still make a saving - only that the first jump and everything
  8451. that follows will remain. }
  8452. if (tai_label(hp3).labsym.getrefs = 0) then
  8453. begin
  8454. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8455. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8456. else
  8457. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8458. { remove jump, first label and second MOV (also catching any aligns) }
  8459. repeat
  8460. if not GetNextInstruction(hp2, hp3) then
  8461. InternalError(2021040810);
  8462. RemoveInstruction(hp2);
  8463. hp2 := hp3;
  8464. until hp2 = hp5;
  8465. { Don't decrement reference count before the removal loop
  8466. above, otherwise GetNextInstruction won't stop on the
  8467. the label }
  8468. tai_label(hp5).labsym.DecRefs;
  8469. end
  8470. else
  8471. begin
  8472. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8473. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8474. else
  8475. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8476. end;
  8477. taicpu(p).opcode:=A_SETcc;
  8478. taicpu(p).opsize:=S_B;
  8479. taicpu(p).is_jmp:=False;
  8480. if taicpu(hp1).opsize=S_B then
  8481. begin
  8482. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8483. if taicpu(hp1).oper[1]^.typ = top_reg then
  8484. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8485. RemoveInstruction(hp1);
  8486. end
  8487. else
  8488. begin
  8489. { Will be a register because the size can't be S_B otherwise }
  8490. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8491. taicpu(p).loadreg(0, ThisReg);
  8492. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8493. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8494. begin
  8495. case taicpu(hp1).opsize of
  8496. S_W:
  8497. taicpu(hp1).opsize := S_BW;
  8498. S_L:
  8499. taicpu(hp1).opsize := S_BL;
  8500. {$ifdef x86_64}
  8501. S_Q:
  8502. begin
  8503. taicpu(hp1).opsize := S_BL;
  8504. { Change the destination register to 32-bit }
  8505. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8506. end;
  8507. {$endif x86_64}
  8508. else
  8509. InternalError(2021040820);
  8510. end;
  8511. taicpu(hp1).opcode := A_MOVZX;
  8512. taicpu(hp1).loadreg(0, ThisReg);
  8513. end
  8514. else
  8515. begin
  8516. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8517. { hp1 is already a MOV instruction with the correct register }
  8518. taicpu(hp1).loadconst(0, 0);
  8519. { Inserting it right before p will guarantee that the flags are also tracked }
  8520. asml.Remove(hp1);
  8521. asml.InsertBefore(hp1, p);
  8522. end;
  8523. end;
  8524. Result:=true;
  8525. exit;
  8526. end
  8527. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8528. Result := TryJccStcClcOpt(p, hp1)
  8529. else if (hp1.typ = ait_label) then
  8530. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8531. end;
  8532. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8533. var
  8534. hp1, hp2, hp3: tai;
  8535. SourceRef, TargetRef: TReference;
  8536. CurrentReg: TRegister;
  8537. begin
  8538. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8539. if not UseAVX then
  8540. InternalError(2021100501);
  8541. Result := False;
  8542. { Look for the following to simplify:
  8543. vmovdqa/u x(mem1), %xmmreg
  8544. vmovdqa/u %xmmreg, y(mem2)
  8545. vmovdqa/u x+16(mem1), %xmmreg
  8546. vmovdqa/u %xmmreg, y+16(mem2)
  8547. Change to:
  8548. vmovdqa/u x(mem1), %ymmreg
  8549. vmovdqa/u %ymmreg, y(mem2)
  8550. vpxor %ymmreg, %ymmreg, %ymmreg
  8551. ( The VPXOR instruction is to zero the upper half, thus removing the
  8552. need to call the potentially expensive VZEROUPPER instruction. Other
  8553. peephole optimisations can remove VPXOR if it's unnecessary )
  8554. }
  8555. TransferUsedRegs(TmpUsedRegs);
  8556. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8557. { NOTE: In the optimisations below, if the references dictate that an
  8558. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8559. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8560. if (taicpu(p).opsize = S_XMM) and
  8561. MatchOpType(taicpu(p), top_ref, top_reg) and
  8562. GetNextInstruction(p, hp1) and
  8563. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8564. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8565. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8566. begin
  8567. SourceRef := taicpu(p).oper[0]^.ref^;
  8568. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8569. if GetNextInstruction(hp1, hp2) and
  8570. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8571. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8572. begin
  8573. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8574. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8575. Inc(SourceRef.offset, 16);
  8576. { Reuse the register in the first block move }
  8577. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8578. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8579. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8580. begin
  8581. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8582. Inc(TargetRef.offset, 16);
  8583. if GetNextInstruction(hp2, hp3) and
  8584. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8585. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8586. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8587. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8588. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8589. begin
  8590. { Update the register tracking to the new size }
  8591. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8592. { Remember that the offsets are 16 ahead }
  8593. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8594. if not (
  8595. ((SourceRef.offset mod 32) = 16) and
  8596. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8597. ) then
  8598. taicpu(p).opcode := A_VMOVDQU;
  8599. taicpu(p).opsize := S_YMM;
  8600. taicpu(p).oper[1]^.reg := CurrentReg;
  8601. if not (
  8602. ((TargetRef.offset mod 32) = 16) and
  8603. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8604. ) then
  8605. taicpu(hp1).opcode := A_VMOVDQU;
  8606. taicpu(hp1).opsize := S_YMM;
  8607. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8608. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8609. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8610. if (pi_uses_ymm in current_procinfo.flags) then
  8611. RemoveInstruction(hp2)
  8612. else
  8613. begin
  8614. taicpu(hp2).opcode := A_VPXOR;
  8615. taicpu(hp2).opsize := S_YMM;
  8616. taicpu(hp2).loadreg(0, CurrentReg);
  8617. taicpu(hp2).loadreg(1, CurrentReg);
  8618. taicpu(hp2).loadreg(2, CurrentReg);
  8619. taicpu(hp2).ops := 3;
  8620. end;
  8621. RemoveInstruction(hp3);
  8622. Result := True;
  8623. Exit;
  8624. end;
  8625. end
  8626. else
  8627. begin
  8628. { See if the next references are 16 less rather than 16 greater }
  8629. Dec(SourceRef.offset, 32); { -16 the other way }
  8630. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8631. begin
  8632. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8633. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8634. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8635. GetNextInstruction(hp2, hp3) and
  8636. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8637. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8638. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8639. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8640. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8641. begin
  8642. { Update the register tracking to the new size }
  8643. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8644. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8645. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8646. if not(
  8647. ((SourceRef.offset mod 32) = 0) and
  8648. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8649. ) then
  8650. taicpu(hp2).opcode := A_VMOVDQU;
  8651. taicpu(hp2).opsize := S_YMM;
  8652. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8653. if not (
  8654. ((TargetRef.offset mod 32) = 0) and
  8655. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8656. ) then
  8657. taicpu(hp3).opcode := A_VMOVDQU;
  8658. taicpu(hp3).opsize := S_YMM;
  8659. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8660. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8661. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8662. if (pi_uses_ymm in current_procinfo.flags) then
  8663. RemoveInstruction(hp1)
  8664. else
  8665. begin
  8666. taicpu(hp1).opcode := A_VPXOR;
  8667. taicpu(hp1).opsize := S_YMM;
  8668. taicpu(hp1).loadreg(0, CurrentReg);
  8669. taicpu(hp1).loadreg(1, CurrentReg);
  8670. taicpu(hp1).loadreg(2, CurrentReg);
  8671. taicpu(hp1).ops := 3;
  8672. Asml.Remove(hp1);
  8673. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8674. end;
  8675. RemoveCurrentP(p, hp2);
  8676. Result := True;
  8677. Exit;
  8678. end;
  8679. end;
  8680. end;
  8681. end;
  8682. end;
  8683. end;
  8684. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8685. var
  8686. hp2, hp3, first_assignment: tai;
  8687. IncCount, OperIdx: Integer;
  8688. OrigLabel: TAsmLabel;
  8689. begin
  8690. Count := 0;
  8691. Result := False;
  8692. first_assignment := nil;
  8693. if (LoopCount >= 20) then
  8694. begin
  8695. { Guard against infinite loops }
  8696. Exit;
  8697. end;
  8698. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8699. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8700. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8701. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8702. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8703. Exit;
  8704. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8705. {
  8706. change
  8707. jmp .L1
  8708. ...
  8709. .L1:
  8710. mov ##, ## ( multiple movs possible )
  8711. jmp/ret
  8712. into
  8713. mov ##, ##
  8714. jmp/ret
  8715. }
  8716. if not Assigned(hp1) then
  8717. begin
  8718. hp1 := GetLabelWithSym(OrigLabel);
  8719. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8720. Exit;
  8721. end;
  8722. hp2 := hp1;
  8723. while Assigned(hp2) do
  8724. begin
  8725. if Assigned(hp2) and (hp2.typ = ait_label) then
  8726. SkipLabels(hp2,hp2);
  8727. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8728. Break;
  8729. case taicpu(hp2).opcode of
  8730. A_MOVSD:
  8731. begin
  8732. if taicpu(hp2).ops = 0 then
  8733. { Wrong MOVSD }
  8734. Break;
  8735. Inc(Count);
  8736. if Count >= 5 then
  8737. { Too many to be worthwhile }
  8738. Break;
  8739. GetNextInstruction(hp2, hp2);
  8740. Continue;
  8741. end;
  8742. A_MOV,
  8743. A_MOVD,
  8744. A_MOVQ,
  8745. A_MOVSX,
  8746. {$ifdef x86_64}
  8747. A_MOVSXD,
  8748. {$endif x86_64}
  8749. A_MOVZX,
  8750. A_MOVAPS,
  8751. A_MOVUPS,
  8752. A_MOVSS,
  8753. A_MOVAPD,
  8754. A_MOVUPD,
  8755. A_MOVDQA,
  8756. A_MOVDQU,
  8757. A_VMOVSS,
  8758. A_VMOVAPS,
  8759. A_VMOVUPS,
  8760. A_VMOVSD,
  8761. A_VMOVAPD,
  8762. A_VMOVUPD,
  8763. A_VMOVDQA,
  8764. A_VMOVDQU:
  8765. begin
  8766. Inc(Count);
  8767. if Count >= 5 then
  8768. { Too many to be worthwhile }
  8769. Break;
  8770. GetNextInstruction(hp2, hp2);
  8771. Continue;
  8772. end;
  8773. A_JMP:
  8774. begin
  8775. { Guard against infinite loops }
  8776. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8777. Exit;
  8778. { Analyse this jump first in case it also duplicates assignments }
  8779. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8780. begin
  8781. { Something did change! }
  8782. Result := True;
  8783. Inc(Count, IncCount);
  8784. if Count >= 5 then
  8785. begin
  8786. { Too many to be worthwhile }
  8787. Exit;
  8788. end;
  8789. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8790. Break;
  8791. end;
  8792. Result := True;
  8793. Break;
  8794. end;
  8795. A_RET:
  8796. begin
  8797. Result := True;
  8798. Break;
  8799. end;
  8800. else
  8801. Break;
  8802. end;
  8803. end;
  8804. if Result then
  8805. begin
  8806. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8807. if Count = 0 then
  8808. begin
  8809. Result := False;
  8810. Exit;
  8811. end;
  8812. TransferUsedRegs(TmpUsedRegs);
  8813. hp3 := p;
  8814. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8815. while True do
  8816. begin
  8817. if Assigned(hp1) and (hp1.typ = ait_label) then
  8818. SkipLabels(hp1,hp1);
  8819. case hp1.typ of
  8820. ait_regalloc:
  8821. if tai_regalloc(hp1).ratype = ra_dealloc then
  8822. begin
  8823. { Duplicate the register deallocation... }
  8824. hp3:=tai(hp1.getcopy);
  8825. if first_assignment = nil then
  8826. first_assignment := hp3;
  8827. asml.InsertBefore(hp3, p);
  8828. { ... but also reallocate it after the jump }
  8829. hp3:=tai(hp1.getcopy);
  8830. tai_regalloc(hp3).ratype := ra_alloc;
  8831. asml.InsertAfter(hp3, p);
  8832. end;
  8833. ait_instruction:
  8834. case taicpu(hp1).opcode of
  8835. A_JMP:
  8836. begin
  8837. { Change the original jump to the new destination }
  8838. OrigLabel.decrefs;
  8839. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8840. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8841. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8842. if not Assigned(first_assignment) then
  8843. InternalError(2021040810)
  8844. else
  8845. p := first_assignment;
  8846. Exit;
  8847. end;
  8848. A_RET:
  8849. begin
  8850. { Now change the jump into a RET instruction }
  8851. ConvertJumpToRET(p, hp1);
  8852. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8853. if not Assigned(first_assignment) then
  8854. InternalError(2021040811)
  8855. else
  8856. p := first_assignment;
  8857. Exit;
  8858. end;
  8859. else
  8860. begin
  8861. { Duplicate the MOV instruction }
  8862. hp3:=tai(hp1.getcopy);
  8863. if first_assignment = nil then
  8864. first_assignment := hp3;
  8865. asml.InsertBefore(hp3, p);
  8866. { Make sure the compiler knows about any final registers written here }
  8867. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8868. with taicpu(hp3).oper[OperIdx]^ do
  8869. begin
  8870. case typ of
  8871. top_ref:
  8872. begin
  8873. if (ref^.base <> NR_NO) and
  8874. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8875. (
  8876. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8877. (
  8878. { Allow the frame pointer if it's not being used by the procedure as such }
  8879. Assigned(current_procinfo) and
  8880. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8881. )
  8882. )
  8883. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8884. then
  8885. begin
  8886. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8887. if not Assigned(first_assignment) then
  8888. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8889. end;
  8890. if (ref^.index <> NR_NO) and
  8891. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8892. (
  8893. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8894. (
  8895. { Allow the frame pointer if it's not being used by the procedure as such }
  8896. Assigned(current_procinfo) and
  8897. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8898. )
  8899. )
  8900. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8901. (ref^.index <> ref^.base) then
  8902. begin
  8903. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8904. if not Assigned(first_assignment) then
  8905. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8906. end;
  8907. end;
  8908. top_reg:
  8909. begin
  8910. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8911. if not Assigned(first_assignment) then
  8912. IncludeRegInUsedRegs(reg, UsedRegs);
  8913. end;
  8914. else
  8915. ;
  8916. end;
  8917. end;
  8918. end;
  8919. end;
  8920. else
  8921. InternalError(2021040720);
  8922. end;
  8923. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8924. { Should have dropped out earlier }
  8925. InternalError(2021040710);
  8926. end;
  8927. end;
  8928. end;
  8929. const
  8930. WriteOp: array[0..3] of set of TInsChange = (
  8931. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8932. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8933. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8934. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8935. RegWriteFlags: array[0..7] of set of TInsChange = (
  8936. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8937. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8938. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8939. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8940. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8941. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8942. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8943. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8944. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8945. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8946. var
  8947. hp2: tai;
  8948. X: Integer;
  8949. begin
  8950. { If we have something like:
  8951. op ###,###
  8952. mov ###,###
  8953. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8954. interfere in regards to what they write to.
  8955. NOTE: p must be a 2-operand instruction
  8956. }
  8957. Result := False;
  8958. if (hp1.typ <> ait_instruction) or
  8959. taicpu(hp1).is_jmp or
  8960. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8961. Exit;
  8962. { NOP is a pipeline fence, likely marking the beginning of the function
  8963. epilogue, so drop out. Similarly, drop out if POP or RET are
  8964. encountered }
  8965. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8966. Exit;
  8967. if (taicpu(hp1).opcode = A_MOVSD) and
  8968. (taicpu(hp1).ops = 0) then
  8969. { Wrong MOVSD }
  8970. Exit;
  8971. { Check for writes to specific registers first }
  8972. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8973. for X := 0 to 7 do
  8974. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8975. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8976. Exit;
  8977. for X := 0 to taicpu(hp1).ops - 1 do
  8978. begin
  8979. { Check to see if this operand writes to something }
  8980. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8981. { And matches something in the CMP/TEST instruction }
  8982. (
  8983. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8984. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8985. (
  8986. { If it's a register, make sure the register written to doesn't
  8987. appear in the cmp instruction as part of a reference }
  8988. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8989. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8990. )
  8991. ) then
  8992. Exit;
  8993. end;
  8994. { Check p to make sure it doesn't write to something that affects hp1 }
  8995. { Check for writes to specific registers first }
  8996. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8997. for X := 0 to 7 do
  8998. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8999. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  9000. Exit;
  9001. for X := 0 to taicpu(p).ops - 1 do
  9002. begin
  9003. { Check to see if this operand writes to something }
  9004. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  9005. { And matches something in hp1 }
  9006. (taicpu(p).oper[X]^.typ = top_reg) and
  9007. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  9008. Exit;
  9009. end;
  9010. { The instruction can be safely moved }
  9011. asml.Remove(hp1);
  9012. { Try to insert after the last instructions where the FLAGS register is not
  9013. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  9014. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  9015. asml.InsertBefore(hp1, hp2)
  9016. { Failing that, try to insert after the last instructions where the
  9017. FLAGS register is not yet in use }
  9018. else if GetLastInstruction(p, hp2) and
  9019. (
  9020. (hp2.typ <> ait_instruction) or
  9021. { Don't insert after an instruction that uses the flags when p doesn't use them }
  9022. RegInInstruction(NR_DEFAULTFLAGS, p) or
  9023. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  9024. ) then
  9025. asml.InsertAfter(hp1, hp2)
  9026. else
  9027. { Note, if p.Previous is nil (even if it should logically never be the
  9028. case), FindRegAllocBackward immediately exits with False and so we
  9029. safely land here (we can't just pass p because FindRegAllocBackward
  9030. immediately exits on an instruction). [Kit] }
  9031. asml.InsertBefore(hp1, p);
  9032. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  9033. { We can't trust UsedRegs because we're looking backwards, although we
  9034. know the registers are allocated after p at the very least, so manually
  9035. create tai_regalloc objects if needed }
  9036. for X := 0 to taicpu(hp1).ops - 1 do
  9037. case taicpu(hp1).oper[X]^.typ of
  9038. top_reg:
  9039. begin
  9040. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  9041. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  9042. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  9043. end;
  9044. top_ref:
  9045. begin
  9046. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  9047. begin
  9048. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  9049. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  9050. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  9051. end;
  9052. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  9053. begin
  9054. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  9055. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  9056. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  9057. end;
  9058. end;
  9059. else
  9060. ;
  9061. end;
  9062. Result := True;
  9063. end;
  9064. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  9065. var
  9066. hp2: tai;
  9067. X: Integer;
  9068. begin
  9069. { If we have something like:
  9070. cmp ###,%reg1
  9071. mov 0,%reg2
  9072. And no modified registers are shared, move the instruction to before
  9073. the comparison as this means it can be optimised without worrying
  9074. about the FLAGS register. (CMP/MOV is generated by
  9075. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  9076. As long as the second instruction doesn't use the flags or one of the
  9077. registers used by CMP or TEST (also check any references that use the
  9078. registers), then it can be moved prior to the comparison.
  9079. }
  9080. Result := False;
  9081. if not TrySwapMovOp(p, hp1) then
  9082. Exit;
  9083. if taicpu(hp1).opcode = A_LEA then
  9084. { The flags will be overwritten by the CMP/TEST instruction }
  9085. ConvertLEA(taicpu(hp1));
  9086. Result := True;
  9087. { Can we move it one further back? }
  9088. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  9089. { Check to see if CMP/TEST is a comparison against zero }
  9090. (
  9091. (
  9092. (taicpu(p).opcode = A_CMP) and
  9093. MatchOperand(taicpu(p).oper[0]^, 0)
  9094. ) or
  9095. (
  9096. (taicpu(p).opcode = A_TEST) and
  9097. (
  9098. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9099. MatchOperand(taicpu(p).oper[0]^, -1)
  9100. )
  9101. )
  9102. ) and
  9103. { These instructions set the zero flag if the result is zero }
  9104. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9105. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9106. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9107. TrySwapMovOp(hp2, hp1);
  9108. end;
  9109. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9110. var
  9111. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9112. JumpLabel: TAsmLabel;
  9113. TmpBool: Boolean;
  9114. begin
  9115. Result := False;
  9116. { Look for:
  9117. stc/clc
  9118. j(c) .L1
  9119. ...
  9120. .L1:
  9121. set(n)cb %reg
  9122. (flags deallocated)
  9123. j(c) .L2
  9124. Change to:
  9125. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9126. j(c) .L2
  9127. }
  9128. p_last := p;
  9129. while GetNextInstruction(p_last, hp1) and
  9130. (hp1.typ = ait_instruction) and
  9131. IsJumpToLabel(taicpu(hp1)) do
  9132. begin
  9133. if DoJumpOptimizations(hp1, TmpBool) then
  9134. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9135. Continue;
  9136. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9137. if not Assigned(JumpLabel) then
  9138. InternalError(2024012801);
  9139. { Optimise the J(c); stc/clc optimisation first since this will
  9140. get missed if the main optimisation takes place }
  9141. if (taicpu(hp1).opcode = A_JCC) then
  9142. begin
  9143. if GetNextInstruction(hp1, hp2) and
  9144. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9145. TryJccStcClcOpt(hp1, hp2) then
  9146. begin
  9147. Result := True;
  9148. Exit;
  9149. end;
  9150. hp2 := nil; { Suppress compiler warning }
  9151. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9152. { Make sure the flags aren't used again }
  9153. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9154. begin
  9155. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9156. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9157. begin
  9158. if (taicpu(p).opcode = A_STC) then
  9159. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9160. else
  9161. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9162. MakeUnconditional(taicpu(hp1));
  9163. { Move the jump to after the flag deallocations }
  9164. Asml.Remove(hp1);
  9165. Asml.InsertAfter(hp1, hp2);
  9166. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9167. Result := True;
  9168. Exit;
  9169. end
  9170. else
  9171. begin
  9172. if (taicpu(p).opcode = A_STC) then
  9173. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9174. else
  9175. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9176. { In this case, the jump is deterministic in that it will never be taken }
  9177. JumpLabel.DecRefs;
  9178. RemoveInstruction(hp1);
  9179. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9180. Result := True;
  9181. Exit;
  9182. end;
  9183. end;
  9184. end;
  9185. hp2 := nil; { Suppress compiler warning }
  9186. if
  9187. { Make sure the carry flag doesn't appear in the jump conditions }
  9188. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9189. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9190. GetNextInstruction(hp2, p_dist) and
  9191. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9192. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9193. begin
  9194. case taicpu(p_dist).opcode of
  9195. A_Jcc:
  9196. begin
  9197. if DoJumpOptimizations(p_dist, TmpBool) then
  9198. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9199. Continue;
  9200. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9201. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9202. begin
  9203. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9204. JumpLabel.decrefs;
  9205. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9206. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9207. Result := True;
  9208. Exit;
  9209. end
  9210. else if GetNextInstruction(p_dist, hp1_dist) and
  9211. (hp1_dist.typ = ait_label) then
  9212. begin
  9213. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9214. JumpLabel.decrefs;
  9215. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9216. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9217. Result := True;
  9218. Exit;
  9219. end;
  9220. end;
  9221. A_SETcc:
  9222. if { Make sure the flags aren't used again }
  9223. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9224. GetNextInstruction(hp2, hp1_dist) and
  9225. (hp1_dist.typ = ait_instruction) and
  9226. IsJumpToLabel(taicpu(hp1_dist)) and
  9227. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9228. { This works if hp1_dist or both are regular JMP instructions }
  9229. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9230. (
  9231. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9232. { Make sure the register isn't still in use, otherwise it
  9233. may get corrupted (fixes #40659) }
  9234. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9235. ) then
  9236. begin
  9237. taicpu(p).allocate_oper(2);
  9238. taicpu(p).ops := 2;
  9239. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9240. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9241. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9242. taicpu(p).opcode := A_MOV;
  9243. taicpu(p).opsize := S_B;
  9244. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9245. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9246. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9247. JumpLabel.decrefs;
  9248. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9249. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9250. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9251. (tai_regalloc(hp2).ratype = ra_alloc) then
  9252. begin
  9253. Asml.Remove(hp2);
  9254. Asml.InsertAfter(hp2, p);
  9255. end;
  9256. Result := True;
  9257. Exit;
  9258. end;
  9259. else
  9260. ;
  9261. end;
  9262. end;
  9263. p_last := hp1;
  9264. end;
  9265. end;
  9266. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9267. var
  9268. hp2, hp3: tai;
  9269. TempBool: Boolean;
  9270. begin
  9271. Result := False;
  9272. {
  9273. j(c) .L1
  9274. stc/clc
  9275. .L1:
  9276. jc/jnc .L2
  9277. (Flags deallocated)
  9278. Change to:
  9279. j)c) .L1
  9280. jmp .L2
  9281. .L1:
  9282. jc/jnc .L2
  9283. Then call DoJumpOptimizations to convert to:
  9284. j(nc) .L2
  9285. .L1: (may become a dead label)
  9286. jc/jnc .L2
  9287. }
  9288. if GetNextInstruction(hp1, hp2) and
  9289. (hp2.typ = ait_label) and
  9290. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9291. GetNextInstruction(hp2, hp3) and
  9292. MatchInstruction(hp3, A_Jcc, []) and
  9293. (
  9294. (
  9295. (taicpu(hp3).condition = C_C) and
  9296. (taicpu(hp1).opcode = A_STC)
  9297. ) or (
  9298. (taicpu(hp3).condition = C_NC) and
  9299. (taicpu(hp1).opcode = A_CLC)
  9300. )
  9301. ) and
  9302. { Make sure the flags aren't used again }
  9303. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9304. begin
  9305. taicpu(hp1).allocate_oper(1);
  9306. taicpu(hp1).ops := 1;
  9307. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9308. taicpu(hp1).opcode := A_JMP;
  9309. taicpu(hp1).is_jmp := True;
  9310. TempBool := True; { Prevent compiler warnings }
  9311. if DoJumpOptimizations(p, TempBool) then
  9312. Result := True
  9313. else
  9314. Include(OptsToCheck, aoc_ForceNewIteration);
  9315. end;
  9316. end;
  9317. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9318. begin
  9319. { This generally only executes under -O3 and above }
  9320. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9321. end;
  9322. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9323. var
  9324. hp1, hp2: tai;
  9325. FoundComparison: Boolean;
  9326. begin
  9327. { Run the pass 1 optimisations as well, since they may have some effect
  9328. after the CMOV blocks are created in OptPass2Jcc }
  9329. Result := False;
  9330. { Result := OptPass1CMOVcc(p);
  9331. if Result then
  9332. Exit;}
  9333. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9334. and make a slightly inefficent result on branching-type blocks, notably
  9335. when setting a function result then jumping to the function epilogue.
  9336. In this case, change:
  9337. cmov(c) %reg1,%reg2
  9338. j(c) @lbl
  9339. (%reg2 deallocated)
  9340. To:
  9341. mov %reg11,%reg2
  9342. j(c) @lbl
  9343. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9344. jump because if it's not present, we may end up with a jump that's
  9345. completely unrelated.
  9346. }
  9347. hp1 := p;
  9348. while GetNextInstruction(hp1, hp1) and
  9349. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9350. if (hp1.typ = ait_instruction) and
  9351. (taicpu(hp1).opcode = A_Jcc) and
  9352. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9353. begin
  9354. TransferUsedRegs(TmpUsedRegs);
  9355. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9356. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9357. (
  9358. { See if we can find a more distant instruction that overwrites
  9359. the destination register }
  9360. (cs_opt_level3 in current_settings.optimizerswitches) and
  9361. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9362. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9363. ) then
  9364. begin
  9365. if (taicpu(p).oper[0]^.typ = top_reg) then
  9366. begin
  9367. { Search backwards to see if the source register is set to a
  9368. constant }
  9369. FoundComparison := False;
  9370. hp1 := p;
  9371. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9372. begin
  9373. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9374. begin
  9375. FoundComparison := True;
  9376. Continue;
  9377. end;
  9378. { Once we find the CMP, TEST or similar instruction, we
  9379. have to stop if we find anything other than a MOV }
  9380. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9381. Break;
  9382. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9383. { Destination register was modified }
  9384. Break;
  9385. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9386. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9387. begin
  9388. { Found a constant! }
  9389. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9390. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9391. { The source register is no longer in use }
  9392. RemoveInstruction(hp1);
  9393. Break;
  9394. end;
  9395. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9396. { Some other instruction has modified the source register }
  9397. Break;
  9398. end;
  9399. end;
  9400. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9401. taicpu(p).opcode := A_MOV;
  9402. taicpu(p).condition := C_None;
  9403. { Rely on the post peephole stage to put the MOV before the
  9404. CMP/TEST instruction that appears prior }
  9405. Result := True;
  9406. Exit;
  9407. end;
  9408. end;
  9409. end;
  9410. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9411. function IsXCHGAcceptable: Boolean; inline;
  9412. begin
  9413. { Always accept if optimising for size }
  9414. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9415. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9416. than 3, so it becomes a saving compared to three MOVs with two of
  9417. them able to execute simultaneously. [Kit] }
  9418. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9419. end;
  9420. var
  9421. NewRef: TReference;
  9422. hp1, hp2, hp3, hp4: Tai;
  9423. {$ifndef x86_64}
  9424. OperIdx: Integer;
  9425. {$endif x86_64}
  9426. NewInstr : Taicpu;
  9427. NewAligh : Tai_align;
  9428. DestLabel: TAsmLabel;
  9429. TempTracking: TAllUsedRegs;
  9430. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9431. var
  9432. NextInstr: tai;
  9433. begin
  9434. Result := False;
  9435. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9436. if not GetNextInstruction(InputInstr, NextInstr) or
  9437. (
  9438. { The FLAGS register isn't always tracked properly, so do not
  9439. perform this optimisation if a conditional statement follows }
  9440. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9441. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9442. ) then
  9443. begin
  9444. reference_reset(NewRef, 1, []);
  9445. NewRef.base := taicpu(p).oper[0]^.reg;
  9446. NewRef.scalefactor := 1;
  9447. if taicpu(InputInstr).opcode = A_ADD then
  9448. begin
  9449. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9450. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9451. end
  9452. else
  9453. begin
  9454. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9455. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9456. end;
  9457. taicpu(p).opcode := A_LEA;
  9458. taicpu(p).loadref(0, NewRef);
  9459. { For the sake of debugging, have the line info match the
  9460. arithmetic instruction rather than the MOV instruction }
  9461. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9462. RemoveInstruction(InputInstr);
  9463. Result := True;
  9464. end;
  9465. end;
  9466. begin
  9467. Result:=false;
  9468. { This optimisation adds an instruction, so only do it for speed }
  9469. if not (cs_opt_size in current_settings.optimizerswitches) and
  9470. MatchOpType(taicpu(p), top_const, top_reg) and
  9471. (taicpu(p).oper[0]^.val = 0) then
  9472. begin
  9473. { To avoid compiler warning }
  9474. DestLabel := nil;
  9475. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9476. InternalError(2021040750);
  9477. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9478. Exit;
  9479. case hp1.typ of
  9480. ait_label:
  9481. begin
  9482. { Change:
  9483. mov $0,%reg mov $0,%reg
  9484. @Lbl1: @Lbl1:
  9485. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9486. je @Lbl2 jne @Lbl2
  9487. To: To:
  9488. mov $0,%reg mov $0,%reg
  9489. jmp @Lbl2 jmp @Lbl3
  9490. (align) (align)
  9491. @Lbl1: @Lbl1:
  9492. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9493. je @Lbl2 je @Lbl2
  9494. @Lbl3: <-- Only if label exists
  9495. (Not if it's optimised for size)
  9496. }
  9497. if not GetNextInstruction(hp1, hp2) then
  9498. Exit;
  9499. if (hp2.typ = ait_instruction) and
  9500. (
  9501. { Register sizes must exactly match }
  9502. (
  9503. (taicpu(hp2).opcode = A_CMP) and
  9504. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9505. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9506. ) or (
  9507. (taicpu(hp2).opcode = A_TEST) and
  9508. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9509. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9510. )
  9511. ) and GetNextInstruction(hp2, hp3) and
  9512. (hp3.typ = ait_instruction) and
  9513. (taicpu(hp3).opcode = A_JCC) and
  9514. (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
  9515. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9516. begin
  9517. { Check condition of jump }
  9518. { Always true? }
  9519. if condition_in(C_E, taicpu(hp3).condition) then
  9520. begin
  9521. { Copy label symbol and obtain matching label entry for the
  9522. conditional jump, as this will be our destination}
  9523. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9524. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9525. Result := True;
  9526. end
  9527. { Always false? }
  9528. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9529. begin
  9530. { This is only worth it if there's a jump to take }
  9531. case hp2.typ of
  9532. ait_instruction:
  9533. begin
  9534. if taicpu(hp2).opcode = A_JMP then
  9535. begin
  9536. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9537. { An unconditional jump follows the conditional jump which will always be false,
  9538. so use this jump's destination for the new jump }
  9539. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9540. Result := True;
  9541. end
  9542. else if taicpu(hp2).opcode = A_JCC then
  9543. begin
  9544. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9545. if condition_in(C_E, taicpu(hp2).condition) then
  9546. begin
  9547. { A second conditional jump follows the conditional jump which will always be false,
  9548. while the second jump is always True, so use this jump's destination for the new jump }
  9549. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9550. Result := True;
  9551. end;
  9552. { Don't risk it if the jump isn't always true (Result remains False) }
  9553. end;
  9554. end;
  9555. else
  9556. { If anything else don't optimise };
  9557. end;
  9558. end;
  9559. if Result then
  9560. begin
  9561. { Just so we have something to insert as a paremeter}
  9562. reference_reset(NewRef, 1, []);
  9563. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9564. { Now actually load the correct parameter (this also
  9565. increases the reference count) }
  9566. NewInstr.loadsymbol(0, DestLabel, 0);
  9567. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9568. begin
  9569. { Get instruction before original label (may not be p under -O3) }
  9570. if not GetLastInstruction(hp1, hp2) then
  9571. { Shouldn't fail here }
  9572. InternalError(2021040701);
  9573. end
  9574. else
  9575. hp2 := p;
  9576. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9577. AsmL.InsertAfter(NewInstr, hp2);
  9578. { Add new alignment field }
  9579. (* AsmL.InsertAfter(
  9580. cai_align.create_max(
  9581. current_settings.alignment.jumpalign,
  9582. current_settings.alignment.jumpalignskipmax
  9583. ),
  9584. NewInstr
  9585. ); *)
  9586. end;
  9587. Exit;
  9588. end;
  9589. end;
  9590. else
  9591. ;
  9592. end;
  9593. end;
  9594. if not GetNextInstruction(p, hp1) then
  9595. Exit;
  9596. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9597. begin
  9598. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9599. begin
  9600. Result := True;
  9601. Exit;
  9602. end;
  9603. { This optimisation is only effective on a second run of Pass 2,
  9604. hence -O3 or above.
  9605. Change:
  9606. mov %reg1,%reg2
  9607. cmp/test (contains %reg1)
  9608. mov x, %reg1
  9609. (another mov or a j(c))
  9610. To:
  9611. mov %reg1,%reg2
  9612. mov x, %reg1
  9613. cmp (%reg1 replaced with %reg2)
  9614. (another mov or a j(c))
  9615. The requirement of an additional MOV or a jump ensures there
  9616. isn't performance loss, since a j(c) will permit macro-fusion
  9617. with the cmp instruction, while another MOV likely means it's
  9618. not all being executed in a single cycle due to parallelisation.
  9619. }
  9620. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9621. MatchOpType(taicpu(p), top_reg, top_reg) and
  9622. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9623. GetNextInstruction(hp1, hp2) and
  9624. MatchInstruction(hp2, A_MOV, []) and
  9625. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9626. { Registers don't have to be the same size in this case }
  9627. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9628. GetNextInstruction(hp2, hp3) and
  9629. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9630. { Make sure the operands in the camparison can be safely replaced }
  9631. (
  9632. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9633. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9634. ) and
  9635. (
  9636. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9637. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9638. ) then
  9639. begin
  9640. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9641. AsmL.Remove(hp2);
  9642. AsmL.InsertAfter(hp2, p);
  9643. Result := True;
  9644. Exit;
  9645. end;
  9646. end;
  9647. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9648. begin
  9649. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9650. further, but we can't just put this jump optimisation in pass 1
  9651. because it tends to perform worse when conditional jumps are
  9652. nearby (e.g. when converting CMOV instructions). [Kit] }
  9653. CopyUsedRegs(TempTracking);
  9654. UpdateUsedRegs(tai(p.Next));
  9655. if OptPass2JMP(hp1) then
  9656. begin
  9657. { Restore register state }
  9658. RestoreUsedRegs(TempTracking);
  9659. ReleaseUsedRegs(TempTracking);
  9660. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9661. OptPass1MOV(p);
  9662. Result := True;
  9663. Exit;
  9664. end;
  9665. { If OptPass2JMP returned False, no optimisations were done to
  9666. the jump and there are no further optimisations that can be done
  9667. to the MOV instruction on this pass other than FuncMov2Func }
  9668. { Restore register state }
  9669. RestoreUsedRegs(TempTracking);
  9670. ReleaseUsedRegs(TempTracking);
  9671. Result := FuncMov2Func(p, hp1);
  9672. Exit;
  9673. end;
  9674. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9675. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9676. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9677. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9678. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9679. begin
  9680. { Change:
  9681. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9682. addl/q $x,%reg2 subl/q $x,%reg2
  9683. To:
  9684. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9685. }
  9686. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9687. { be lazy, checking separately for sub would be slightly better }
  9688. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9689. begin
  9690. TransferUsedRegs(TmpUsedRegs);
  9691. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9692. if TryMovArith2Lea(hp1) then
  9693. begin
  9694. Result := True;
  9695. Exit;
  9696. end
  9697. end
  9698. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9699. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9700. { Same as above, but also adds or subtracts to %reg2 in between.
  9701. It's still valid as long as the flags aren't in use }
  9702. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9703. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9704. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9705. { be lazy, checking separately for sub would be slightly better }
  9706. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9707. begin
  9708. TransferUsedRegs(TmpUsedRegs);
  9709. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9710. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9711. if TryMovArith2Lea(hp2) then
  9712. begin
  9713. Result := True;
  9714. Exit;
  9715. end;
  9716. end;
  9717. end;
  9718. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9719. {$ifdef x86_64}
  9720. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9721. {$else x86_64}
  9722. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9723. {$endif x86_64}
  9724. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9725. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9726. { mov reg1, reg2 mov reg1, reg2
  9727. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9728. begin
  9729. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9730. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9731. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9732. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9733. TransferUsedRegs(TmpUsedRegs);
  9734. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9735. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9736. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9737. then
  9738. begin
  9739. RemoveCurrentP(p, hp1);
  9740. Result:=true;
  9741. end;
  9742. Exit;
  9743. end;
  9744. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9745. IsXCHGAcceptable and
  9746. { XCHG doesn't support 8-bit registers }
  9747. (taicpu(p).opsize <> S_B) and
  9748. MatchInstruction(hp1, A_MOV, []) and
  9749. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9750. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9751. GetNextInstruction(hp1, hp2) and
  9752. MatchInstruction(hp2, A_MOV, []) and
  9753. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9754. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9755. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9756. begin
  9757. { mov %reg1,%reg2
  9758. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9759. mov %reg2,%reg3
  9760. (%reg2 not used afterwards)
  9761. Note that xchg takes 3 cycles to execute, and generally mov's take
  9762. only one cycle apiece, but the first two mov's can be executed in
  9763. parallel, only taking 2 cycles overall. Older processors should
  9764. therefore only optimise for size. [Kit]
  9765. }
  9766. TransferUsedRegs(TmpUsedRegs);
  9767. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9768. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9769. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9770. begin
  9771. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9772. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9773. taicpu(hp1).opcode := A_XCHG;
  9774. RemoveCurrentP(p, hp1);
  9775. RemoveInstruction(hp2);
  9776. Result := True;
  9777. Exit;
  9778. end;
  9779. end;
  9780. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9781. MatchInstruction(hp1, A_SAR, []) then
  9782. begin
  9783. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9784. begin
  9785. { the use of %edx also covers the opsize being S_L }
  9786. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9787. begin
  9788. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9789. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9790. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9791. begin
  9792. { Change:
  9793. movl %eax,%edx
  9794. sarl $31,%edx
  9795. To:
  9796. cltd
  9797. }
  9798. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9799. RemoveInstruction(hp1);
  9800. taicpu(p).opcode := A_CDQ;
  9801. taicpu(p).opsize := S_NO;
  9802. taicpu(p).clearop(1);
  9803. taicpu(p).clearop(0);
  9804. taicpu(p).ops:=0;
  9805. Result := True;
  9806. Exit;
  9807. end
  9808. else if (cs_opt_size in current_settings.optimizerswitches) and
  9809. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9810. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9811. begin
  9812. { Change:
  9813. movl %edx,%eax
  9814. sarl $31,%edx
  9815. To:
  9816. movl %edx,%eax
  9817. cltd
  9818. Note that this creates a dependency between the two instructions,
  9819. so only perform if optimising for size.
  9820. }
  9821. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9822. taicpu(hp1).opcode := A_CDQ;
  9823. taicpu(hp1).opsize := S_NO;
  9824. taicpu(hp1).clearop(1);
  9825. taicpu(hp1).clearop(0);
  9826. taicpu(hp1).ops:=0;
  9827. Include(OptsToCheck, aoc_ForceNewIteration);
  9828. Exit;
  9829. end;
  9830. {$ifndef x86_64}
  9831. end
  9832. { Don't bother if CMOV is supported, because a more optimal
  9833. sequence would have been generated for the Abs() intrinsic }
  9834. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9835. { the use of %eax also covers the opsize being S_L }
  9836. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9837. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9838. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9839. GetNextInstruction(hp1, hp2) and
  9840. MatchInstruction(hp2, A_XOR, [S_L]) and
  9841. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9842. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9843. GetNextInstruction(hp2, hp3) and
  9844. MatchInstruction(hp3, A_SUB, [S_L]) and
  9845. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9846. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9847. begin
  9848. { Change:
  9849. movl %eax,%edx
  9850. sarl $31,%eax
  9851. xorl %eax,%edx
  9852. subl %eax,%edx
  9853. (Instruction that uses %edx)
  9854. (%eax deallocated)
  9855. (%edx deallocated)
  9856. To:
  9857. cltd
  9858. xorl %edx,%eax <-- Note the registers have swapped
  9859. subl %edx,%eax
  9860. (Instruction that uses %eax) <-- %eax rather than %edx
  9861. }
  9862. TransferUsedRegs(TmpUsedRegs);
  9863. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9864. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9865. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9866. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9867. begin
  9868. if GetNextInstruction(hp3, hp4) and
  9869. not RegModifiedByInstruction(NR_EDX, hp4) and
  9870. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9871. begin
  9872. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9873. taicpu(p).opcode := A_CDQ;
  9874. taicpu(p).clearop(1);
  9875. taicpu(p).clearop(0);
  9876. taicpu(p).ops:=0;
  9877. RemoveInstruction(hp1);
  9878. taicpu(hp2).loadreg(0, NR_EDX);
  9879. taicpu(hp2).loadreg(1, NR_EAX);
  9880. taicpu(hp3).loadreg(0, NR_EDX);
  9881. taicpu(hp3).loadreg(1, NR_EAX);
  9882. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9883. { Convert references in the following instruction (hp4) from %edx to %eax }
  9884. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9885. with taicpu(hp4).oper[OperIdx]^ do
  9886. case typ of
  9887. top_reg:
  9888. if getsupreg(reg) = RS_EDX then
  9889. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9890. top_ref:
  9891. begin
  9892. if getsupreg(reg) = RS_EDX then
  9893. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9894. if getsupreg(reg) = RS_EDX then
  9895. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9896. end;
  9897. else
  9898. ;
  9899. end;
  9900. Result := True;
  9901. Exit;
  9902. end;
  9903. end;
  9904. {$else x86_64}
  9905. end;
  9906. end
  9907. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9908. { the use of %rdx also covers the opsize being S_Q }
  9909. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9910. begin
  9911. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9912. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9913. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9914. begin
  9915. { Change:
  9916. movq %rax,%rdx
  9917. sarq $63,%rdx
  9918. To:
  9919. cqto
  9920. }
  9921. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9922. RemoveInstruction(hp1);
  9923. taicpu(p).opcode := A_CQO;
  9924. taicpu(p).opsize := S_NO;
  9925. taicpu(p).clearop(1);
  9926. taicpu(p).clearop(0);
  9927. taicpu(p).ops:=0;
  9928. Result := True;
  9929. Exit;
  9930. end
  9931. else if (cs_opt_size in current_settings.optimizerswitches) and
  9932. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9933. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9934. begin
  9935. { Change:
  9936. movq %rdx,%rax
  9937. sarq $63,%rdx
  9938. To:
  9939. movq %rdx,%rax
  9940. cqto
  9941. Note that this creates a dependency between the two instructions,
  9942. so only perform if optimising for size.
  9943. }
  9944. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9945. taicpu(hp1).opcode := A_CQO;
  9946. taicpu(hp1).opsize := S_NO;
  9947. taicpu(hp1).clearop(1);
  9948. taicpu(hp1).clearop(0);
  9949. taicpu(hp1).ops:=0;
  9950. Include(OptsToCheck, aoc_ForceNewIteration);
  9951. Exit;
  9952. {$endif x86_64}
  9953. end;
  9954. end;
  9955. end;
  9956. if MatchInstruction(hp1, A_MOV, []) and
  9957. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9958. { Though "GetNextInstruction" could be factored out, along with
  9959. the instructions that depend on hp2, it is an expensive call that
  9960. should be delayed for as long as possible, hence we do cheaper
  9961. checks first that are likely to be False. [Kit] }
  9962. begin
  9963. if (
  9964. (
  9965. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9966. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9967. (
  9968. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9969. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9970. )
  9971. ) or
  9972. (
  9973. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9974. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9975. (
  9976. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9977. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9978. )
  9979. )
  9980. ) and
  9981. GetNextInstruction(hp1, hp2) and
  9982. MatchInstruction(hp2, A_SAR, []) and
  9983. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9984. begin
  9985. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9986. begin
  9987. { Change:
  9988. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9989. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9990. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9991. To:
  9992. movl r/m,%eax <- Note the change in register
  9993. cltd
  9994. }
  9995. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9996. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9997. taicpu(p).loadreg(1, NR_EAX);
  9998. taicpu(hp1).opcode := A_CDQ;
  9999. taicpu(hp1).clearop(1);
  10000. taicpu(hp1).clearop(0);
  10001. taicpu(hp1).ops:=0;
  10002. RemoveInstruction(hp2);
  10003. Include(OptsToCheck, aoc_ForceNewIteration);
  10004. (*
  10005. {$ifdef x86_64}
  10006. end
  10007. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  10008. { This code sequence does not get generated - however it might become useful
  10009. if and when 128-bit signed integer types make an appearance, so the code
  10010. is kept here for when it is eventually needed. [Kit] }
  10011. (
  10012. (
  10013. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  10014. (
  10015. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10016. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  10017. )
  10018. ) or
  10019. (
  10020. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  10021. (
  10022. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10023. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  10024. )
  10025. )
  10026. ) and
  10027. GetNextInstruction(hp1, hp2) and
  10028. MatchInstruction(hp2, A_SAR, [S_Q]) and
  10029. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  10030. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  10031. begin
  10032. { Change:
  10033. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  10034. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  10035. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  10036. To:
  10037. movq r/m,%rax <- Note the change in register
  10038. cqto
  10039. }
  10040. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  10041. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  10042. taicpu(p).loadreg(1, NR_RAX);
  10043. taicpu(hp1).opcode := A_CQO;
  10044. taicpu(hp1).clearop(1);
  10045. taicpu(hp1).clearop(0);
  10046. taicpu(hp1).ops:=0;
  10047. RemoveInstruction(hp2);
  10048. Include(OptsToCheck, aoc_ForceNewIteration);
  10049. {$endif x86_64}
  10050. *)
  10051. end;
  10052. end;
  10053. {$ifdef x86_64}
  10054. end;
  10055. if (taicpu(p).opsize = S_L) and
  10056. (taicpu(p).oper[1]^.typ = top_reg) and
  10057. (
  10058. MatchInstruction(hp1, A_MOV,[]) and
  10059. (taicpu(hp1).opsize = S_L) and
  10060. (taicpu(hp1).oper[1]^.typ = top_reg)
  10061. ) and (
  10062. GetNextInstruction(hp1, hp2) and
  10063. (tai(hp2).typ=ait_instruction) and
  10064. (taicpu(hp2).opsize = S_Q) and
  10065. (
  10066. (
  10067. MatchInstruction(hp2, A_ADD,[]) and
  10068. (taicpu(hp2).opsize = S_Q) and
  10069. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10070. (
  10071. (
  10072. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10073. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10074. ) or (
  10075. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10076. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10077. )
  10078. )
  10079. ) or (
  10080. MatchInstruction(hp2, A_LEA,[]) and
  10081. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  10082. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  10083. (
  10084. (
  10085. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10086. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10087. ) or (
  10088. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10089. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  10090. )
  10091. ) and (
  10092. (
  10093. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10094. ) or (
  10095. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10096. )
  10097. )
  10098. )
  10099. )
  10100. ) and (
  10101. GetNextInstruction(hp2, hp3) and
  10102. MatchInstruction(hp3, A_SHR,[]) and
  10103. (taicpu(hp3).opsize = S_Q) and
  10104. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10105. (taicpu(hp3).oper[0]^.val = 1) and
  10106. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10107. ) then
  10108. begin
  10109. { Change movl x, reg1d movl x, reg1d
  10110. movl y, reg2d movl y, reg2d
  10111. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10112. shrq $1, reg1q shrq $1, reg1q
  10113. ( reg1d and reg2d can be switched around in the first two instructions )
  10114. To movl x, reg1d
  10115. addl y, reg1d
  10116. rcrl $1, reg1d
  10117. This corresponds to the common expression (x + y) shr 1, where
  10118. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10119. smaller code, but won't account for x + y causing an overflow). [Kit]
  10120. }
  10121. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10122. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10123. begin
  10124. { Change first MOV command to have the same register as the final output }
  10125. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10126. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10127. Result := True;
  10128. end
  10129. else
  10130. begin
  10131. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10132. Include(OptsToCheck, aoc_ForceNewIteration);
  10133. end;
  10134. { Change second MOV command to an ADD command. This is easier than
  10135. converting the existing command because it means we don't have to
  10136. touch 'y', which might be a complicated reference, and also the
  10137. fact that the third command might either be ADD or LEA. [Kit] }
  10138. taicpu(hp1).opcode := A_ADD;
  10139. { Delete old ADD/LEA instruction }
  10140. RemoveInstruction(hp2);
  10141. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10142. taicpu(hp3).opcode := A_RCR;
  10143. taicpu(hp3).changeopsize(S_L);
  10144. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10145. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10146. called, so FuncMov2Func below is safe to call }
  10147. {$endif x86_64}
  10148. end;
  10149. if FuncMov2Func(p, hp1) then
  10150. begin
  10151. Result := True;
  10152. Exit;
  10153. end;
  10154. end;
  10155. {$push}
  10156. {$q-}{$r-}
  10157. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10158. var
  10159. ThisReg: TRegister;
  10160. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10161. TargetSubReg: TSubRegister;
  10162. hp1, hp2: tai;
  10163. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10164. { Store list of found instructions so we don't have to call
  10165. GetNextInstructionUsingReg multiple times }
  10166. InstrList: array of taicpu;
  10167. InstrMax, Index: Integer;
  10168. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10169. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10170. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10171. WorkingValue: TCgInt;
  10172. PreMessage: string;
  10173. { Data flow analysis }
  10174. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10175. BitwiseOnly, OrXorUsed,
  10176. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10177. function CheckOverflowConditions: Boolean;
  10178. begin
  10179. Result := True;
  10180. if (TestValSignedMax > SignedUpperLimit) then
  10181. UpperSignedOverflow := True;
  10182. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10183. LowerSignedOverflow := True;
  10184. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10185. LowerUnsignedOverflow := True;
  10186. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10187. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10188. begin
  10189. { Absolute overflow }
  10190. Result := False;
  10191. Exit;
  10192. end;
  10193. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10194. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10195. ShiftDownOverflow := True;
  10196. if (TestValMin < 0) or (TestValMax < 0) then
  10197. begin
  10198. LowerUnsignedOverflow := True;
  10199. UpperUnsignedOverflow := True;
  10200. end;
  10201. end;
  10202. function AdjustInitialLoadAndSize: Boolean;
  10203. begin
  10204. Result := False;
  10205. if not p_removed then
  10206. begin
  10207. if TargetSize = MinSize then
  10208. begin
  10209. { Convert the input MOVZX to a MOV }
  10210. if (taicpu(p).oper[0]^.typ = top_reg) and
  10211. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10212. begin
  10213. { Or remove it completely! }
  10214. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10215. RemoveCurrentP(p);
  10216. p_removed := True;
  10217. end
  10218. else
  10219. begin
  10220. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10221. taicpu(p).opcode := A_MOV;
  10222. taicpu(p).oper[1]^.reg := ThisReg;
  10223. taicpu(p).opsize := TargetSize;
  10224. end;
  10225. Result := True;
  10226. end
  10227. else if TargetSize <> MaxSize then
  10228. begin
  10229. case MaxSize of
  10230. S_L:
  10231. if TargetSize = S_W then
  10232. begin
  10233. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10234. taicpu(p).opsize := S_BW;
  10235. taicpu(p).oper[1]^.reg := ThisReg;
  10236. Result := True;
  10237. end
  10238. else
  10239. InternalError(2020112341);
  10240. S_W:
  10241. if TargetSize = S_L then
  10242. begin
  10243. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10244. taicpu(p).opsize := S_BL;
  10245. taicpu(p).oper[1]^.reg := ThisReg;
  10246. Result := True;
  10247. end
  10248. else
  10249. InternalError(2020112342);
  10250. else
  10251. ;
  10252. end;
  10253. end
  10254. else if not hp1_removed and not RegInUse then
  10255. begin
  10256. { If we have something like:
  10257. movzbl (oper),%regd
  10258. add x, %regd
  10259. movzbl %regb, %regd
  10260. We can reduce the register size to the input of the final
  10261. movzbl instruction. Overflows won't have any effect.
  10262. }
  10263. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10264. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10265. begin
  10266. TargetSize := S_B;
  10267. setsubreg(ThisReg, R_SUBL);
  10268. Result := True;
  10269. end
  10270. else if (taicpu(p).opsize = S_WL) and
  10271. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10272. begin
  10273. TargetSize := S_W;
  10274. setsubreg(ThisReg, R_SUBW);
  10275. Result := True;
  10276. end;
  10277. if Result then
  10278. begin
  10279. { Convert the input MOVZX to a MOV }
  10280. if (taicpu(p).oper[0]^.typ = top_reg) and
  10281. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10282. begin
  10283. { Or remove it completely! }
  10284. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10285. RemoveCurrentP(p);
  10286. p_removed := True;
  10287. end
  10288. else
  10289. begin
  10290. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10291. taicpu(p).opcode := A_MOV;
  10292. taicpu(p).oper[1]^.reg := ThisReg;
  10293. taicpu(p).opsize := TargetSize;
  10294. end;
  10295. end;
  10296. end;
  10297. end;
  10298. end;
  10299. procedure AdjustFinalLoad;
  10300. begin
  10301. if not LowerUnsignedOverflow then
  10302. begin
  10303. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10304. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10305. begin
  10306. { Convert the output MOVZX to a MOV }
  10307. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10308. begin
  10309. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10310. if (MinSize = S_B) or
  10311. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10312. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10313. begin
  10314. { Remove it completely! }
  10315. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10316. { Be careful; if p = hp1 and p was also removed, p
  10317. will become a dangling pointer }
  10318. if p = hp1 then
  10319. begin
  10320. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10321. p_removed := True;
  10322. end
  10323. else
  10324. RemoveInstruction(hp1);
  10325. hp1_removed := True;
  10326. end;
  10327. end
  10328. else
  10329. begin
  10330. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10331. taicpu(hp1).opcode := A_MOV;
  10332. taicpu(hp1).oper[0]^.reg := ThisReg;
  10333. taicpu(hp1).opsize := TargetSize;
  10334. end;
  10335. end
  10336. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10337. begin
  10338. { Need to change the size of the output }
  10339. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10340. taicpu(hp1).oper[0]^.reg := ThisReg;
  10341. taicpu(hp1).opsize := S_BL;
  10342. end;
  10343. end;
  10344. end;
  10345. function CompressInstructions: Boolean;
  10346. var
  10347. LocalIndex: Integer;
  10348. begin
  10349. Result := False;
  10350. { The objective here is to try to find a combination that
  10351. removes one of the MOV/Z instructions. }
  10352. if (
  10353. (taicpu(p).oper[0]^.typ <> top_reg) or
  10354. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10355. ) and
  10356. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10357. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10358. begin
  10359. { Make a preference to remove the second MOVZX instruction }
  10360. case taicpu(hp1).opsize of
  10361. S_BL, S_WL:
  10362. begin
  10363. TargetSize := S_L;
  10364. TargetSubReg := R_SUBD;
  10365. end;
  10366. S_BW:
  10367. begin
  10368. TargetSize := S_W;
  10369. TargetSubReg := R_SUBW;
  10370. end;
  10371. else
  10372. InternalError(2020112302);
  10373. end;
  10374. end
  10375. else
  10376. begin
  10377. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10378. begin
  10379. { Exceeded lower bound but not upper bound }
  10380. TargetSize := MaxSize;
  10381. end
  10382. else if not LowerUnsignedOverflow then
  10383. begin
  10384. { Size didn't exceed lower bound }
  10385. TargetSize := MinSize;
  10386. end
  10387. else
  10388. Exit;
  10389. end;
  10390. case TargetSize of
  10391. S_B:
  10392. TargetSubReg := R_SUBL;
  10393. S_W:
  10394. TargetSubReg := R_SUBW;
  10395. S_L:
  10396. TargetSubReg := R_SUBD;
  10397. else
  10398. InternalError(2020112350);
  10399. end;
  10400. { Update the register to its new size }
  10401. setsubreg(ThisReg, TargetSubReg);
  10402. RegInUse := False;
  10403. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10404. begin
  10405. { Check to see if the active register is used afterwards;
  10406. if not, we can change it and make a saving. }
  10407. TransferUsedRegs(TmpUsedRegs);
  10408. { The target register may be marked as in use to cross
  10409. a jump to a distant label, so exclude it }
  10410. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10411. hp2 := p;
  10412. repeat
  10413. { Explicitly check for the excluded register (don't include the first
  10414. instruction as it may be reading from here }
  10415. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10416. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10417. begin
  10418. RegInUse := True;
  10419. Break;
  10420. end;
  10421. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10422. if not GetNextInstruction(hp2, hp2) then
  10423. InternalError(2020112340);
  10424. until (hp2 = hp1);
  10425. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10426. { We might still be able to get away with this }
  10427. RegInUse := not
  10428. (
  10429. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10430. (hp2.typ = ait_instruction) and
  10431. (
  10432. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10433. instruction that doesn't actually contain ThisReg }
  10434. (cs_opt_level3 in current_settings.optimizerswitches) or
  10435. RegInInstruction(ThisReg, hp2)
  10436. ) and
  10437. RegLoadedWithNewValue(ThisReg, hp2)
  10438. );
  10439. if not RegInUse then
  10440. begin
  10441. { Force the register size to the same as this instruction so it can be removed}
  10442. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10443. begin
  10444. TargetSize := S_L;
  10445. TargetSubReg := R_SUBD;
  10446. end
  10447. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10448. begin
  10449. TargetSize := S_W;
  10450. TargetSubReg := R_SUBW;
  10451. end;
  10452. ThisReg := taicpu(hp1).oper[1]^.reg;
  10453. setsubreg(ThisReg, TargetSubReg);
  10454. RegChanged := True;
  10455. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10456. TransferUsedRegs(TmpUsedRegs);
  10457. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10458. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10459. if p = hp1 then
  10460. begin
  10461. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10462. p_removed := True;
  10463. end
  10464. else
  10465. RemoveInstruction(hp1);
  10466. hp1_removed := True;
  10467. { Instruction will become "mov %reg,%reg" }
  10468. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10469. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10470. begin
  10471. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10472. RemoveCurrentP(p);
  10473. p_removed := True;
  10474. end
  10475. else
  10476. taicpu(p).oper[1]^.reg := ThisReg;
  10477. Result := True;
  10478. end
  10479. else
  10480. begin
  10481. if TargetSize <> MaxSize then
  10482. begin
  10483. { Since the register is in use, we have to force it to
  10484. MaxSize otherwise part of it may become undefined later on }
  10485. TargetSize := MaxSize;
  10486. case TargetSize of
  10487. S_B:
  10488. TargetSubReg := R_SUBL;
  10489. S_W:
  10490. TargetSubReg := R_SUBW;
  10491. S_L:
  10492. TargetSubReg := R_SUBD;
  10493. else
  10494. InternalError(2020112351);
  10495. end;
  10496. setsubreg(ThisReg, TargetSubReg);
  10497. end;
  10498. AdjustFinalLoad;
  10499. end;
  10500. end
  10501. else
  10502. AdjustFinalLoad;
  10503. Result := AdjustInitialLoadAndSize or Result;
  10504. { Now go through every instruction we found and change the
  10505. size. If TargetSize = MaxSize, then almost no changes are
  10506. needed and Result can remain False if it hasn't been set
  10507. yet.
  10508. If RegChanged is True, then the register requires changing
  10509. and so the point about TargetSize = MaxSize doesn't apply. }
  10510. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10511. begin
  10512. for LocalIndex := 0 to InstrMax do
  10513. begin
  10514. { If p_removed is true, then the original MOV/Z was removed
  10515. and removing the AND instruction may not be safe if it
  10516. appears first }
  10517. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10518. InternalError(2020112310);
  10519. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10520. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10521. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10522. InstrList[LocalIndex].opsize := TargetSize;
  10523. end;
  10524. Result := True;
  10525. end;
  10526. end;
  10527. begin
  10528. Result := False;
  10529. p_removed := False;
  10530. hp1_removed := False;
  10531. ThisReg := taicpu(p).oper[1]^.reg;
  10532. { Check for:
  10533. movs/z ###,%ecx (or %cx or %rcx)
  10534. ...
  10535. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10536. (dealloc %ecx)
  10537. Change to:
  10538. mov ###,%cl (if ### = %cl, then remove completely)
  10539. ...
  10540. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10541. }
  10542. if (getsupreg(ThisReg) = RS_ECX) and
  10543. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10544. (hp1.typ = ait_instruction) and
  10545. (
  10546. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10547. instruction that doesn't actually contain ECX }
  10548. (cs_opt_level3 in current_settings.optimizerswitches) or
  10549. RegInInstruction(NR_ECX, hp1) or
  10550. (
  10551. { It's common for the shift/rotate's read/write register to be
  10552. initialised in between, so under -O2 and under, search ahead
  10553. one more instruction
  10554. }
  10555. GetNextInstruction(hp1, hp1) and
  10556. (hp1.typ = ait_instruction) and
  10557. RegInInstruction(NR_ECX, hp1)
  10558. )
  10559. ) and
  10560. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10561. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10562. begin
  10563. TransferUsedRegs(TmpUsedRegs);
  10564. hp2 := p;
  10565. repeat
  10566. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10567. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10568. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10569. begin
  10570. case taicpu(p).opsize of
  10571. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10572. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10573. begin
  10574. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10575. RemoveCurrentP(p);
  10576. end
  10577. else
  10578. begin
  10579. taicpu(p).opcode := A_MOV;
  10580. taicpu(p).opsize := S_B;
  10581. taicpu(p).oper[1]^.reg := NR_CL;
  10582. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10583. end;
  10584. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10585. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10586. begin
  10587. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10588. RemoveCurrentP(p);
  10589. end
  10590. else
  10591. begin
  10592. taicpu(p).opcode := A_MOV;
  10593. taicpu(p).opsize := S_W;
  10594. taicpu(p).oper[1]^.reg := NR_CX;
  10595. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10596. end;
  10597. {$ifdef x86_64}
  10598. S_LQ:
  10599. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10600. begin
  10601. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10602. RemoveCurrentP(p);
  10603. end
  10604. else
  10605. begin
  10606. taicpu(p).opcode := A_MOV;
  10607. taicpu(p).opsize := S_L;
  10608. taicpu(p).oper[1]^.reg := NR_ECX;
  10609. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10610. end;
  10611. {$endif x86_64}
  10612. else
  10613. InternalError(2021120401);
  10614. end;
  10615. Result := True;
  10616. Exit;
  10617. end;
  10618. end;
  10619. { This is anything but quick! }
  10620. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10621. Exit;
  10622. SetLength(InstrList, 0);
  10623. InstrMax := -1;
  10624. case taicpu(p).opsize of
  10625. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10626. begin
  10627. {$if defined(i386) or defined(i8086)}
  10628. { If the target size is 8-bit, make sure we can actually encode it }
  10629. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10630. Exit;
  10631. {$endif i386 or i8086}
  10632. LowerLimit := $FF;
  10633. SignedLowerLimit := $7F;
  10634. SignedLowerLimitBottom := -128;
  10635. MinSize := S_B;
  10636. if taicpu(p).opsize = S_BW then
  10637. begin
  10638. MaxSize := S_W;
  10639. UpperLimit := $FFFF;
  10640. SignedUpperLimit := $7FFF;
  10641. SignedUpperLimitBottom := -32768;
  10642. end
  10643. else
  10644. begin
  10645. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10646. MaxSize := S_L;
  10647. UpperLimit := $FFFFFFFF;
  10648. SignedUpperLimit := $7FFFFFFF;
  10649. SignedUpperLimitBottom := -2147483648;
  10650. end;
  10651. end;
  10652. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10653. begin
  10654. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10655. LowerLimit := $FFFF;
  10656. SignedLowerLimit := $7FFF;
  10657. SignedLowerLimitBottom := -32768;
  10658. UpperLimit := $FFFFFFFF;
  10659. SignedUpperLimit := $7FFFFFFF;
  10660. SignedUpperLimitBottom := -2147483648;
  10661. MinSize := S_W;
  10662. MaxSize := S_L;
  10663. end;
  10664. {$ifdef x86_64}
  10665. S_LQ:
  10666. begin
  10667. { Both the lower and upper limits are set to 32-bit. If a limit
  10668. is breached, then optimisation is impossible }
  10669. LowerLimit := $FFFFFFFF;
  10670. SignedLowerLimit := $7FFFFFFF;
  10671. SignedLowerLimitBottom := -2147483648;
  10672. UpperLimit := $FFFFFFFF;
  10673. SignedUpperLimit := $7FFFFFFF;
  10674. SignedUpperLimitBottom := -2147483648;
  10675. MinSize := S_L;
  10676. MaxSize := S_L;
  10677. end;
  10678. {$endif x86_64}
  10679. else
  10680. InternalError(2020112301);
  10681. end;
  10682. TestValMin := 0;
  10683. TestValMax := LowerLimit;
  10684. TestValSignedMax := SignedLowerLimit;
  10685. TryShiftDownLimit := LowerLimit;
  10686. TryShiftDown := S_NO;
  10687. ShiftDownOverflow := False;
  10688. RegChanged := False;
  10689. BitwiseOnly := True;
  10690. OrXorUsed := False;
  10691. UpperSignedOverflow := False;
  10692. LowerSignedOverflow := False;
  10693. UpperUnsignedOverflow := False;
  10694. LowerUnsignedOverflow := False;
  10695. hp1 := p;
  10696. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10697. (hp1.typ = ait_instruction) and
  10698. (
  10699. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10700. instruction that doesn't actually contain ThisReg }
  10701. (cs_opt_level3 in current_settings.optimizerswitches) or
  10702. { This allows this Movx optimisation to work through the SETcc instructions
  10703. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10704. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10705. skip over these SETcc instructions). }
  10706. (taicpu(hp1).opcode = A_SETcc) or
  10707. RegInInstruction(ThisReg, hp1)
  10708. ) do
  10709. begin
  10710. case taicpu(hp1).opcode of
  10711. A_INC,A_DEC:
  10712. begin
  10713. { Has to be an exact match on the register }
  10714. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10715. Break;
  10716. if taicpu(hp1).opcode = A_INC then
  10717. begin
  10718. Inc(TestValMin);
  10719. Inc(TestValMax);
  10720. Inc(TestValSignedMax);
  10721. end
  10722. else
  10723. begin
  10724. Dec(TestValMin);
  10725. Dec(TestValMax);
  10726. Dec(TestValSignedMax);
  10727. end;
  10728. end;
  10729. A_TEST, A_CMP:
  10730. begin
  10731. if (
  10732. { Too high a risk of non-linear behaviour that breaks DFA
  10733. here, unless it's cmp $0,%reg, which is equivalent to
  10734. test %reg,%reg }
  10735. OrXorUsed and
  10736. (taicpu(hp1).opcode = A_CMP) and
  10737. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10738. ) or
  10739. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10740. { Has to be an exact match on the register }
  10741. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10742. (
  10743. { Permit "test %reg,%reg" }
  10744. (taicpu(hp1).opcode = A_TEST) and
  10745. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10746. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10747. ) or
  10748. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10749. { Make sure the comparison value is not smaller than the
  10750. smallest allowed signed value for the minimum size (e.g.
  10751. -128 for 8-bit) }
  10752. not (
  10753. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10754. { Is it in the negative range? }
  10755. (
  10756. (taicpu(hp1).oper[0]^.val < 0) and
  10757. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10758. )
  10759. ) then
  10760. Break;
  10761. { Check to see if the active register is used afterwards }
  10762. TransferUsedRegs(TmpUsedRegs);
  10763. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10764. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10765. begin
  10766. { Make sure the comparison or any previous instructions
  10767. hasn't pushed the test values outside of the range of
  10768. MinSize }
  10769. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10770. begin
  10771. { Exceeded lower bound but not upper bound }
  10772. Exit;
  10773. end
  10774. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10775. begin
  10776. { Size didn't exceed lower bound }
  10777. TargetSize := MinSize;
  10778. end
  10779. else
  10780. Break;
  10781. case TargetSize of
  10782. S_B:
  10783. TargetSubReg := R_SUBL;
  10784. S_W:
  10785. TargetSubReg := R_SUBW;
  10786. S_L:
  10787. TargetSubReg := R_SUBD;
  10788. else
  10789. InternalError(2021051002);
  10790. end;
  10791. if TargetSize <> MaxSize then
  10792. begin
  10793. { Update the register to its new size }
  10794. setsubreg(ThisReg, TargetSubReg);
  10795. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10796. taicpu(hp1).oper[1]^.reg := ThisReg;
  10797. taicpu(hp1).opsize := TargetSize;
  10798. { Convert the input MOVZX to a MOV if necessary }
  10799. AdjustInitialLoadAndSize;
  10800. if (InstrMax >= 0) then
  10801. begin
  10802. for Index := 0 to InstrMax do
  10803. begin
  10804. { If p_removed is true, then the original MOV/Z was removed
  10805. and removing the AND instruction may not be safe if it
  10806. appears first }
  10807. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10808. InternalError(2020112311);
  10809. if InstrList[Index].oper[0]^.typ = top_reg then
  10810. InstrList[Index].oper[0]^.reg := ThisReg;
  10811. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10812. InstrList[Index].opsize := MinSize;
  10813. end;
  10814. end;
  10815. Result := True;
  10816. end;
  10817. Exit;
  10818. end;
  10819. end;
  10820. A_SETcc:
  10821. begin
  10822. { This allows this Movx optimisation to work through the SETcc instructions
  10823. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10824. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10825. skip over these SETcc instructions). }
  10826. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10827. { Of course, break out if the current register is used }
  10828. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10829. Break
  10830. else
  10831. { We must use Continue so the instruction doesn't get added
  10832. to InstrList }
  10833. Continue;
  10834. end;
  10835. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10836. begin
  10837. if
  10838. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10839. { Has to be an exact match on the register }
  10840. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10841. (
  10842. (
  10843. (taicpu(hp1).oper[0]^.typ = top_const) and
  10844. (
  10845. (
  10846. (taicpu(hp1).opcode = A_SHL) and
  10847. (
  10848. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10849. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10850. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10851. )
  10852. ) or (
  10853. (taicpu(hp1).opcode <> A_SHL) and
  10854. (
  10855. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10856. { Is it in the negative range? }
  10857. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10858. )
  10859. )
  10860. )
  10861. ) or (
  10862. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10863. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10864. )
  10865. ) then
  10866. Break;
  10867. { Only process OR and XOR if there are only bitwise operations,
  10868. since otherwise they can too easily fool the data flow
  10869. analysis (they can cause non-linear behaviour) }
  10870. case taicpu(hp1).opcode of
  10871. A_ADD:
  10872. begin
  10873. if OrXorUsed then
  10874. { Too high a risk of non-linear behaviour that breaks DFA here }
  10875. Break
  10876. else
  10877. BitwiseOnly := False;
  10878. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10879. begin
  10880. TestValMin := TestValMin * 2;
  10881. TestValMax := TestValMax * 2;
  10882. TestValSignedMax := TestValSignedMax * 2;
  10883. end
  10884. else
  10885. begin
  10886. WorkingValue := taicpu(hp1).oper[0]^.val;
  10887. TestValMin := TestValMin + WorkingValue;
  10888. TestValMax := TestValMax + WorkingValue;
  10889. TestValSignedMax := TestValSignedMax + WorkingValue;
  10890. end;
  10891. end;
  10892. A_SUB:
  10893. begin
  10894. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10895. begin
  10896. TestValMin := 0;
  10897. TestValMax := 0;
  10898. TestValSignedMax := 0;
  10899. end
  10900. else
  10901. begin
  10902. if OrXorUsed then
  10903. { Too high a risk of non-linear behaviour that breaks DFA here }
  10904. Break
  10905. else
  10906. BitwiseOnly := False;
  10907. WorkingValue := taicpu(hp1).oper[0]^.val;
  10908. TestValMin := TestValMin - WorkingValue;
  10909. TestValMax := TestValMax - WorkingValue;
  10910. TestValSignedMax := TestValSignedMax - WorkingValue;
  10911. end;
  10912. end;
  10913. A_AND:
  10914. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10915. begin
  10916. { we might be able to go smaller if AND appears first }
  10917. if InstrMax = -1 then
  10918. case MinSize of
  10919. S_B:
  10920. ;
  10921. S_W:
  10922. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10923. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10924. begin
  10925. TryShiftDown := S_B;
  10926. TryShiftDownLimit := $FF;
  10927. end;
  10928. S_L:
  10929. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10930. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10931. begin
  10932. TryShiftDown := S_B;
  10933. TryShiftDownLimit := $FF;
  10934. end
  10935. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10936. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10937. begin
  10938. TryShiftDown := S_W;
  10939. TryShiftDownLimit := $FFFF;
  10940. end;
  10941. else
  10942. InternalError(2020112320);
  10943. end;
  10944. WorkingValue := taicpu(hp1).oper[0]^.val;
  10945. TestValMin := TestValMin and WorkingValue;
  10946. TestValMax := TestValMax and WorkingValue;
  10947. TestValSignedMax := TestValSignedMax and WorkingValue;
  10948. end;
  10949. A_OR:
  10950. begin
  10951. if not BitwiseOnly then
  10952. Break;
  10953. OrXorUsed := True;
  10954. WorkingValue := taicpu(hp1).oper[0]^.val;
  10955. TestValMin := TestValMin or WorkingValue;
  10956. TestValMax := TestValMax or WorkingValue;
  10957. TestValSignedMax := TestValSignedMax or WorkingValue;
  10958. end;
  10959. A_XOR:
  10960. begin
  10961. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10962. begin
  10963. TestValMin := 0;
  10964. TestValMax := 0;
  10965. TestValSignedMax := 0;
  10966. end
  10967. else
  10968. begin
  10969. if not BitwiseOnly then
  10970. Break;
  10971. OrXorUsed := True;
  10972. WorkingValue := taicpu(hp1).oper[0]^.val;
  10973. TestValMin := TestValMin xor WorkingValue;
  10974. TestValMax := TestValMax xor WorkingValue;
  10975. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10976. end;
  10977. end;
  10978. A_SHL:
  10979. begin
  10980. BitwiseOnly := False;
  10981. WorkingValue := taicpu(hp1).oper[0]^.val;
  10982. TestValMin := TestValMin shl WorkingValue;
  10983. TestValMax := TestValMax shl WorkingValue;
  10984. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10985. end;
  10986. A_SHR,
  10987. { The first instruction was MOVZX, so the value won't be negative }
  10988. A_SAR:
  10989. begin
  10990. if InstrMax <> -1 then
  10991. BitwiseOnly := False
  10992. else
  10993. { we might be able to go smaller if SHR appears first }
  10994. case MinSize of
  10995. S_B:
  10996. ;
  10997. S_W:
  10998. if (taicpu(hp1).oper[0]^.val >= 8) then
  10999. begin
  11000. TryShiftDown := S_B;
  11001. TryShiftDownLimit := $FF;
  11002. TryShiftDownSignedLimit := $7F;
  11003. TryShiftDownSignedLimitLower := -128;
  11004. end;
  11005. S_L:
  11006. if (taicpu(hp1).oper[0]^.val >= 24) then
  11007. begin
  11008. TryShiftDown := S_B;
  11009. TryShiftDownLimit := $FF;
  11010. TryShiftDownSignedLimit := $7F;
  11011. TryShiftDownSignedLimitLower := -128;
  11012. end
  11013. else if (taicpu(hp1).oper[0]^.val >= 16) then
  11014. begin
  11015. TryShiftDown := S_W;
  11016. TryShiftDownLimit := $FFFF;
  11017. TryShiftDownSignedLimit := $7FFF;
  11018. TryShiftDownSignedLimitLower := -32768;
  11019. end;
  11020. else
  11021. InternalError(2020112321);
  11022. end;
  11023. WorkingValue := taicpu(hp1).oper[0]^.val;
  11024. if taicpu(hp1).opcode = A_SAR then
  11025. begin
  11026. TestValMin := SarInt64(TestValMin, WorkingValue);
  11027. TestValMax := SarInt64(TestValMax, WorkingValue);
  11028. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  11029. end
  11030. else
  11031. begin
  11032. TestValMin := TestValMin shr WorkingValue;
  11033. TestValMax := TestValMax shr WorkingValue;
  11034. TestValSignedMax := TestValSignedMax shr WorkingValue;
  11035. end;
  11036. end;
  11037. else
  11038. InternalError(2020112303);
  11039. end;
  11040. end;
  11041. (*
  11042. A_IMUL:
  11043. case taicpu(hp1).ops of
  11044. 2:
  11045. begin
  11046. if not MatchOpType(hp1, top_reg, top_reg) or
  11047. { Has to be an exact match on the register }
  11048. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  11049. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  11050. Break;
  11051. TestValMin := TestValMin * TestValMin;
  11052. TestValMax := TestValMax * TestValMax;
  11053. TestValSignedMax := TestValSignedMax * TestValMax;
  11054. end;
  11055. 3:
  11056. begin
  11057. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11058. { Has to be an exact match on the register }
  11059. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11060. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11061. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11062. { Is it in the negative range? }
  11063. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11064. Break;
  11065. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  11066. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  11067. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  11068. end;
  11069. else
  11070. Break;
  11071. end;
  11072. A_IDIV:
  11073. case taicpu(hp1).ops of
  11074. 3:
  11075. begin
  11076. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11077. { Has to be an exact match on the register }
  11078. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11079. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11080. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11081. { Is it in the negative range? }
  11082. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11083. Break;
  11084. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  11085. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  11086. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  11087. end;
  11088. else
  11089. Break;
  11090. end;
  11091. *)
  11092. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11093. begin
  11094. { If there are no instructions in between, then we might be able to make a saving }
  11095. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11096. Break;
  11097. { We have something like:
  11098. movzbw %dl,%dx
  11099. ...
  11100. movswl %dx,%edx
  11101. Change the latter to a zero-extension then enter the
  11102. A_MOVZX case branch.
  11103. }
  11104. {$ifdef x86_64}
  11105. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11106. begin
  11107. { this becomes a zero extension from 32-bit to 64-bit, but
  11108. the upper 32 bits are already zero, so just delete the
  11109. instruction }
  11110. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11111. RemoveInstruction(hp1);
  11112. Result := True;
  11113. Exit;
  11114. end
  11115. else
  11116. {$endif x86_64}
  11117. begin
  11118. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11119. taicpu(hp1).opcode := A_MOVZX;
  11120. {$ifdef x86_64}
  11121. case taicpu(hp1).opsize of
  11122. S_BQ:
  11123. begin
  11124. taicpu(hp1).opsize := S_BL;
  11125. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11126. end;
  11127. S_WQ:
  11128. begin
  11129. taicpu(hp1).opsize := S_WL;
  11130. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11131. end;
  11132. S_LQ:
  11133. begin
  11134. taicpu(hp1).opcode := A_MOV;
  11135. taicpu(hp1).opsize := S_L;
  11136. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11137. { In this instance, we need to break out because the
  11138. instruction is no longer MOVZX or MOVSXD }
  11139. Result := True;
  11140. Exit;
  11141. end;
  11142. else
  11143. ;
  11144. end;
  11145. {$endif x86_64}
  11146. Result := CompressInstructions;
  11147. Exit;
  11148. end;
  11149. end;
  11150. A_MOVZX:
  11151. begin
  11152. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11153. Break;
  11154. if (InstrMax = -1) then
  11155. begin
  11156. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11157. begin
  11158. { Optimise around i40003 }
  11159. { Check to see if the active register is used afterwards }
  11160. TransferUsedRegs(TmpUsedRegs);
  11161. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  11162. if (
  11163. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) or
  11164. not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs)
  11165. ) and
  11166. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11167. {$ifndef x86_64}
  11168. and (
  11169. (taicpu(p).oper[0]^.typ <> top_reg) or
  11170. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11171. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11172. )
  11173. {$endif not x86_64}
  11174. then
  11175. begin
  11176. if (taicpu(p).oper[0]^.typ = top_reg) then
  11177. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11178. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11179. taicpu(p).opsize := S_BL;
  11180. { Only remove if the active register is overwritten }
  11181. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11182. begin
  11183. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11184. RemoveInstruction(hp1);
  11185. end;
  11186. Result := True;
  11187. Exit;
  11188. end;
  11189. end
  11190. else
  11191. begin
  11192. { Will return false if the second parameter isn't ThisReg
  11193. (can happen on -O2 and under) }
  11194. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11195. begin
  11196. { The two MOVZX instructions are adjacent, so remove the first one }
  11197. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11198. RemoveCurrentP(p);
  11199. Result := True;
  11200. Exit;
  11201. end;
  11202. Break;
  11203. end;
  11204. end;
  11205. Result := CompressInstructions;
  11206. Exit;
  11207. end;
  11208. else
  11209. { This includes ADC, SBB and IDIV }
  11210. Break;
  11211. end;
  11212. if not CheckOverflowConditions then
  11213. Break;
  11214. { Contains highest index (so instruction count - 1) }
  11215. Inc(InstrMax);
  11216. if InstrMax > High(InstrList) then
  11217. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11218. InstrList[InstrMax] := taicpu(hp1);
  11219. end;
  11220. end;
  11221. {$pop}
  11222. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11223. var
  11224. hp1 : tai;
  11225. begin
  11226. Result:=false;
  11227. if (taicpu(p).ops >= 2) and
  11228. ((taicpu(p).oper[0]^.typ = top_const) or
  11229. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11230. (taicpu(p).oper[1]^.typ = top_reg) and
  11231. ((taicpu(p).ops = 2) or
  11232. ((taicpu(p).oper[2]^.typ = top_reg) and
  11233. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11234. GetLastInstruction(p,hp1) and
  11235. MatchInstruction(hp1,A_MOV,[]) and
  11236. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11237. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11238. begin
  11239. TransferUsedRegs(TmpUsedRegs);
  11240. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11241. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11242. { change
  11243. mov reg1,reg2
  11244. imul y,reg2 to imul y,reg1,reg2 }
  11245. begin
  11246. taicpu(p).ops := 3;
  11247. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11248. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11249. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11250. RemoveInstruction(hp1);
  11251. result:=true;
  11252. end;
  11253. end;
  11254. end;
  11255. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11256. var
  11257. ThisLabel: TAsmLabel;
  11258. begin
  11259. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11260. ThisLabel.decrefs;
  11261. taicpu(p).condition := C_None;
  11262. taicpu(p).opcode := A_RET;
  11263. taicpu(p).is_jmp := false;
  11264. taicpu(p).ops := taicpu(ret_p).ops;
  11265. case taicpu(ret_p).ops of
  11266. 0:
  11267. taicpu(p).clearop(0);
  11268. 1:
  11269. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11270. else
  11271. internalerror(2016041301);
  11272. end;
  11273. { If the original label is now dead, it might turn out that the label
  11274. immediately follows p. As a result, everything beyond it, which will
  11275. be just some final register configuration and a RET instruction, is
  11276. now dead code. [Kit] }
  11277. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11278. running RemoveDeadCodeAfterJump for each RET instruction, because
  11279. this optimisation rarely happens and most RETs appear at the end of
  11280. routines where there is nothing that can be stripped. [Kit] }
  11281. if not ThisLabel.is_used then
  11282. RemoveDeadCodeAfterJump(p);
  11283. end;
  11284. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11285. var
  11286. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11287. Unconditional, PotentialModified: Boolean;
  11288. OperPtr: POper;
  11289. NewRef: TReference;
  11290. InstrList: array of taicpu;
  11291. InstrMax, Index: Integer;
  11292. const
  11293. {$ifdef DEBUG_AOPTCPU}
  11294. SNoFlags: shortstring = ' so the flags aren''t modified';
  11295. {$else DEBUG_AOPTCPU}
  11296. SNoFlags = '';
  11297. {$endif DEBUG_AOPTCPU}
  11298. begin
  11299. Result:=false;
  11300. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11301. begin
  11302. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11303. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11304. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11305. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11306. GetNextInstruction(hp1, hp2) and
  11307. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11308. { Change from: To:
  11309. set(C) %reg j(~C) label
  11310. test %reg,%reg/cmp $0,%reg
  11311. je label
  11312. set(C) %reg j(C) label
  11313. test %reg,%reg/cmp $0,%reg
  11314. jne label
  11315. (Also do something similar with sete/setne instead of je/jne)
  11316. }
  11317. begin
  11318. { Before we do anything else, we need to check the instructions
  11319. in between SETcc and TEST to make sure they don't modify the
  11320. FLAGS register - if -O2 or under, there won't be any
  11321. instructions between SET and TEST }
  11322. TransferUsedRegs(TmpUsedRegs);
  11323. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11324. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11325. begin
  11326. next := p;
  11327. SetLength(InstrList, 0);
  11328. InstrMax := -1;
  11329. PotentialModified := False;
  11330. { Make a note of every instruction that modifies the FLAGS
  11331. register }
  11332. while GetNextInstruction(next, next) and (next <> hp1) do
  11333. begin
  11334. if next.typ <> ait_instruction then
  11335. { GetNextInstructionUsingReg should have returned False }
  11336. InternalError(2021051701);
  11337. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11338. begin
  11339. case taicpu(next).opcode of
  11340. A_SETcc,
  11341. A_CMOVcc,
  11342. A_Jcc:
  11343. begin
  11344. if PotentialModified then
  11345. { Not safe because the flags were modified earlier }
  11346. Exit
  11347. else
  11348. { Condition is the same as the initial SETcc, so this is safe
  11349. (don't add to instruction list though) }
  11350. Continue;
  11351. end;
  11352. A_ADD:
  11353. begin
  11354. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11355. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11356. (taicpu(next).oper[1]^.typ <> top_reg) or
  11357. { Must write to a register }
  11358. (taicpu(next).oper[0]^.typ = top_ref) then
  11359. { Require a constant or a register }
  11360. Exit;
  11361. PotentialModified := True;
  11362. end;
  11363. A_SUB:
  11364. begin
  11365. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11366. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11367. (taicpu(next).oper[1]^.typ <> top_reg) or
  11368. { Must write to a register }
  11369. (taicpu(next).oper[0]^.typ <> top_const) or
  11370. (taicpu(next).oper[0]^.val = $80000000) then
  11371. { Can't subtract a register with LEA - also
  11372. check that the value isn't -2^31, as this
  11373. can't be negated }
  11374. Exit;
  11375. PotentialModified := True;
  11376. end;
  11377. A_SAL,
  11378. A_SHL:
  11379. begin
  11380. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11381. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11382. (taicpu(next).oper[1]^.typ <> top_reg) or
  11383. { Must write to a register }
  11384. (taicpu(next).oper[0]^.typ <> top_const) or
  11385. (taicpu(next).oper[0]^.val < 0) or
  11386. (taicpu(next).oper[0]^.val > 3) then
  11387. Exit;
  11388. PotentialModified := True;
  11389. end;
  11390. A_IMUL:
  11391. begin
  11392. if (taicpu(next).ops <> 3) or
  11393. (taicpu(next).oper[1]^.typ <> top_reg) or
  11394. { Must write to a register }
  11395. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11396. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11397. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11398. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11399. Exit
  11400. else
  11401. PotentialModified := True;
  11402. end;
  11403. else
  11404. { Don't know how to change this, so abort }
  11405. Exit;
  11406. end;
  11407. { Contains highest index (so instruction count - 1) }
  11408. Inc(InstrMax);
  11409. if InstrMax > High(InstrList) then
  11410. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11411. InstrList[InstrMax] := taicpu(next);
  11412. end;
  11413. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11414. end;
  11415. if not Assigned(next) or (next <> hp1) then
  11416. { It should be equal to hp1 }
  11417. InternalError(2021051702);
  11418. { Cycle through each instruction and check to see if we can
  11419. change them to versions that don't modify the flags }
  11420. if (InstrMax >= 0) then
  11421. begin
  11422. for Index := 0 to InstrMax do
  11423. case InstrList[Index].opcode of
  11424. A_ADD:
  11425. begin
  11426. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11427. InstrList[Index].opcode := A_LEA;
  11428. reference_reset(NewRef, 1, []);
  11429. NewRef.base := InstrList[Index].oper[1]^.reg;
  11430. if InstrList[Index].oper[0]^.typ = top_reg then
  11431. begin
  11432. NewRef.index := InstrList[Index].oper[0]^.reg;
  11433. NewRef.scalefactor := 1;
  11434. end
  11435. else
  11436. NewRef.offset := InstrList[Index].oper[0]^.val;
  11437. InstrList[Index].loadref(0, NewRef);
  11438. end;
  11439. A_SUB:
  11440. begin
  11441. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11442. InstrList[Index].opcode := A_LEA;
  11443. reference_reset(NewRef, 1, []);
  11444. NewRef.base := InstrList[Index].oper[1]^.reg;
  11445. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11446. InstrList[Index].loadref(0, NewRef);
  11447. end;
  11448. A_SHL,
  11449. A_SAL:
  11450. begin
  11451. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11452. InstrList[Index].opcode := A_LEA;
  11453. reference_reset(NewRef, 1, []);
  11454. NewRef.index := InstrList[Index].oper[1]^.reg;
  11455. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11456. InstrList[Index].loadref(0, NewRef);
  11457. end;
  11458. A_IMUL:
  11459. begin
  11460. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11461. InstrList[Index].opcode := A_LEA;
  11462. reference_reset(NewRef, 1, []);
  11463. NewRef.index := InstrList[Index].oper[1]^.reg;
  11464. case InstrList[Index].oper[0]^.val of
  11465. 2, 4, 8:
  11466. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11467. else {3, 5 and 9}
  11468. begin
  11469. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11470. NewRef.base := InstrList[Index].oper[1]^.reg;
  11471. end;
  11472. end;
  11473. InstrList[Index].loadref(0, NewRef);
  11474. end;
  11475. else
  11476. InternalError(2021051710);
  11477. end;
  11478. end;
  11479. { Mark the FLAGS register as used across this whole block }
  11480. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11481. end;
  11482. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11483. JumpC := taicpu(hp2).condition;
  11484. Unconditional := False;
  11485. if conditions_equal(JumpC, C_E) then
  11486. SetC := inverse_cond(taicpu(p).condition)
  11487. else if conditions_equal(JumpC, C_NE) then
  11488. SetC := taicpu(p).condition
  11489. else
  11490. { We've got something weird here (and inefficent) }
  11491. begin
  11492. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11493. SetC := C_NONE;
  11494. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11495. if condition_in(C_AE, JumpC) then
  11496. Unconditional := True
  11497. else
  11498. { Not sure what to do with this jump - drop out }
  11499. Exit;
  11500. end;
  11501. RemoveInstruction(hp1);
  11502. if Unconditional then
  11503. MakeUnconditional(taicpu(hp2))
  11504. else
  11505. begin
  11506. if SetC = C_NONE then
  11507. InternalError(2018061402);
  11508. taicpu(hp2).SetCondition(SetC);
  11509. end;
  11510. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11511. TmpUsedRegs }
  11512. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11513. begin
  11514. RemoveCurrentp(p, hp2);
  11515. if taicpu(hp2).opcode = A_SETcc then
  11516. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11517. else
  11518. begin
  11519. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11520. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11521. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11522. end;
  11523. end
  11524. else
  11525. if taicpu(hp2).opcode = A_SETcc then
  11526. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11527. else
  11528. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11529. Result := True;
  11530. end
  11531. else if
  11532. { Make sure the instructions are adjacent }
  11533. (
  11534. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11535. GetNextInstruction(p, hp1)
  11536. ) and
  11537. MatchInstruction(hp1, A_MOV, [S_B]) and
  11538. { Writing to memory is allowed }
  11539. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11540. begin
  11541. {
  11542. Watch out for sequences such as:
  11543. set(c)b %regb
  11544. movb %regb,(ref)
  11545. movb $0,1(ref)
  11546. movb $0,2(ref)
  11547. movb $0,3(ref)
  11548. Much more efficient to turn it into:
  11549. movl $0,%regl
  11550. set(c)b %regb
  11551. movl %regl,(ref)
  11552. Or:
  11553. set(c)b %regb
  11554. movzbl %regb,%regl
  11555. movl %regl,(ref)
  11556. }
  11557. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11558. GetNextInstruction(hp1, hp2) and
  11559. MatchInstruction(hp2, A_MOV, [S_B]) and
  11560. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11561. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11562. begin
  11563. { Don't do anything else except set Result to True }
  11564. end
  11565. else
  11566. begin
  11567. if taicpu(p).oper[0]^.typ = top_reg then
  11568. begin
  11569. TransferUsedRegs(TmpUsedRegs);
  11570. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11571. end;
  11572. { If it's not a register, it's a memory address }
  11573. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11574. begin
  11575. { Even if the register is still in use, we can minimise the
  11576. pipeline stall by changing the MOV into another SETcc. }
  11577. taicpu(hp1).opcode := A_SETcc;
  11578. taicpu(hp1).condition := taicpu(p).condition;
  11579. if taicpu(hp1).oper[1]^.typ = top_ref then
  11580. begin
  11581. { Swapping the operand pointers like this is probably a
  11582. bit naughty, but it is far faster than using loadoper
  11583. to transfer the reference from oper[1] to oper[0] if
  11584. you take into account the extra procedure calls and
  11585. the memory allocation and deallocation required }
  11586. OperPtr := taicpu(hp1).oper[1];
  11587. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11588. taicpu(hp1).oper[0] := OperPtr;
  11589. end
  11590. else
  11591. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11592. taicpu(hp1).clearop(1);
  11593. taicpu(hp1).ops := 1;
  11594. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11595. end
  11596. else
  11597. begin
  11598. if taicpu(hp1).oper[1]^.typ = top_reg then
  11599. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11600. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11601. RemoveInstruction(hp1);
  11602. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11603. end
  11604. end;
  11605. Result := True;
  11606. end;
  11607. end;
  11608. end;
  11609. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11610. var
  11611. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11612. TargetReg: TRegister;
  11613. condition, inverted_condition: TAsmCond;
  11614. FoundMOV: Boolean;
  11615. begin
  11616. Result := False;
  11617. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11618. create the most optimial instructions possible due to limited
  11619. register availability, and there are situations where two
  11620. complementary "simple" CMOV blocks are created which, after the fact
  11621. can be merged into a "double" block. For example:
  11622. movw $257,%ax
  11623. movw $2,%r8w
  11624. xorl r9d,%r9d
  11625. testw $16,18(%rcx)
  11626. cmovew %ax,%dx
  11627. cmovew %r8w,%bx
  11628. cmovel %r9d,%r14d
  11629. movw $1283,%ax
  11630. movw $4,%r8w
  11631. movl $9,%r9d
  11632. cmovnew %ax,%dx
  11633. cmovnew %r8w,%bx
  11634. cmovnel %r9d,%r14d
  11635. The CMOVNE instructions at the end can be removed, and the
  11636. destination registers copied into the MOV instructions directly
  11637. above them, before finally being moved to before the first CMOVE
  11638. instructions, to produce:
  11639. movw $257,%ax
  11640. movw $2,%r8w
  11641. xorl r9d,%r9d
  11642. testw $16,18(%rcx)
  11643. movw $1283,%dx
  11644. movw $4,%bx
  11645. movl $9,%r14d
  11646. cmovew %ax,%dx
  11647. cmovew %r8w,%bx
  11648. cmovel %r9d,%r14d
  11649. Which can then be later optimised to:
  11650. movw $257,%ax
  11651. movw $2,%r8w
  11652. xorl r9d,%r9d
  11653. movw $1283,%dx
  11654. movw $4,%bx
  11655. movl $9,%r14d
  11656. testw $16,18(%rcx)
  11657. cmovew %ax,%dx
  11658. cmovew %r8w,%bx
  11659. cmovel %r9d,%r14d
  11660. }
  11661. TargetReg := taicpu(hp1).oper[1]^.reg;
  11662. condition := taicpu(hp1).condition;
  11663. inverted_condition := inverse_cond(condition);
  11664. pFirstMov := nil;
  11665. pLastMov := nil;
  11666. pCMOV := nil;
  11667. if (p.typ = ait_instruction) then
  11668. pCond := p
  11669. else if not GetNextInstruction(p, pCond) then
  11670. InternalError(2024012501);
  11671. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11672. { We should get the CMP or TEST instructeion }
  11673. InternalError(2024012502);
  11674. if (
  11675. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11676. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11677. ) then
  11678. begin
  11679. { We have to tread carefully here, hence why we're not using
  11680. GetNextInstructionUsingReg... we can only accept MOV and other
  11681. CMOV instructions. Anything else and we must drop out}
  11682. hp2 := hp1;
  11683. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11684. begin
  11685. if (hp2.typ <> ait_instruction) then
  11686. Exit;
  11687. case taicpu(hp2).opcode of
  11688. A_MOV:
  11689. begin
  11690. if not Assigned(pFirstMov) then
  11691. pFirstMov := hp2;
  11692. pLastMOV := hp2;
  11693. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11694. { Something different - drop out }
  11695. Exit;
  11696. { Otherwise, leave it for now }
  11697. end;
  11698. A_CMOVcc:
  11699. begin
  11700. if taicpu(hp2).condition = inverted_condition then
  11701. begin
  11702. { We found what we're looking for }
  11703. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11704. begin
  11705. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11706. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11707. begin
  11708. pCMOV := hp2;
  11709. Break;
  11710. end
  11711. else
  11712. { Unsafe reference - drop out }
  11713. Exit;
  11714. end;
  11715. end
  11716. else if taicpu(hp2).condition <> condition then
  11717. { Something weird - drop out }
  11718. Exit;
  11719. end;
  11720. else
  11721. { Invalid }
  11722. Exit;
  11723. end;
  11724. end;
  11725. if not Assigned(pCMOV) then
  11726. { No complementary CMOV found }
  11727. Exit;
  11728. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11729. begin
  11730. { Don't need to do anything special or search for a matching MOV }
  11731. Asml.Remove(pCMOV);
  11732. if RegInInstruction(TargetReg, pCond) then
  11733. { Make sure we don't overwrite the register if it's being used in the condition }
  11734. Asml.InsertAfter(pCMOV, pCond)
  11735. else
  11736. Asml.InsertBefore(pCMOV, pCond);
  11737. taicpu(pCMOV).opcode := A_MOV;
  11738. taicpu(pCMOV).condition := C_None;
  11739. { Don't need to worry about allocating new registers in these cases }
  11740. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11741. Result := True;
  11742. Exit;
  11743. end
  11744. else
  11745. begin
  11746. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11747. FoundMOV := False;
  11748. { Search for the MOV that sets the target register }
  11749. hp2 := pFirstMov;
  11750. repeat
  11751. if (taicpu(hp2).opcode = A_MOV) and
  11752. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11753. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11754. begin
  11755. { Change the destination }
  11756. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11757. if not FoundMOV then
  11758. begin
  11759. FoundMOV := True;
  11760. { Make sure the register is allocated }
  11761. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11762. end;
  11763. hp1 := tai(hp2.Previous);
  11764. Asml.Remove(hp2);
  11765. if RegInInstruction(TargetReg, pCond) then
  11766. { Make sure we don't overwrite the register if it's being used in the condition }
  11767. Asml.InsertAfter(hp2, pCond)
  11768. else
  11769. Asml.InsertBefore(hp2, pCond);
  11770. if (hp2 = pLastMov) then
  11771. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11772. Break;
  11773. hp2 := hp1;
  11774. end;
  11775. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11776. if FoundMOV then
  11777. { Delete the CMOV }
  11778. RemoveInstruction(pCMOV)
  11779. else
  11780. begin
  11781. { If no MOV was found, we have to actually move and transmute the CMOV }
  11782. Asml.Remove(pCMOV);
  11783. if RegInInstruction(TargetReg, pCond) then
  11784. { Make sure we don't overwrite the register if it's being used in the condition }
  11785. Asml.InsertAfter(pCMOV, pCond)
  11786. else
  11787. Asml.InsertBefore(pCMOV, pCond);
  11788. taicpu(pCMOV).opcode := A_MOV;
  11789. taicpu(pCMOV).condition := C_None;
  11790. end;
  11791. Result := True;
  11792. Exit;
  11793. end;
  11794. end;
  11795. end;
  11796. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11797. var
  11798. hp1, hp2, pCond: tai;
  11799. begin
  11800. Result := False;
  11801. { Search ahead for CMOV instructions }
  11802. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11803. begin
  11804. hp1 := p;
  11805. hp2 := p;
  11806. pCond := nil; { To prevent compiler warnings }
  11807. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11808. DEFAULTFLAGS }
  11809. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11810. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11811. pCond := p;
  11812. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11813. begin
  11814. if (hp1.typ <> ait_instruction) then
  11815. { Break out on markers and labels etc. }
  11816. Break;
  11817. case taicpu(hp1).opcode of
  11818. A_MOV:
  11819. { Ignore regular MOVs unless they are obviously not related
  11820. to a CMOV block }
  11821. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11822. Break;
  11823. A_CMOVcc:
  11824. if TryCmpCMovOpts(pCond, hp1) then
  11825. begin
  11826. hp1 := hp2;
  11827. { p itself isn't changed, and we're still inside a
  11828. while loop to catch subsequent CMOVs, so just flag
  11829. a new iteration }
  11830. Include(OptsToCheck, aoc_ForceNewIteration);
  11831. Continue;
  11832. end;
  11833. else
  11834. { Drop out if we find anything else }
  11835. Break;
  11836. end;
  11837. hp2 := hp1;
  11838. end;
  11839. end;
  11840. end;
  11841. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11842. var
  11843. hp1, hp2, pCond: tai;
  11844. SourceReg, TargetReg: TRegister;
  11845. begin
  11846. Result := False;
  11847. { In some situations, we end up with an inefficient arrangement of
  11848. instructions in the form of:
  11849. or %reg1,%reg2
  11850. (%reg1 deallocated)
  11851. test %reg2,%reg2
  11852. mov x,%reg2
  11853. we may be able to swap and rearrange the registers to produce:
  11854. or %reg2,%reg1
  11855. mov x,%reg2
  11856. test %reg1,%reg1
  11857. (%reg1 deallocated)
  11858. }
  11859. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11860. (taicpu(p).oper[1]^.typ = top_reg) and
  11861. (
  11862. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11863. MatchOperand(taicpu(p).oper[0]^, -1)
  11864. ) and
  11865. GetNextInstruction(p, hp1) and
  11866. MatchInstruction(hp1, A_MOV, []) and
  11867. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11868. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11869. begin
  11870. TargetReg := taicpu(p).oper[1]^.reg;
  11871. { Now look backwards to find a simple commutative operation: ADD,
  11872. IMUL (2-register version), OR, AND or XOR - whose destination
  11873. register is the same as TEST }
  11874. hp2 := p;
  11875. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11876. if RegInInstruction(TargetReg, hp2) then
  11877. begin
  11878. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11879. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11880. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11881. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11882. begin
  11883. SourceReg := taicpu(hp2).oper[0]^.reg;
  11884. if
  11885. { Make sure the MOV doesn't use the other register }
  11886. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11887. { And make sure the source register is not used afterwards }
  11888. not RegInUsedRegs(SourceReg, UsedRegs) then
  11889. begin
  11890. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11891. taicpu(hp2).oper[0]^.reg := TargetReg;
  11892. taicpu(hp2).oper[1]^.reg := SourceReg;
  11893. if taicpu(p).oper[0]^.typ = top_reg then
  11894. taicpu(p).oper[0]^.reg := SourceReg;
  11895. taicpu(p).oper[1]^.reg := SourceReg;
  11896. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11897. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11898. Include(OptsToCheck, aoc_ForceNewIteration);
  11899. { We can still check the following optimisations since
  11900. the instruction is still a TEST }
  11901. end;
  11902. end;
  11903. Break;
  11904. end;
  11905. end;
  11906. { Search ahead3 for CMOV instructions }
  11907. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11908. begin
  11909. hp1 := p;
  11910. hp2 := p;
  11911. pCond := nil; { To prevent compiler warnings }
  11912. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11913. DEFAULTFLAGS }
  11914. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11915. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11916. pCond := p;
  11917. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11918. begin
  11919. if (hp1.typ <> ait_instruction) then
  11920. { Break out on markers and labels etc. }
  11921. Break;
  11922. case taicpu(hp1).opcode of
  11923. A_MOV:
  11924. { Ignore regular MOVs unless they are obviously not related
  11925. to a CMOV block }
  11926. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11927. Break;
  11928. A_CMOVcc:
  11929. if TryCmpCMovOpts(pCond, hp1) then
  11930. begin
  11931. hp1 := hp2;
  11932. { p itself isn't changed, and we're still inside a
  11933. while loop to catch subsequent CMOVs, so just flag
  11934. a new iteration }
  11935. Include(OptsToCheck, aoc_ForceNewIteration);
  11936. Continue;
  11937. end;
  11938. else
  11939. { Drop out if we find anything else }
  11940. Break;
  11941. end;
  11942. hp2 := hp1;
  11943. end;
  11944. end;
  11945. end;
  11946. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11947. var
  11948. hp1: tai;
  11949. Count: Integer;
  11950. OrigLabel: TAsmLabel;
  11951. begin
  11952. result := False;
  11953. { Sometimes, the optimisations below can permit this }
  11954. RemoveDeadCodeAfterJump(p);
  11955. 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
  11956. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11957. begin
  11958. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11959. { Also a side-effect of optimisations }
  11960. if CollapseZeroDistJump(p, OrigLabel) then
  11961. begin
  11962. Result := True;
  11963. Exit;
  11964. end;
  11965. hp1 := GetLabelWithSym(OrigLabel);
  11966. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11967. begin
  11968. if taicpu(hp1).opcode = A_RET then
  11969. begin
  11970. {
  11971. change
  11972. jmp .L1
  11973. ...
  11974. .L1:
  11975. ret
  11976. into
  11977. ret
  11978. }
  11979. begin
  11980. ConvertJumpToRET(p, hp1);
  11981. result:=true;
  11982. end;
  11983. end
  11984. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11985. not (cs_opt_size in current_settings.optimizerswitches) and
  11986. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11987. begin
  11988. Result := True;
  11989. Exit;
  11990. end;
  11991. end;
  11992. end;
  11993. end;
  11994. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11995. begin
  11996. Result := assigned(p) and
  11997. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11998. (taicpu(p).oper[1]^.typ = top_reg) and
  11999. (
  12000. (taicpu(p).oper[0]^.typ = top_reg) or
  12001. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  12002. it is not expected that this can cause a seg. violation }
  12003. (
  12004. (taicpu(p).oper[0]^.typ = top_ref) and
  12005. { TODO: Can we detect which references become constants at this
  12006. stage so we don't have to do a blanket ban? }
  12007. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  12008. (
  12009. IsRefSafe(taicpu(p).oper[0]^.ref) or
  12010. (
  12011. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  12012. not RefModified and
  12013. { If the reference also appears in the condition, then we know it's safe, otherwise
  12014. any kind of access violation would have occurred already }
  12015. Assigned(cond_p) and
  12016. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12017. (cond_p.typ = ait_instruction) and
  12018. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  12019. { Just consider 2-operand comparison instructions for now to be safe }
  12020. (taicpu(cond_p).ops = 2) and
  12021. (
  12022. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  12023. (
  12024. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  12025. { Don't risk identical registers but different offsets, as we may have constructs
  12026. such as buffer streams with things like length fields that indicate whether
  12027. any more data follows. And there are probably some contrived examples where
  12028. writing to offsets behind the one being read also lead to access violations }
  12029. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  12030. (
  12031. { Check that we're not modifying a register that appears in the reference }
  12032. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  12033. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  12034. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  12035. )
  12036. )
  12037. )
  12038. )
  12039. )
  12040. )
  12041. );
  12042. end;
  12043. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  12044. begin
  12045. { Update integer registers, ignoring deallocations }
  12046. repeat
  12047. while assigned(p) and
  12048. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  12049. (p.typ = ait_label) or
  12050. ((p.typ = ait_marker) and
  12051. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  12052. p := tai(p.next);
  12053. while assigned(p) and
  12054. (p.typ=ait_RegAlloc) Do
  12055. begin
  12056. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  12057. begin
  12058. case tai_regalloc(p).ratype of
  12059. ra_alloc :
  12060. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  12061. else
  12062. ;
  12063. end;
  12064. end;
  12065. p := tai(p.next);
  12066. end;
  12067. until not(assigned(p)) or
  12068. (not(p.typ in SkipInstr) and
  12069. not((p.typ = ait_label) and
  12070. labelCanBeSkipped(tai_label(p))));
  12071. end;
  12072. {$ifndef 8086}
  12073. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  12074. begin
  12075. Result := False;
  12076. EndJump := nil;
  12077. BlockStop := nil;
  12078. while (BlockStart <> fOptimizer.BlockEnd) and
  12079. { stop on labels }
  12080. (BlockStart.typ <> ait_label) do
  12081. begin
  12082. { Keep track of all integer registers that are used }
  12083. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  12084. if BlockStart.typ = ait_instruction then
  12085. begin
  12086. if (taicpu(BlockStart).opcode = A_JMP) then
  12087. begin
  12088. if not IsJumpToLabel(taicpu(BlockStart)) or
  12089. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  12090. Exit;
  12091. EndJump := BlockStart;
  12092. Break;
  12093. end
  12094. { Check to see if we have a valid MOV instruction instead }
  12095. else if (taicpu(BlockStart).opcode <> A_MOV) or
  12096. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  12097. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12098. begin
  12099. Exit;
  12100. end
  12101. else
  12102. { This will be a valid MOV }
  12103. fAllocationRange := BlockStart;
  12104. end;
  12105. OneBeforeBlock := BlockStart;
  12106. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12107. end;
  12108. if (BlockStart = fOptimizer.BlockEnd) then
  12109. Exit;
  12110. BlockStop := BlockStart;
  12111. Result := True;
  12112. end;
  12113. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12114. var
  12115. hp1: tai;
  12116. RefModified: Boolean;
  12117. begin
  12118. Result := 0;
  12119. hp1 := BlockStart;
  12120. RefModified := False; { As long as the condition is inverted, this can be reset }
  12121. while assigned(hp1) and
  12122. (hp1 <> BlockStop) do
  12123. begin
  12124. case hp1.typ of
  12125. ait_instruction:
  12126. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12127. begin
  12128. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12129. begin
  12130. Inc(Result);
  12131. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12132. Assigned(fCondition) and
  12133. { Will have 2 operands }
  12134. (
  12135. (
  12136. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12137. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12138. ) or
  12139. (
  12140. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12141. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12142. )
  12143. ) then
  12144. { It is no longer safe to use the reference in the condition.
  12145. this prevents problems such as:
  12146. mov (%reg),%reg
  12147. mov (%reg),...
  12148. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12149. (fixes #40165)
  12150. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12151. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12152. }
  12153. RefModified := True;
  12154. end
  12155. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12156. { CMOV with constants grows the code size }
  12157. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12158. begin
  12159. { Register was reserved by TryCMOVConst and
  12160. stored on ConstRegs }
  12161. end
  12162. else
  12163. begin
  12164. Result := -1;
  12165. Exit;
  12166. end;
  12167. end
  12168. else
  12169. begin
  12170. Result := -1;
  12171. Exit;
  12172. end;
  12173. else
  12174. { Most likely an align };
  12175. end;
  12176. fOptimizer.GetNextInstruction(hp1, hp1);
  12177. end;
  12178. end;
  12179. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12180. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12181. (this is done as a separate stage because the double types are extensions of the branching type,
  12182. but we can't discount the conditional jump until the last step) }
  12183. procedure EvaluateBranchingType;
  12184. begin
  12185. Inc(CMOVScore);
  12186. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12187. { Too many instructions to be worthwhile }
  12188. fState := tsInvalid;
  12189. end;
  12190. var
  12191. hp1: tai;
  12192. Count: Integer;
  12193. begin
  12194. { Table of valid CMOV block types
  12195. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12196. ---------- --------- --------- --------- --------- ---------
  12197. tsSimple X Yes X X X
  12198. tsDetour = 1st X X X X
  12199. tsBranching <> Mid Yes X X X
  12200. tsDouble End-label Yes * Yes X Yes
  12201. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12202. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12203. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12204. * Only one reference allowed
  12205. }
  12206. hp1 := nil; { To prevent compiler warnings }
  12207. Optimizer.CopyUsedRegs(RegisterTracking);
  12208. fOptimizer := Optimizer;
  12209. fLabel := AFirstLabel;
  12210. CMOVScore := 0;
  12211. ConstCount := 0;
  12212. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12213. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12214. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12215. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12216. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12217. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12218. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12219. fInsertionPoint := p_initialjump;
  12220. fCondition := nil;
  12221. fInitialJump := p_initialjump;
  12222. fFirstMovBlock := p_initialmov;
  12223. fFirstMovBlockStop := nil;
  12224. fSecondJump := nil;
  12225. fSecondMovBlock := nil;
  12226. fSecondMovBlockStop := nil;
  12227. fMidLabel := nil;
  12228. fSecondJump := nil;
  12229. fSecondMovBlock := nil;
  12230. fEndLabel := nil;
  12231. fAllocationRange := nil;
  12232. { Assume it all goes horribly wrong! }
  12233. fState := tsInvalid;
  12234. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12235. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12236. 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
  12237. begin
  12238. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12239. for Count := 0 to 1 do
  12240. with taicpu(fCondition).oper[Count]^ do
  12241. case typ of
  12242. top_reg:
  12243. if getregtype(reg) = R_INTREGISTER then
  12244. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12245. top_ref:
  12246. begin
  12247. if
  12248. {$ifdef x86_64}
  12249. (ref^.base <> NR_RIP) and
  12250. {$endif x86_64}
  12251. (ref^.base <> NR_NO) then
  12252. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12253. if (ref^.index <> NR_NO) then
  12254. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12255. end
  12256. else
  12257. ;
  12258. end;
  12259. { When inserting instructions before hp_prev, try to insert them
  12260. before the allocation of the FLAGS register }
  12261. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12262. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12263. { If not found, set it equal to the condition so it's something sensible }
  12264. fInsertionPoint := fCondition;
  12265. { When dealing with a comparison against zero, take note of the
  12266. instruction before it to see if we can move instructions further
  12267. back in order to benefit PostPeepholeOptTestOr.
  12268. }
  12269. if (
  12270. (
  12271. (taicpu(fCondition).opcode = A_CMP) and
  12272. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12273. ) or
  12274. (
  12275. (taicpu(fCondition).opcode = A_TEST) and
  12276. (
  12277. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12278. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12279. )
  12280. )
  12281. ) and
  12282. Optimizer.GetLastInstruction(fCondition, hp1) then
  12283. begin
  12284. { These instructions set the zero flag if the result is zero }
  12285. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12286. begin
  12287. fInsertionPoint := hp1;
  12288. { Also mark all the registers in this previous instruction
  12289. as 'in use', even if they've just been deallocated }
  12290. for Count := 0 to 1 do
  12291. with taicpu(hp1).oper[Count]^ do
  12292. case typ of
  12293. top_reg:
  12294. if getregtype(reg) = R_INTREGISTER then
  12295. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12296. top_ref:
  12297. begin
  12298. if
  12299. {$ifdef x86_64}
  12300. (ref^.base <> NR_RIP) and
  12301. {$endif x86_64}
  12302. (ref^.base <> NR_NO) then
  12303. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12304. if (ref^.index <> NR_NO) then
  12305. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12306. end
  12307. else
  12308. ;
  12309. end;
  12310. end;
  12311. end;
  12312. end
  12313. else
  12314. fCondition := nil;
  12315. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12316. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12317. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12318. { If not found, set it equal to p so it's something sensible }
  12319. fInsertionPoint := hp1;
  12320. hp1 := p_initialmov;
  12321. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12322. Exit;
  12323. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12324. if (hp1.typ <> ait_label) then { should be on a jump }
  12325. begin
  12326. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12327. { Need a label afterwards }
  12328. Exit;
  12329. end
  12330. else
  12331. fMidLabel := hp1;
  12332. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12333. { Not the correct label }
  12334. fMidLabel := nil;
  12335. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12336. { If there's neither a 2nd jump nor correct label, then it's invalid
  12337. (see above table) }
  12338. Exit;
  12339. { Analyse the first block of MOVs more closely }
  12340. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12341. if Assigned(fSecondJump) then
  12342. begin
  12343. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12344. begin
  12345. fState := tsDetour
  12346. end
  12347. else
  12348. begin
  12349. { Need the correct mid-label for this one }
  12350. if not Assigned(fMidLabel) then
  12351. Exit;
  12352. fState := tsBranching;
  12353. end;
  12354. end
  12355. else
  12356. { No jump. but mid-label is present }
  12357. fState := tsSimple;
  12358. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12359. begin
  12360. { Invalid or too many instructions to be worthwhile }
  12361. fState := tsInvalid;
  12362. Exit;
  12363. end;
  12364. { check further for
  12365. jCC xxx
  12366. <several movs 1>
  12367. jmp yyy
  12368. xxx:
  12369. <several movs 2>
  12370. yyy:
  12371. etc.
  12372. }
  12373. if (fState = tsBranching) and
  12374. { Estimate for required savings for extra jump }
  12375. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12376. { Only one reference is allowed for double blocks }
  12377. (AFirstLabel.getrefs = 1) then
  12378. begin
  12379. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12380. fSecondMovBlock := hp1;
  12381. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12382. begin
  12383. EvaluateBranchingType;
  12384. Exit;
  12385. end;
  12386. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12387. if (hp1.typ <> ait_label) then { should be on a jump }
  12388. begin
  12389. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12390. begin
  12391. { Need a label afterwards }
  12392. EvaluateBranchingType;
  12393. Exit;
  12394. end;
  12395. end
  12396. else
  12397. fEndLabel := hp1;
  12398. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12399. { Second jump doesn't go to the end }
  12400. fEndLabel := nil;
  12401. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12402. begin
  12403. { If there's neither a 3rd jump nor correct end label, then it's
  12404. not a invalid double block, but is a valid single branching
  12405. block (see above table) }
  12406. EvaluateBranchingType;
  12407. Exit;
  12408. end;
  12409. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12410. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12411. { Invalid or too many instructions to be worthwhile }
  12412. Exit;
  12413. Inc(CMOVScore, Count);
  12414. if Assigned(fThirdJump) then
  12415. begin
  12416. if not Assigned(fSecondJump) then
  12417. fState := tsDoubleSecondBranching
  12418. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12419. fState := tsDoubleBranchSame
  12420. else
  12421. fState := tsDoubleBranchDifferent;
  12422. end
  12423. else
  12424. fState := tsDouble;
  12425. end;
  12426. if fState = tsBranching then
  12427. EvaluateBranchingType;
  12428. end;
  12429. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12430. new register to store the constant }
  12431. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12432. var
  12433. RegSize: TSubRegister;
  12434. CurrentVal: TCGInt;
  12435. ANewReg: TRegister;
  12436. X: ShortInt;
  12437. begin
  12438. Result := False;
  12439. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12440. Exit;
  12441. if ConstCount >= MAX_CMOV_REGISTERS then
  12442. { Arrays are full }
  12443. Exit;
  12444. { Remember that CMOV can't encode 8-bit registers }
  12445. case taicpu(p).opsize of
  12446. S_W:
  12447. RegSize := R_SUBW;
  12448. S_L:
  12449. RegSize := R_SUBD;
  12450. {$ifdef x86_64}
  12451. S_Q:
  12452. RegSize := R_SUBQ;
  12453. {$endif x86_64}
  12454. else
  12455. InternalError(2021100401);
  12456. end;
  12457. { See if the value has already been reserved for another CMOV instruction }
  12458. CurrentVal := taicpu(p).oper[0]^.val;
  12459. for X := 0 to ConstCount - 1 do
  12460. if ConstVals[X] = CurrentVal then
  12461. begin
  12462. ConstRegs[ConstCount] := ConstRegs[X];
  12463. ConstSizes[ConstCount] := RegSize;
  12464. ConstVals[ConstCount] := CurrentVal;
  12465. Inc(ConstCount);
  12466. Inc(Count);
  12467. Result := True;
  12468. Exit;
  12469. end;
  12470. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12471. if ANewReg = NR_NO then
  12472. { No free registers }
  12473. Exit;
  12474. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12475. up vying for the same register }
  12476. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12477. ConstRegs[ConstCount] := ANewReg;
  12478. ConstSizes[ConstCount] := RegSize;
  12479. ConstVals[ConstCount] := CurrentVal;
  12480. Inc(ConstCount);
  12481. Inc(Count);
  12482. Result := True;
  12483. end;
  12484. destructor TCMOVTracking.Done;
  12485. begin
  12486. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12487. end;
  12488. procedure TCMOVTracking.Process(out new_p: tai);
  12489. var
  12490. Count, Writes: LongInt;
  12491. RegMatch: Boolean;
  12492. hp1, hp_new: tai;
  12493. inverted_condition, condition: TAsmCond;
  12494. begin
  12495. if (fState in [tsInvalid, tsProcessed]) then
  12496. InternalError(2023110701);
  12497. { Repurpose RegisterTracking to mark registers that we've defined }
  12498. RegisterTracking[R_INTREGISTER].Clear;
  12499. Count := 0;
  12500. Writes := 0;
  12501. condition := taicpu(fInitialJump).condition;
  12502. inverted_condition := inverse_cond(condition);
  12503. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12504. doesn't get CMOVs in this case }
  12505. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12506. begin
  12507. { Include the jump in the flag tracking }
  12508. if Assigned(fThirdJump) then
  12509. begin
  12510. if (fState = tsDoubleBranchSame) then
  12511. begin
  12512. { Will be an unconditional jump, so track to the instruction before it }
  12513. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12514. InternalError(2023110710);
  12515. end
  12516. else
  12517. hp1 := fThirdJump;
  12518. end
  12519. else
  12520. hp1 := fSecondMovBlockStop;
  12521. end
  12522. else
  12523. begin
  12524. { Include a conditional jump in the flag tracking }
  12525. if Assigned(fSecondJump) then
  12526. begin
  12527. if (fState = tsDetour) then
  12528. begin
  12529. { Will be an unconditional jump, so track to the instruction before it }
  12530. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12531. InternalError(2023110711);
  12532. end
  12533. else
  12534. hp1 := fSecondJump;
  12535. end
  12536. else
  12537. hp1 := fFirstMovBlockStop;
  12538. end;
  12539. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12540. { Process the second set of MOVs first, because if a destination
  12541. register is shared between the first and second MOV sets, it is more
  12542. efficient to turn the first one into a MOV instruction and place it
  12543. before the CMP if possible, but we won't know which registers are
  12544. shared until we've processed at least one list, so we might as well
  12545. make it the second one since that won't be modified again. }
  12546. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12547. begin
  12548. hp1 := fSecondMovBlock;
  12549. repeat
  12550. if not Assigned(hp1) then
  12551. InternalError(2018062902);
  12552. if (hp1.typ = ait_instruction) then
  12553. begin
  12554. { Extra safeguard }
  12555. if (taicpu(hp1).opcode <> A_MOV) then
  12556. InternalError(2018062903);
  12557. { Note: tsDoubleBranchDifferent is essentially identical to
  12558. tsBranching and the 2nd block is best left largely
  12559. untouched, but we need to evaluate which registers the MOVs
  12560. write to in order to track what would be complementary CMOV
  12561. pairs that can be further optimised. [Kit] }
  12562. if fState <> tsDoubleBranchDifferent then
  12563. begin
  12564. if taicpu(hp1).oper[0]^.typ = top_const then
  12565. begin
  12566. RegMatch := False;
  12567. for Count := 0 to ConstCount - 1 do
  12568. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12569. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12570. begin
  12571. RegMatch := True;
  12572. { If it's in RegisterTracking, then this register
  12573. is being used more than once and hence has
  12574. already had its value defined (it gets added to
  12575. UsedRegs through AllocRegBetween below) }
  12576. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12577. begin
  12578. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12579. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12580. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12581. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12582. ConstMovs[Count] := hp_new;
  12583. end
  12584. else
  12585. { We just need an instruction between hp_prev and hp1
  12586. where we know the register is marked as in use }
  12587. hp_new := fSecondMovBlock;
  12588. { Keep track of largest write for this register so it can be optimised later }
  12589. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12590. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12591. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12592. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12593. Break;
  12594. end;
  12595. if not RegMatch then
  12596. InternalError(2021100411);
  12597. end;
  12598. taicpu(hp1).opcode := A_CMOVcc;
  12599. taicpu(hp1).condition := condition;
  12600. end;
  12601. { Store these writes to search for duplicates later on }
  12602. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12603. Inc(Writes);
  12604. end;
  12605. fOptimizer.GetNextInstruction(hp1, hp1);
  12606. until (hp1 = fSecondMovBlockStop);
  12607. end;
  12608. { Now do the first set of MOVs }
  12609. hp1 := fFirstMovBlock;
  12610. repeat
  12611. if not Assigned(hp1) then
  12612. InternalError(2018062904);
  12613. if (hp1.typ = ait_instruction) then
  12614. begin
  12615. RegMatch := False;
  12616. { Extra safeguard }
  12617. if (taicpu(hp1).opcode <> A_MOV) then
  12618. InternalError(2018062905);
  12619. { Search through the RegWrites list to see if there are any
  12620. opposing CMOV pairs that write to the same register }
  12621. for Count := 0 to Writes - 1 do
  12622. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12623. begin
  12624. { We have a match. Keep this as a MOV }
  12625. { Move ahead in preparation }
  12626. fOptimizer.GetNextInstruction(hp1, hp1);
  12627. RegMatch := True;
  12628. Break;
  12629. end;
  12630. if RegMatch then
  12631. Continue;
  12632. if taicpu(hp1).oper[0]^.typ = top_const then
  12633. begin
  12634. for Count := 0 to ConstCount - 1 do
  12635. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12636. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12637. begin
  12638. RegMatch := True;
  12639. { If it's in RegisterTracking, then this register is
  12640. being used more than once and hence has already had
  12641. its value defined (it gets added to UsedRegs through
  12642. AllocRegBetween below) }
  12643. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12644. begin
  12645. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12646. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12647. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12648. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12649. ConstMovs[Count] := hp_new;
  12650. end
  12651. else
  12652. { We just need an instruction between hp_prev and hp1
  12653. where we know the register is marked as in use }
  12654. hp_new := fFirstMovBlock;
  12655. { Keep track of largest write for this register so it can be optimised later }
  12656. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12657. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12658. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12659. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12660. Break;
  12661. end;
  12662. if not RegMatch then
  12663. InternalError(2021100412);
  12664. end;
  12665. taicpu(hp1).opcode := A_CMOVcc;
  12666. taicpu(hp1).condition := inverted_condition;
  12667. if (fState = tsDoubleBranchDifferent) then
  12668. begin
  12669. { Store these writes to search for duplicates later on }
  12670. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12671. Inc(Writes);
  12672. end;
  12673. end;
  12674. fOptimizer.GetNextInstruction(hp1, hp1);
  12675. until (hp1 = fFirstMovBlockStop);
  12676. { Update initialisation MOVs to the smallest possible size }
  12677. for Count := 0 to ConstCount - 1 do
  12678. if Assigned(ConstMovs[Count]) then
  12679. begin
  12680. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12681. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12682. end;
  12683. case fState of
  12684. tsSimple:
  12685. begin
  12686. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12687. { No branch to delete }
  12688. end;
  12689. tsDetour:
  12690. begin
  12691. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12692. { Preserve jump }
  12693. end;
  12694. tsBranching, tsDoubleBranchDifferent:
  12695. begin
  12696. if (fState = tsBranching) then
  12697. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12698. else
  12699. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12700. taicpu(fSecondJump).opcode := A_JCC;
  12701. taicpu(fSecondJump).condition := inverted_condition;
  12702. end;
  12703. tsDouble, tsDoubleBranchSame:
  12704. begin
  12705. if (fState = tsDouble) then
  12706. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12707. else
  12708. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12709. { Delete second jump }
  12710. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12711. fOptimizer.RemoveInstruction(fSecondJump);
  12712. end;
  12713. tsDoubleSecondBranching:
  12714. begin
  12715. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12716. { Delete second jump, preserve third jump as conditional }
  12717. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12718. fOptimizer.RemoveInstruction(fSecondJump);
  12719. taicpu(fThirdJump).opcode := A_JCC;
  12720. taicpu(fThirdJump).condition := condition;
  12721. end;
  12722. else
  12723. InternalError(2023110720);
  12724. end;
  12725. { Now we can safely decrement the reference count }
  12726. tasmlabel(fLabel).decrefs;
  12727. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12728. { Remove the original jump }
  12729. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12730. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12731. fState := tsProcessed;
  12732. end;
  12733. {$endif 8086}
  12734. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12735. var
  12736. hp1,hp2: tai;
  12737. carryadd_opcode : TAsmOp;
  12738. symbol: TAsmSymbol;
  12739. increg, tmpreg: TRegister;
  12740. {$ifndef i8086}
  12741. CMOVTracking: PCMOVTracking;
  12742. hp3,hp4,hp5: tai;
  12743. {$endif i8086}
  12744. TempBool: Boolean;
  12745. begin
  12746. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12747. DoJumpOptimizations(p, TempBool) then
  12748. Exit(True);
  12749. result:=false;
  12750. if GetNextInstruction(p,hp1) then
  12751. begin
  12752. if (hp1.typ=ait_label) then
  12753. begin
  12754. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12755. Exit;
  12756. end
  12757. else if (hp1.typ<>ait_instruction) then
  12758. Exit;
  12759. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12760. if (
  12761. (
  12762. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12763. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12764. (Taicpu(hp1).oper[0]^.val=1)
  12765. ) or
  12766. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12767. ) and
  12768. GetNextInstruction(hp1,hp2) and
  12769. FindLabel(TAsmLabel(symbol), hp2) then
  12770. { jb @@1 cmc
  12771. inc/dec operand --> adc/sbb operand,0
  12772. @@1:
  12773. ... and ...
  12774. jnb @@1
  12775. inc/dec operand --> adc/sbb operand,0
  12776. @@1: }
  12777. begin
  12778. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12779. begin
  12780. case taicpu(hp1).opcode of
  12781. A_INC,
  12782. A_ADD:
  12783. carryadd_opcode:=A_ADC;
  12784. A_DEC,
  12785. A_SUB:
  12786. carryadd_opcode:=A_SBB;
  12787. else
  12788. InternalError(2021011001);
  12789. end;
  12790. Taicpu(p).clearop(0);
  12791. Taicpu(p).ops:=0;
  12792. Taicpu(p).is_jmp:=false;
  12793. Taicpu(p).opcode:=A_CMC;
  12794. Taicpu(p).condition:=C_NONE;
  12795. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12796. Taicpu(hp1).ops:=2;
  12797. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12798. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12799. else
  12800. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12801. Taicpu(hp1).loadconst(0,0);
  12802. Taicpu(hp1).opcode:=carryadd_opcode;
  12803. result:=true;
  12804. exit;
  12805. end
  12806. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12807. begin
  12808. case taicpu(hp1).opcode of
  12809. A_INC,
  12810. A_ADD:
  12811. carryadd_opcode:=A_ADC;
  12812. A_DEC,
  12813. A_SUB:
  12814. carryadd_opcode:=A_SBB;
  12815. else
  12816. InternalError(2021011002);
  12817. end;
  12818. Taicpu(hp1).ops:=2;
  12819. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12820. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12821. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12822. else
  12823. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12824. Taicpu(hp1).loadconst(0,0);
  12825. Taicpu(hp1).opcode:=carryadd_opcode;
  12826. RemoveCurrentP(p, hp1);
  12827. result:=true;
  12828. exit;
  12829. end
  12830. {
  12831. jcc @@1 setcc tmpreg
  12832. inc/dec/add/sub operand -> (movzx tmpreg)
  12833. @@1: add/sub tmpreg,operand
  12834. While this increases code size slightly, it makes the code much faster if the
  12835. jump is unpredictable
  12836. }
  12837. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12838. begin
  12839. { search for an available register which is volatile }
  12840. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12841. if increg <> NR_NO then
  12842. begin
  12843. { We don't need to check if tmpreg is in hp1 or not, because
  12844. it will be marked as in use at p (if not, this is
  12845. indictive of a compiler bug). }
  12846. TAsmLabel(symbol).decrefs;
  12847. Taicpu(p).clearop(0);
  12848. Taicpu(p).ops:=1;
  12849. Taicpu(p).is_jmp:=false;
  12850. Taicpu(p).opcode:=A_SETcc;
  12851. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12852. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12853. Taicpu(p).loadreg(0,increg);
  12854. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12855. begin
  12856. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12857. R_SUBW:
  12858. begin
  12859. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12860. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12861. end;
  12862. R_SUBD:
  12863. begin
  12864. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12865. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12866. end;
  12867. {$ifdef x86_64}
  12868. R_SUBQ:
  12869. begin
  12870. { MOVZX doesn't have a 64-bit variant, because
  12871. the 32-bit version implicitly zeroes the
  12872. upper 32-bits of the destination register }
  12873. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12874. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12875. setsubreg(tmpreg, R_SUBQ);
  12876. end;
  12877. {$endif x86_64}
  12878. else
  12879. Internalerror(2020030601);
  12880. end;
  12881. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12882. asml.InsertAfter(hp2,p);
  12883. end
  12884. else
  12885. tmpreg := increg;
  12886. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12887. begin
  12888. Taicpu(hp1).ops:=2;
  12889. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12890. end;
  12891. Taicpu(hp1).loadreg(0,tmpreg);
  12892. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12893. Result := True;
  12894. { p is no longer a Jcc instruction, so exit }
  12895. Exit;
  12896. end;
  12897. end;
  12898. end;
  12899. { Detect the following:
  12900. jmp<cond> @Lbl1
  12901. jmp @Lbl2
  12902. ...
  12903. @Lbl1:
  12904. ret
  12905. Change to:
  12906. jmp<inv_cond> @Lbl2
  12907. ret
  12908. }
  12909. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12910. begin
  12911. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12912. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12913. MatchInstruction(hp2,A_RET,[S_NO]) then
  12914. begin
  12915. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12916. { Change label address to that of the unconditional jump }
  12917. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12918. TAsmLabel(symbol).DecRefs;
  12919. taicpu(hp1).opcode := A_RET;
  12920. taicpu(hp1).is_jmp := false;
  12921. taicpu(hp1).ops := taicpu(hp2).ops;
  12922. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12923. case taicpu(hp2).ops of
  12924. 0:
  12925. taicpu(hp1).clearop(0);
  12926. 1:
  12927. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12928. else
  12929. internalerror(2016041302);
  12930. end;
  12931. end;
  12932. {$ifndef i8086}
  12933. end
  12934. {
  12935. convert
  12936. j<c> .L1
  12937. mov 1,reg
  12938. jmp .L2
  12939. .L1
  12940. mov 0,reg
  12941. .L2
  12942. into
  12943. mov 0,reg
  12944. set<not(c)> reg
  12945. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12946. would destroy the flag contents
  12947. }
  12948. else if MatchInstruction(hp1,A_MOV,[]) and
  12949. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12950. {$ifdef i386}
  12951. (
  12952. { Under i386, ESI, EDI, EBP and ESP
  12953. don't have an 8-bit representation }
  12954. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12955. ) and
  12956. {$endif i386}
  12957. (taicpu(hp1).oper[0]^.val=1) and
  12958. GetNextInstruction(hp1,hp2) and
  12959. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12960. GetNextInstruction(hp2,hp3) and
  12961. (hp3.typ=ait_label) and
  12962. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12963. (tai_label(hp3).labsym.getrefs=1) and
  12964. GetNextInstruction(hp3,hp4) and
  12965. MatchInstruction(hp4,A_MOV,[]) and
  12966. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12967. (taicpu(hp4).oper[0]^.val=0) and
  12968. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12969. GetNextInstruction(hp4,hp5) and
  12970. (hp5.typ=ait_label) and
  12971. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12972. (tai_label(hp5).labsym.getrefs=1) then
  12973. begin
  12974. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12975. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12976. { remove last label }
  12977. RemoveInstruction(hp5);
  12978. { remove second label }
  12979. RemoveInstruction(hp3);
  12980. { remove jmp }
  12981. RemoveInstruction(hp2);
  12982. if taicpu(hp1).opsize=S_B then
  12983. RemoveInstruction(hp1)
  12984. else
  12985. taicpu(hp1).loadconst(0,0);
  12986. taicpu(hp4).opcode:=A_SETcc;
  12987. taicpu(hp4).opsize:=S_B;
  12988. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12989. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12990. taicpu(hp4).opercnt:=1;
  12991. taicpu(hp4).ops:=1;
  12992. taicpu(hp4).freeop(1);
  12993. RemoveCurrentP(p);
  12994. Result:=true;
  12995. exit;
  12996. end
  12997. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12998. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12999. begin
  13000. { check for
  13001. jCC xxx
  13002. <several movs>
  13003. xxx:
  13004. Also spot:
  13005. Jcc xxx
  13006. <several movs>
  13007. jmp xxx
  13008. Change to:
  13009. <several cmovs with inverted condition>
  13010. jmp xxx (only for the 2nd case)
  13011. }
  13012. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  13013. if CMOVTracking^.State <> tsInvalid then
  13014. begin
  13015. CMovTracking^.Process(p);
  13016. Result := True;
  13017. end;
  13018. CMOVTracking^.Done;
  13019. {$endif i8086}
  13020. end;
  13021. end;
  13022. end;
  13023. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  13024. var
  13025. hp1,hp2,hp3: tai;
  13026. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  13027. NewSize: TOpSize;
  13028. NewRegSize: TSubRegister;
  13029. Limit: TCgInt;
  13030. SwapOper: POper;
  13031. begin
  13032. result:=false;
  13033. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  13034. GetNextInstruction(p,hp1) and
  13035. (hp1.typ = ait_instruction);
  13036. if reg_and_hp1_is_instr and
  13037. (
  13038. (taicpu(hp1).opcode <> A_LEA) or
  13039. { If the LEA instruction can be converted into an arithmetic instruction,
  13040. it may be possible to then fold it. }
  13041. (
  13042. { If the flags register is in use, don't change the instruction
  13043. to an ADD otherwise this will scramble the flags. [Kit] }
  13044. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13045. ConvertLEA(taicpu(hp1))
  13046. )
  13047. ) and
  13048. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  13049. GetNextInstruction(hp1,hp2) and
  13050. MatchInstruction(hp2,A_MOV,[]) and
  13051. (taicpu(hp2).oper[0]^.typ = top_reg) and
  13052. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  13053. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  13054. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  13055. {$ifdef i386}
  13056. { not all registers have byte size sub registers on i386 }
  13057. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  13058. {$endif i386}
  13059. (((taicpu(hp1).ops=2) and
  13060. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  13061. ((taicpu(hp1).ops=1) and
  13062. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  13063. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  13064. begin
  13065. { change movsX/movzX reg/ref, reg2
  13066. add/sub/or/... reg3/$const, reg2
  13067. mov reg2 reg/ref
  13068. to add/sub/or/... reg3/$const, reg/ref }
  13069. { by example:
  13070. movswl %si,%eax movswl %si,%eax p
  13071. decl %eax addl %edx,%eax hp1
  13072. movw %ax,%si movw %ax,%si hp2
  13073. ->
  13074. movswl %si,%eax movswl %si,%eax p
  13075. decw %eax addw %edx,%eax hp1
  13076. movw %ax,%si movw %ax,%si hp2
  13077. }
  13078. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  13079. {
  13080. ->
  13081. movswl %si,%eax movswl %si,%eax p
  13082. decw %si addw %dx,%si hp1
  13083. movw %ax,%si movw %ax,%si hp2
  13084. }
  13085. case taicpu(hp1).ops of
  13086. 1:
  13087. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  13088. 2:
  13089. begin
  13090. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  13091. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  13092. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  13093. end;
  13094. else
  13095. internalerror(2008042702);
  13096. end;
  13097. {
  13098. ->
  13099. decw %si addw %dx,%si p
  13100. }
  13101. DebugMsg(SPeepholeOptimization + 'var3',p);
  13102. RemoveCurrentP(p, hp1);
  13103. RemoveInstruction(hp2);
  13104. Result := True;
  13105. Exit;
  13106. end;
  13107. if reg_and_hp1_is_instr and
  13108. (taicpu(hp1).opcode = A_MOV) and
  13109. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13110. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13111. {$ifdef x86_64}
  13112. { check for implicit extension to 64 bit }
  13113. or
  13114. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13115. (taicpu(hp1).opsize=S_Q) and
  13116. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13117. )
  13118. {$endif x86_64}
  13119. )
  13120. then
  13121. begin
  13122. { change
  13123. movx %reg1,%reg2
  13124. mov %reg2,%reg3
  13125. dealloc %reg2
  13126. into
  13127. movx %reg,%reg3
  13128. }
  13129. TransferUsedRegs(TmpUsedRegs);
  13130. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13131. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13132. begin
  13133. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13134. {$ifdef x86_64}
  13135. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13136. (taicpu(hp1).opsize=S_Q) then
  13137. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13138. else
  13139. {$endif x86_64}
  13140. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13141. RemoveInstruction(hp1);
  13142. Result := True;
  13143. Exit;
  13144. end;
  13145. end;
  13146. if reg_and_hp1_is_instr and
  13147. ((taicpu(hp1).opcode=A_MOV) or
  13148. (taicpu(hp1).opcode=A_ADD) or
  13149. (taicpu(hp1).opcode=A_SUB) or
  13150. (taicpu(hp1).opcode=A_CMP) or
  13151. (taicpu(hp1).opcode=A_OR) or
  13152. (taicpu(hp1).opcode=A_XOR) or
  13153. (taicpu(hp1).opcode=A_AND)
  13154. ) and
  13155. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13156. begin
  13157. AndTest := (taicpu(hp1).opcode=A_AND) and
  13158. GetNextInstruction(hp1, hp2) and
  13159. (hp2.typ = ait_instruction) and
  13160. (
  13161. (
  13162. (taicpu(hp2).opcode=A_TEST) and
  13163. (
  13164. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13165. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13166. (
  13167. { If the AND and TEST instructions share a constant, this is also valid }
  13168. (taicpu(hp1).oper[0]^.typ = top_const) and
  13169. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13170. )
  13171. ) and
  13172. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13173. ) or
  13174. (
  13175. (taicpu(hp2).opcode=A_CMP) and
  13176. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13177. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13178. )
  13179. );
  13180. { change
  13181. movx (oper),%reg2
  13182. and $x,%reg2
  13183. test %reg2,%reg2
  13184. dealloc %reg2
  13185. into
  13186. op %reg1,%reg3
  13187. if the second op accesses only the bits stored in reg1
  13188. }
  13189. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13190. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13191. (taicpu(hp1).oper[0]^.typ = top_const) and
  13192. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13193. AndTest then
  13194. begin
  13195. { Check if the AND constant is in range }
  13196. case taicpu(p).opsize of
  13197. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13198. begin
  13199. NewSize := S_B;
  13200. Limit := $FF;
  13201. end;
  13202. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13203. begin
  13204. NewSize := S_W;
  13205. Limit := $FFFF;
  13206. end;
  13207. {$ifdef x86_64}
  13208. S_LQ:
  13209. begin
  13210. NewSize := S_L;
  13211. Limit := $FFFFFFFF;
  13212. end;
  13213. {$endif x86_64}
  13214. else
  13215. InternalError(2021120303);
  13216. end;
  13217. if (
  13218. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13219. { Check for negative operands }
  13220. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13221. ) and
  13222. GetNextInstruction(hp2,hp3) and
  13223. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13224. (taicpu(hp3).condition in [C_E,C_NE]) then
  13225. begin
  13226. TransferUsedRegs(TmpUsedRegs);
  13227. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13228. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13229. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13230. begin
  13231. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13232. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13233. taicpu(hp1).opcode := A_TEST;
  13234. taicpu(hp1).opsize := NewSize;
  13235. RemoveInstruction(hp2);
  13236. RemoveCurrentP(p, hp1);
  13237. Result:=true;
  13238. exit;
  13239. end;
  13240. end;
  13241. end;
  13242. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13243. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13244. (taicpu(hp1).opsize=S_B)) or
  13245. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13246. (taicpu(hp1).opsize=S_W))
  13247. {$ifdef x86_64}
  13248. or ((taicpu(p).opsize=S_LQ) and
  13249. (taicpu(hp1).opsize=S_L))
  13250. {$endif x86_64}
  13251. ) and
  13252. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13253. begin
  13254. { change
  13255. movx %reg1,%reg2
  13256. op %reg2,%reg3
  13257. dealloc %reg2
  13258. into
  13259. op %reg1,%reg3
  13260. if the second op accesses only the bits stored in reg1
  13261. }
  13262. TransferUsedRegs(TmpUsedRegs);
  13263. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13264. if AndTest then
  13265. begin
  13266. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13267. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13268. end
  13269. else
  13270. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13271. if not RegUsed then
  13272. begin
  13273. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13274. if taicpu(p).oper[0]^.typ=top_reg then
  13275. begin
  13276. case taicpu(hp1).opsize of
  13277. S_B:
  13278. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13279. S_W:
  13280. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13281. S_L:
  13282. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13283. else
  13284. Internalerror(2020102301);
  13285. end;
  13286. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13287. end
  13288. else
  13289. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13290. RemoveCurrentP(p);
  13291. if AndTest then
  13292. RemoveInstruction(hp2);
  13293. result:=true;
  13294. exit;
  13295. end;
  13296. end
  13297. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13298. (
  13299. { Bitwise operations only }
  13300. (taicpu(hp1).opcode=A_AND) or
  13301. (taicpu(hp1).opcode=A_TEST) or
  13302. (
  13303. (taicpu(hp1).oper[0]^.typ = top_const) and
  13304. (
  13305. (taicpu(hp1).opcode=A_OR) or
  13306. (taicpu(hp1).opcode=A_XOR)
  13307. )
  13308. )
  13309. ) and
  13310. (
  13311. (taicpu(hp1).oper[0]^.typ = top_const) or
  13312. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13313. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13314. ) then
  13315. begin
  13316. { change
  13317. movx %reg2,%reg2
  13318. op const,%reg2
  13319. into
  13320. op const,%reg2 (smaller version)
  13321. movx %reg2,%reg2
  13322. also change
  13323. movx %reg1,%reg2
  13324. and/test (oper),%reg2
  13325. dealloc %reg2
  13326. into
  13327. and/test (oper),%reg1
  13328. }
  13329. case taicpu(p).opsize of
  13330. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13331. begin
  13332. NewSize := S_B;
  13333. NewRegSize := R_SUBL;
  13334. Limit := $FF;
  13335. end;
  13336. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13337. begin
  13338. NewSize := S_W;
  13339. NewRegSize := R_SUBW;
  13340. Limit := $FFFF;
  13341. end;
  13342. {$ifdef x86_64}
  13343. S_LQ:
  13344. begin
  13345. NewSize := S_L;
  13346. NewRegSize := R_SUBD;
  13347. Limit := $FFFFFFFF;
  13348. end;
  13349. {$endif x86_64}
  13350. else
  13351. Internalerror(2021120302);
  13352. end;
  13353. TransferUsedRegs(TmpUsedRegs);
  13354. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13355. if AndTest then
  13356. begin
  13357. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13358. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13359. end
  13360. else
  13361. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13362. if
  13363. (
  13364. (taicpu(p).opcode = A_MOVZX) and
  13365. (
  13366. (taicpu(hp1).opcode=A_AND) or
  13367. (taicpu(hp1).opcode=A_TEST)
  13368. ) and
  13369. not (
  13370. { If both are references, then the final instruction will have
  13371. both operands as references, which is not allowed }
  13372. (taicpu(p).oper[0]^.typ = top_ref) and
  13373. (taicpu(hp1).oper[0]^.typ = top_ref)
  13374. ) and
  13375. not RegUsed
  13376. ) or
  13377. (
  13378. (
  13379. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13380. not RegUsed
  13381. ) and
  13382. (taicpu(p).oper[0]^.typ = top_reg) and
  13383. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13384. (taicpu(hp1).oper[0]^.typ = top_const) and
  13385. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13386. ) then
  13387. begin
  13388. {$if defined(i386) or defined(i8086)}
  13389. { If the target size is 8-bit, make sure we can actually encode it }
  13390. 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
  13391. Exit;
  13392. {$endif i386 or i8086}
  13393. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13394. taicpu(hp1).opsize := NewSize;
  13395. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13396. if AndTest then
  13397. begin
  13398. RemoveInstruction(hp2);
  13399. if not RegUsed then
  13400. begin
  13401. taicpu(hp1).opcode := A_TEST;
  13402. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13403. begin
  13404. { Make sure the reference is the second operand }
  13405. SwapOper := taicpu(hp1).oper[0];
  13406. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13407. taicpu(hp1).oper[1] := SwapOper;
  13408. end;
  13409. end;
  13410. end;
  13411. case taicpu(hp1).oper[0]^.typ of
  13412. top_reg:
  13413. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13414. top_const:
  13415. { For the AND/TEST case }
  13416. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13417. else
  13418. ;
  13419. end;
  13420. if RegUsed then
  13421. begin
  13422. AsmL.Remove(p);
  13423. AsmL.InsertAfter(p, hp1);
  13424. p := hp1;
  13425. end
  13426. else
  13427. RemoveCurrentP(p, hp1);
  13428. result:=true;
  13429. exit;
  13430. end;
  13431. end;
  13432. end;
  13433. if reg_and_hp1_is_instr and
  13434. (taicpu(p).oper[0]^.typ = top_reg) and
  13435. (
  13436. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13437. ) and
  13438. (taicpu(hp1).oper[0]^.typ = top_const) and
  13439. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13440. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13441. { Minimum shift value allowed is the bit difference between the sizes }
  13442. (taicpu(hp1).oper[0]^.val >=
  13443. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13444. 8 * (
  13445. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13446. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13447. )
  13448. ) then
  13449. begin
  13450. { For:
  13451. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13452. shl/sal ##, %reg1
  13453. Remove the movsx/movzx instruction if the shift overwrites the
  13454. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13455. }
  13456. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13457. RemoveCurrentP(p, hp1);
  13458. Result := True;
  13459. Exit;
  13460. end
  13461. else if reg_and_hp1_is_instr and
  13462. (taicpu(p).oper[0]^.typ = top_reg) and
  13463. (
  13464. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13465. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13466. ) and
  13467. (taicpu(hp1).oper[0]^.typ = top_const) and
  13468. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13469. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13470. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13471. (taicpu(hp1).oper[0]^.val <
  13472. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13473. 8 * (
  13474. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13475. )
  13476. ) then
  13477. begin
  13478. { For:
  13479. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13480. sar ##, %reg1 shr ##, %reg1
  13481. Move the shift to before the movx instruction if the shift value
  13482. is not too large.
  13483. }
  13484. asml.Remove(hp1);
  13485. asml.InsertBefore(hp1, p);
  13486. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13487. case taicpu(p).opsize of
  13488. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13489. taicpu(hp1).opsize := S_B;
  13490. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13491. taicpu(hp1).opsize := S_W;
  13492. {$ifdef x86_64}
  13493. S_LQ:
  13494. taicpu(hp1).opsize := S_L;
  13495. {$endif}
  13496. else
  13497. InternalError(2020112401);
  13498. end;
  13499. if (taicpu(hp1).opcode = A_SHR) then
  13500. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13501. else
  13502. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13503. Result := True;
  13504. end;
  13505. if reg_and_hp1_is_instr and
  13506. (taicpu(p).oper[0]^.typ = top_reg) and
  13507. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13508. (
  13509. (taicpu(hp1).opcode = taicpu(p).opcode)
  13510. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13511. {$ifdef x86_64}
  13512. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13513. {$endif x86_64}
  13514. ) then
  13515. begin
  13516. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13517. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13518. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13519. begin
  13520. {
  13521. For example:
  13522. movzbw %al,%ax
  13523. movzwl %ax,%eax
  13524. Compress into:
  13525. movzbl %al,%eax
  13526. }
  13527. RegUsed := False;
  13528. case taicpu(p).opsize of
  13529. S_BW:
  13530. case taicpu(hp1).opsize of
  13531. S_WL:
  13532. begin
  13533. taicpu(p).opsize := S_BL;
  13534. RegUsed := True;
  13535. end;
  13536. {$ifdef x86_64}
  13537. S_WQ:
  13538. begin
  13539. if taicpu(p).opcode = A_MOVZX then
  13540. begin
  13541. taicpu(p).opsize := S_BL;
  13542. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13543. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13544. end
  13545. else
  13546. taicpu(p).opsize := S_BQ;
  13547. RegUsed := True;
  13548. end;
  13549. {$endif x86_64}
  13550. else
  13551. ;
  13552. end;
  13553. {$ifdef x86_64}
  13554. S_BL:
  13555. case taicpu(hp1).opsize of
  13556. S_LQ:
  13557. begin
  13558. if taicpu(p).opcode = A_MOVZX then
  13559. begin
  13560. taicpu(p).opsize := S_BL;
  13561. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13562. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13563. end
  13564. else
  13565. taicpu(p).opsize := S_BQ;
  13566. RegUsed := True;
  13567. end;
  13568. else
  13569. ;
  13570. end;
  13571. S_WL:
  13572. case taicpu(hp1).opsize of
  13573. S_LQ:
  13574. begin
  13575. if taicpu(p).opcode = A_MOVZX then
  13576. begin
  13577. taicpu(p).opsize := S_WL;
  13578. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13579. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13580. end
  13581. else
  13582. taicpu(p).opsize := S_WQ;
  13583. RegUsed := True;
  13584. end;
  13585. else
  13586. ;
  13587. end;
  13588. {$endif x86_64}
  13589. else
  13590. ;
  13591. end;
  13592. if RegUsed then
  13593. begin
  13594. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13595. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13596. RemoveInstruction(hp1);
  13597. Result := True;
  13598. Exit;
  13599. end;
  13600. end;
  13601. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13602. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13603. GetNextInstruction(hp1, hp2) and
  13604. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13605. (
  13606. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13607. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13608. {$ifdef x86_64}
  13609. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13610. {$endif x86_64}
  13611. ) and
  13612. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13613. (
  13614. (
  13615. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13616. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13617. ) or
  13618. (
  13619. { Only allow the operands in reverse order for TEST instructions }
  13620. (taicpu(hp2).opcode = A_TEST) and
  13621. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13622. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13623. )
  13624. ) then
  13625. begin
  13626. {
  13627. For example:
  13628. movzbl %al,%eax
  13629. movzbl (ref),%edx
  13630. andl %edx,%eax
  13631. (%edx deallocated)
  13632. Change to:
  13633. andb (ref),%al
  13634. movzbl %al,%eax
  13635. Rules are:
  13636. - First two instructions have the same opcode and opsize
  13637. - First instruction's operands are the same super-register
  13638. - Second instruction operates on a different register
  13639. - Third instruction is AND, OR, XOR or TEST
  13640. - Third instruction's operands are the destination registers of the first two instructions
  13641. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13642. - Second instruction's destination register is deallocated afterwards
  13643. }
  13644. TransferUsedRegs(TmpUsedRegs);
  13645. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13646. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13647. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13648. begin
  13649. case taicpu(p).opsize of
  13650. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13651. NewSize := S_B;
  13652. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13653. NewSize := S_W;
  13654. {$ifdef x86_64}
  13655. S_LQ:
  13656. NewSize := S_L;
  13657. {$endif x86_64}
  13658. else
  13659. InternalError(2021120301);
  13660. end;
  13661. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13662. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13663. taicpu(hp2).opsize := NewSize;
  13664. RemoveInstruction(hp1);
  13665. { With TEST, it's best to keep the MOVX instruction at the top }
  13666. if (taicpu(hp2).opcode <> A_TEST) then
  13667. begin
  13668. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13669. asml.Remove(p);
  13670. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13671. asml.InsertAfter(p, hp2);
  13672. p := hp2;
  13673. end
  13674. else
  13675. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13676. Result := True;
  13677. Exit;
  13678. end;
  13679. end;
  13680. end;
  13681. if taicpu(p).opcode=A_MOVZX then
  13682. begin
  13683. { removes superfluous And's after movzx's }
  13684. if reg_and_hp1_is_instr and
  13685. (taicpu(hp1).opcode = A_AND) and
  13686. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13687. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13688. {$ifdef x86_64}
  13689. { check for implicit extension to 64 bit }
  13690. or
  13691. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13692. (taicpu(hp1).opsize=S_Q) and
  13693. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13694. )
  13695. {$endif x86_64}
  13696. )
  13697. then
  13698. begin
  13699. case taicpu(p).opsize Of
  13700. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13701. if (taicpu(hp1).oper[0]^.val = $ff) then
  13702. begin
  13703. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13704. RemoveInstruction(hp1);
  13705. Result:=true;
  13706. exit;
  13707. end;
  13708. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13709. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13710. begin
  13711. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13712. RemoveInstruction(hp1);
  13713. Result:=true;
  13714. exit;
  13715. end;
  13716. {$ifdef x86_64}
  13717. S_LQ:
  13718. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13719. begin
  13720. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13721. RemoveInstruction(hp1);
  13722. Result:=true;
  13723. exit;
  13724. end;
  13725. {$endif x86_64}
  13726. else
  13727. ;
  13728. end;
  13729. { we cannot get rid of the and, but can we get rid of the movz ?}
  13730. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13731. begin
  13732. case taicpu(p).opsize Of
  13733. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13734. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13735. begin
  13736. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13737. RemoveCurrentP(p,hp1);
  13738. Result:=true;
  13739. exit;
  13740. end;
  13741. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13742. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13743. begin
  13744. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13745. RemoveCurrentP(p,hp1);
  13746. Result:=true;
  13747. exit;
  13748. end;
  13749. {$ifdef x86_64}
  13750. S_LQ:
  13751. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13752. begin
  13753. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13754. RemoveCurrentP(p,hp1);
  13755. Result:=true;
  13756. exit;
  13757. end;
  13758. {$endif x86_64}
  13759. else
  13760. ;
  13761. end;
  13762. end;
  13763. end;
  13764. { changes some movzx constructs to faster synonyms (all examples
  13765. are given with eax/ax, but are also valid for other registers)}
  13766. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13767. begin
  13768. case taicpu(p).opsize of
  13769. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13770. (the machine code is equivalent to movzbl %al,%eax), but the
  13771. code generator still generates that assembler instruction and
  13772. it is silently converted. This should probably be checked.
  13773. [Kit] }
  13774. S_BW:
  13775. begin
  13776. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13777. (
  13778. not IsMOVZXAcceptable
  13779. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13780. or (
  13781. (cs_opt_size in current_settings.optimizerswitches) and
  13782. (taicpu(p).oper[1]^.reg = NR_AX)
  13783. )
  13784. ) then
  13785. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13786. begin
  13787. DebugMsg(SPeepholeOptimization + 'var7',p);
  13788. taicpu(p).opcode := A_AND;
  13789. taicpu(p).changeopsize(S_W);
  13790. taicpu(p).loadConst(0,$ff);
  13791. Result := True;
  13792. end
  13793. else if not IsMOVZXAcceptable and
  13794. GetNextInstruction(p, hp1) and
  13795. (tai(hp1).typ = ait_instruction) and
  13796. (taicpu(hp1).opcode = A_AND) and
  13797. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13798. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13799. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13800. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13801. begin
  13802. DebugMsg(SPeepholeOptimization + 'var8',p);
  13803. taicpu(p).opcode := A_MOV;
  13804. taicpu(p).changeopsize(S_W);
  13805. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13806. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13807. Result := True;
  13808. end;
  13809. end;
  13810. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13811. S_BL:
  13812. if not IsMOVZXAcceptable then
  13813. begin
  13814. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13815. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13816. begin
  13817. DebugMsg(SPeepholeOptimization + 'var9',p);
  13818. taicpu(p).opcode := A_AND;
  13819. taicpu(p).changeopsize(S_L);
  13820. taicpu(p).loadConst(0,$ff);
  13821. Result := True;
  13822. end
  13823. else if GetNextInstruction(p, hp1) and
  13824. (tai(hp1).typ = ait_instruction) and
  13825. (taicpu(hp1).opcode = A_AND) and
  13826. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13827. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13828. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13829. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13830. begin
  13831. DebugMsg(SPeepholeOptimization + 'var10',p);
  13832. taicpu(p).opcode := A_MOV;
  13833. taicpu(p).changeopsize(S_L);
  13834. { do not use R_SUBWHOLE
  13835. as movl %rdx,%eax
  13836. is invalid in assembler PM }
  13837. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13838. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13839. Result := True;
  13840. end;
  13841. end;
  13842. {$endif i8086}
  13843. S_WL:
  13844. if not IsMOVZXAcceptable then
  13845. begin
  13846. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13847. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13848. begin
  13849. DebugMsg(SPeepholeOptimization + 'var11',p);
  13850. taicpu(p).opcode := A_AND;
  13851. taicpu(p).changeopsize(S_L);
  13852. taicpu(p).loadConst(0,$ffff);
  13853. Result := True;
  13854. end
  13855. else if GetNextInstruction(p, hp1) and
  13856. (tai(hp1).typ = ait_instruction) and
  13857. (taicpu(hp1).opcode = A_AND) and
  13858. (taicpu(hp1).oper[0]^.typ = top_const) and
  13859. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13860. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13861. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13862. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13863. begin
  13864. DebugMsg(SPeepholeOptimization + 'var12',p);
  13865. taicpu(p).opcode := A_MOV;
  13866. taicpu(p).changeopsize(S_L);
  13867. { do not use R_SUBWHOLE
  13868. as movl %rdx,%eax
  13869. is invalid in assembler PM }
  13870. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13871. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13872. Result := True;
  13873. end;
  13874. end;
  13875. else
  13876. InternalError(2017050705);
  13877. end;
  13878. end
  13879. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13880. begin
  13881. if GetNextInstruction(p, hp1) and
  13882. (tai(hp1).typ = ait_instruction) and
  13883. (taicpu(hp1).opcode = A_AND) and
  13884. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13885. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13886. begin
  13887. case taicpu(p).opsize Of
  13888. S_BL:
  13889. if (taicpu(hp1).opsize <> S_L) or
  13890. (taicpu(hp1).oper[0]^.val > $FF) then
  13891. begin
  13892. DebugMsg(SPeepholeOptimization + 'var13',p);
  13893. taicpu(hp1).changeopsize(S_L);
  13894. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13895. Include(OptsToCheck, aoc_ForceNewIteration);
  13896. end;
  13897. S_WL:
  13898. if (taicpu(hp1).opsize <> S_L) or
  13899. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13900. begin
  13901. DebugMsg(SPeepholeOptimization + 'var14',p);
  13902. taicpu(hp1).changeopsize(S_L);
  13903. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13904. Include(OptsToCheck, aoc_ForceNewIteration);
  13905. end;
  13906. S_BW:
  13907. if (taicpu(hp1).opsize <> S_W) or
  13908. (taicpu(hp1).oper[0]^.val > $FF) then
  13909. begin
  13910. DebugMsg(SPeepholeOptimization + 'var15',p);
  13911. taicpu(hp1).changeopsize(S_W);
  13912. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13913. Include(OptsToCheck, aoc_ForceNewIteration);
  13914. end;
  13915. else
  13916. Internalerror(2017050704)
  13917. end;
  13918. end;
  13919. end;
  13920. end;
  13921. end;
  13922. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13923. var
  13924. hp1, hp2 : tai;
  13925. MaskLength : Cardinal;
  13926. MaskedBits : TCgInt;
  13927. ActiveReg : TRegister;
  13928. begin
  13929. Result:=false;
  13930. { There are no optimisations for reference targets }
  13931. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13932. Exit;
  13933. while GetNextInstruction(p, hp1) and
  13934. (hp1.typ = ait_instruction) do
  13935. begin
  13936. if (taicpu(p).oper[0]^.typ = top_const) then
  13937. begin
  13938. case taicpu(hp1).opcode of
  13939. A_AND:
  13940. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13941. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13942. { the second register must contain the first one, so compare their subreg types }
  13943. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13944. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13945. { change
  13946. and const1, reg
  13947. and const2, reg
  13948. to
  13949. and (const1 and const2), reg
  13950. }
  13951. begin
  13952. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13953. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13954. RemoveCurrentP(p, hp1);
  13955. Result:=true;
  13956. exit;
  13957. end;
  13958. A_CMP:
  13959. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13960. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13961. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13962. { Just check that the condition on the next instruction is compatible }
  13963. GetNextInstruction(hp1, hp2) and
  13964. (hp2.typ = ait_instruction) and
  13965. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13966. then
  13967. { change
  13968. and 2^n, reg
  13969. cmp 2^n, reg
  13970. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13971. to
  13972. and 2^n, reg
  13973. test reg, reg
  13974. j(~c) / set(~c) / cmov(~c)
  13975. }
  13976. begin
  13977. { Keep TEST instruction in, rather than remove it, because
  13978. it may trigger other optimisations such as MovAndTest2Test }
  13979. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13980. taicpu(hp1).opcode := A_TEST;
  13981. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13982. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13983. Result := True;
  13984. Exit;
  13985. end
  13986. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13987. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13988. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13989. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13990. { change
  13991. and $ff/$ff/$ffff, reg
  13992. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13993. dealloc reg
  13994. to
  13995. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13996. }
  13997. begin
  13998. TransferUsedRegs(TmpUsedRegs);
  13999. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14000. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  14001. begin
  14002. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  14003. case taicpu(p).oper[0]^.val of
  14004. $ff:
  14005. begin
  14006. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  14007. taicpu(hp1).opsize:=S_B;
  14008. end;
  14009. $ffff:
  14010. begin
  14011. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  14012. taicpu(hp1).opsize:=S_W;
  14013. end;
  14014. $ffffffff:
  14015. begin
  14016. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  14017. taicpu(hp1).opsize:=S_L;
  14018. end;
  14019. else
  14020. Internalerror(2023030401);
  14021. end;
  14022. RemoveCurrentP(p);
  14023. Result := True;
  14024. Exit;
  14025. end;
  14026. end;
  14027. A_MOVZX:
  14028. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  14029. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  14030. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14031. (
  14032. (
  14033. (taicpu(p).opsize=S_W) and
  14034. (taicpu(hp1).opsize=S_BW)
  14035. ) or
  14036. (
  14037. (taicpu(p).opsize=S_L) and
  14038. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  14039. )
  14040. {$ifdef x86_64}
  14041. or
  14042. (
  14043. (taicpu(p).opsize=S_Q) and
  14044. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  14045. )
  14046. {$endif x86_64}
  14047. ) then
  14048. begin
  14049. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14050. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  14051. ) or
  14052. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14053. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  14054. then
  14055. begin
  14056. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  14057. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  14058. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  14059. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  14060. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  14061. }
  14062. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  14063. RemoveInstruction(hp1);
  14064. { See if there are other optimisations possible }
  14065. Continue;
  14066. end;
  14067. end;
  14068. A_SHL:
  14069. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14070. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  14071. begin
  14072. {$ifopt R+}
  14073. {$define RANGE_WAS_ON}
  14074. {$R-}
  14075. {$endif}
  14076. { get length of potential and mask }
  14077. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  14078. { really a mask? }
  14079. {$ifdef RANGE_WAS_ON}
  14080. {$R+}
  14081. {$endif}
  14082. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  14083. { unmasked part shifted out? }
  14084. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  14085. begin
  14086. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  14087. RemoveCurrentP(p, hp1);
  14088. Result:=true;
  14089. exit;
  14090. end;
  14091. end;
  14092. A_SHR:
  14093. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14094. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  14095. (taicpu(hp1).oper[0]^.val <= 63) then
  14096. begin
  14097. { Does SHR combined with the AND cover all the bits?
  14098. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  14099. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  14100. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  14101. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  14102. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  14103. begin
  14104. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  14105. RemoveCurrentP(p, hp1);
  14106. Result := True;
  14107. Exit;
  14108. end;
  14109. end;
  14110. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14111. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14112. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14113. begin
  14114. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14115. (
  14116. (
  14117. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14118. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14119. ) or (
  14120. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14121. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14122. {$ifdef x86_64}
  14123. ) or (
  14124. (taicpu(hp1).opsize = S_LQ) and
  14125. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14126. {$endif x86_64}
  14127. )
  14128. ) then
  14129. begin
  14130. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14131. begin
  14132. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14133. RemoveInstruction(hp1);
  14134. { See if there are other optimisations possible }
  14135. Continue;
  14136. end;
  14137. { The super-registers are the same though.
  14138. Note that this change by itself doesn't improve
  14139. code speed, but it opens up other optimisations. }
  14140. {$ifdef x86_64}
  14141. { Convert 64-bit register to 32-bit }
  14142. case taicpu(hp1).opsize of
  14143. S_BQ:
  14144. begin
  14145. taicpu(hp1).opsize := S_BL;
  14146. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14147. end;
  14148. S_WQ:
  14149. begin
  14150. taicpu(hp1).opsize := S_WL;
  14151. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14152. end
  14153. else
  14154. ;
  14155. end;
  14156. {$endif x86_64}
  14157. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14158. taicpu(hp1).opcode := A_MOVZX;
  14159. { See if there are other optimisations possible }
  14160. Continue;
  14161. end;
  14162. end;
  14163. else
  14164. ;
  14165. end;
  14166. end
  14167. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14168. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14169. begin
  14170. {$ifdef x86_64}
  14171. if (taicpu(p).opsize = S_Q) then
  14172. begin
  14173. { Never necessary }
  14174. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14175. RemoveCurrentP(p, hp1);
  14176. Result := True;
  14177. Exit;
  14178. end;
  14179. {$endif x86_64}
  14180. { Forward check to determine necessity of and %reg,%reg }
  14181. TransferUsedRegs(TmpUsedRegs);
  14182. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14183. { Saves on a bunch of dereferences }
  14184. ActiveReg := taicpu(p).oper[1]^.reg;
  14185. case taicpu(hp1).opcode of
  14186. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14187. if (
  14188. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14189. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14190. ) and
  14191. (
  14192. (taicpu(hp1).opcode <> A_MOV) or
  14193. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14194. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14195. ) and
  14196. not (
  14197. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14198. (taicpu(hp1).opcode = A_MOV) and
  14199. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14200. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14201. ) and
  14202. (
  14203. (
  14204. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14205. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14206. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14207. ) or
  14208. (
  14209. {$ifdef x86_64}
  14210. (
  14211. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14212. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14213. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14214. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14215. ) and
  14216. {$endif x86_64}
  14217. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14218. )
  14219. ) then
  14220. begin
  14221. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14222. RemoveCurrentP(p, hp1);
  14223. Result := True;
  14224. Exit;
  14225. end;
  14226. A_ADD,
  14227. A_AND,
  14228. A_BSF,
  14229. A_BSR,
  14230. A_BTC,
  14231. A_BTR,
  14232. A_BTS,
  14233. A_OR,
  14234. A_SUB,
  14235. A_XOR:
  14236. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14237. if (
  14238. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14239. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14240. ) and
  14241. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14242. begin
  14243. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14244. RemoveCurrentP(p, hp1);
  14245. Result := True;
  14246. Exit;
  14247. end;
  14248. A_CMP,
  14249. A_TEST:
  14250. if (
  14251. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14252. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14253. ) and
  14254. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14255. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14256. begin
  14257. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14258. RemoveCurrentP(p, hp1);
  14259. Result := True;
  14260. Exit;
  14261. end;
  14262. A_BSWAP,
  14263. A_NEG,
  14264. A_NOT:
  14265. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14266. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14267. begin
  14268. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14269. RemoveCurrentP(p, hp1);
  14270. Result := True;
  14271. Exit;
  14272. end;
  14273. else
  14274. ;
  14275. end;
  14276. end;
  14277. if (taicpu(hp1).is_jmp) and
  14278. (taicpu(hp1).opcode<>A_JMP) and
  14279. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14280. begin
  14281. { change
  14282. and x, reg
  14283. jxx
  14284. to
  14285. test x, reg
  14286. jxx
  14287. if reg is deallocated before the
  14288. jump, but only if it's a conditional jump (PFV)
  14289. }
  14290. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14291. taicpu(p).opcode := A_TEST;
  14292. Exit;
  14293. end;
  14294. Break;
  14295. end;
  14296. { Lone AND tests }
  14297. if (taicpu(p).oper[0]^.typ = top_const) then
  14298. begin
  14299. {
  14300. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14301. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14302. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14303. }
  14304. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14305. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14306. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14307. begin
  14308. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14309. if taicpu(p).opsize = S_L then
  14310. begin
  14311. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14312. Result := True;
  14313. end;
  14314. end;
  14315. end;
  14316. { Backward check to determine necessity of and %reg,%reg }
  14317. if (taicpu(p).oper[0]^.typ = top_reg) and
  14318. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14319. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14320. GetLastInstruction(p, hp2) and
  14321. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14322. { Check size of adjacent instruction to determine if the AND is
  14323. effectively a null operation }
  14324. (
  14325. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14326. { Note: Don't include S_Q }
  14327. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14328. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14329. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14330. ) then
  14331. begin
  14332. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14333. { If GetNextInstruction returned False, hp1 will be nil }
  14334. RemoveCurrentP(p, hp1);
  14335. Result := True;
  14336. Exit;
  14337. end;
  14338. end;
  14339. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14340. var
  14341. hp1, hp2: tai;
  14342. NewRef: TReference;
  14343. Distance: Cardinal;
  14344. TempTracking: TAllUsedRegs;
  14345. DoAddMov2Lea: Boolean;
  14346. { This entire nested function is used in an if-statement below, but we
  14347. want to avoid all the used reg transfers and GetNextInstruction calls
  14348. until we really have to check }
  14349. function MemRegisterNotUsedLater: Boolean; inline;
  14350. var
  14351. hp2: tai;
  14352. begin
  14353. TransferUsedRegs(TmpUsedRegs);
  14354. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14355. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14356. else
  14357. { p and hp1 will be adjacent }
  14358. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14359. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14360. end;
  14361. begin
  14362. Result := False;
  14363. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14364. (taicpu(p).oper[1]^.typ = top_reg) then
  14365. begin
  14366. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14367. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14368. (hp1.typ <> ait_instruction) or
  14369. not
  14370. (
  14371. (cs_opt_level3 in current_settings.optimizerswitches) or
  14372. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14373. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14374. ) then
  14375. Exit;
  14376. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14377. addq $x, %rax
  14378. movq %rax, %rdx
  14379. sarq $63, %rdx
  14380. (%rax still in use)
  14381. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14382. leaq $x(%rax),%rdx
  14383. addq $x, %rax
  14384. sarq $63, %rdx
  14385. ...which is okay since it breaks the dependency chain between
  14386. addq and movq, but if OptPass2MOV is called first:
  14387. addq $x, %rax
  14388. cqto
  14389. ...which is better in all ways, taking only 2 cycles to execute
  14390. and much smaller in code size.
  14391. }
  14392. { The extra register tracking is quite strenuous }
  14393. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14394. MatchInstruction(hp1, A_MOV, []) then
  14395. begin
  14396. { Update the register tracking to the MOV instruction }
  14397. CopyUsedRegs(TempTracking);
  14398. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14399. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14400. else
  14401. { p and hp1 will be adjacent }
  14402. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14403. hp2 := hp1;
  14404. if OptPass2MOV(hp1) then
  14405. Include(OptsToCheck, aoc_ForceNewIteration);
  14406. { Reset the tracking to the current instruction }
  14407. RestoreUsedRegs(TempTracking);
  14408. ReleaseUsedRegs(TempTracking);
  14409. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14410. OptPass2ADD get called again }
  14411. if (hp1 <> hp2) then
  14412. begin
  14413. Result := True;
  14414. Exit;
  14415. end;
  14416. end;
  14417. { Change:
  14418. add %reg2,%reg1
  14419. (%reg2 not modified in between)
  14420. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14421. To:
  14422. mov/s/z #(%reg1,%reg2),%reg1
  14423. }
  14424. if (taicpu(p).oper[0]^.typ = top_reg) and
  14425. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14426. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14427. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14428. (
  14429. (
  14430. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14431. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14432. { r/esp cannot be an index }
  14433. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14434. ) or (
  14435. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14436. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14437. )
  14438. ) and (
  14439. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14440. (
  14441. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14442. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14443. MemRegisterNotUsedLater
  14444. )
  14445. ) then
  14446. begin
  14447. if (
  14448. { Instructions are guaranteed to be adjacent on -O2 and under }
  14449. (cs_opt_level3 in current_settings.optimizerswitches) and
  14450. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14451. ) then
  14452. begin
  14453. { If the other register is used in between, move the MOV
  14454. instruction to right after the ADD instruction so a
  14455. saving can still be made }
  14456. Asml.Remove(hp1);
  14457. Asml.InsertAfter(hp1, p);
  14458. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14459. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14460. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14461. RemoveCurrentp(p, hp1);
  14462. end
  14463. else
  14464. begin
  14465. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14466. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14467. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14468. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14469. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14470. { hp1 may not be the immediate next instruction under -O3 }
  14471. RemoveCurrentp(p)
  14472. else
  14473. RemoveCurrentp(p, hp1);
  14474. end;
  14475. Result := True;
  14476. Exit;
  14477. end;
  14478. { Change:
  14479. addl/q $x,%reg1
  14480. movl/q %reg1,%reg2
  14481. To:
  14482. leal/q $x(%reg1),%reg2
  14483. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14484. Breaks the dependency chain.
  14485. }
  14486. if (taicpu(p).oper[0]^.typ = top_const) and
  14487. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14488. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14489. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14490. (
  14491. { Instructions are guaranteed to be adjacent on -O2 and under }
  14492. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14493. (
  14494. { If the flags are used, don't make the optimisation,
  14495. otherwise they will be scrambled. Fixes #41148 }
  14496. (
  14497. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14498. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14499. ) and
  14500. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14501. )
  14502. ) then
  14503. begin
  14504. TransferUsedRegs(TmpUsedRegs);
  14505. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14506. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14507. else
  14508. { p and hp1 will be adjacent }
  14509. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14510. if (
  14511. SetAndTest(
  14512. (
  14513. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14514. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14515. ),
  14516. DoAddMov2Lea
  14517. ) or
  14518. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14519. not (cs_opt_size in current_settings.optimizerswitches)
  14520. ) then
  14521. begin
  14522. { Change the MOV instruction to a LEA instruction, and update the
  14523. first operand }
  14524. reference_reset(NewRef, 1, []);
  14525. NewRef.base := taicpu(p).oper[1]^.reg;
  14526. NewRef.scalefactor := 1;
  14527. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14528. taicpu(hp1).opcode := A_LEA;
  14529. taicpu(hp1).loadref(0, NewRef);
  14530. if DoAddMov2Lea then
  14531. begin
  14532. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14533. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14534. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14535. { hp1 may not be the immediate next instruction under -O3 }
  14536. RemoveCurrentp(p)
  14537. else
  14538. RemoveCurrentp(p, hp1);
  14539. end
  14540. else
  14541. begin
  14542. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14543. { Move what is now the LEA instruction to before the ADD instruction }
  14544. Asml.Remove(hp1);
  14545. Asml.InsertBefore(hp1, p);
  14546. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14547. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14548. p := hp1;
  14549. end;
  14550. Result := True;
  14551. end;
  14552. end;
  14553. end;
  14554. end;
  14555. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14556. var
  14557. SubReg: TSubRegister;
  14558. hp1, hp2: tai;
  14559. CallJmp: Boolean;
  14560. begin
  14561. Result := False;
  14562. CallJmp := False;
  14563. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14564. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14565. with taicpu(p).oper[0]^.ref^ do
  14566. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14567. if (offset = 0) then
  14568. begin
  14569. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14570. begin
  14571. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14572. taicpu(p).opcode := A_ADD;
  14573. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14574. Result := True;
  14575. end
  14576. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14577. begin
  14578. if (base <> NR_NO) then
  14579. begin
  14580. if (scalefactor <= 1) then
  14581. begin
  14582. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14583. taicpu(p).opcode := A_ADD;
  14584. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14585. Result := True;
  14586. end;
  14587. end
  14588. else
  14589. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14590. if (scalefactor in [2, 4, 8]) then
  14591. begin
  14592. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14593. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14594. taicpu(p).opcode := A_SHL;
  14595. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14596. Result := True;
  14597. end;
  14598. end;
  14599. end
  14600. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14601. lot of latency, so break off the offset if %reg3 is used soon
  14602. afterwards }
  14603. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14604. { If 3-component addresses don't have additional latency, don't
  14605. perform this optimisation }
  14606. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14607. GetNextInstruction(p, hp1) and
  14608. (hp1.typ = ait_instruction) and
  14609. (
  14610. (
  14611. { Permit jumps and calls since they have a larger degree of overhead }
  14612. (
  14613. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14614. (
  14615. { ... unless the register specifies the location }
  14616. (taicpu(hp1).ops > 0) and
  14617. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14618. )
  14619. ) and
  14620. (
  14621. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14622. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14623. )
  14624. )
  14625. or
  14626. (
  14627. { Check up to two instructions ahead }
  14628. GetNextInstruction(hp1, hp2) and
  14629. (hp2.typ = ait_instruction) and
  14630. (
  14631. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14632. (
  14633. { Same as above }
  14634. (taicpu(hp2).ops > 0) and
  14635. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14636. )
  14637. ) and
  14638. (
  14639. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14640. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14641. )
  14642. )
  14643. ) then
  14644. begin
  14645. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14646. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14647. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14648. offset := 0;
  14649. if Assigned(symbol) or Assigned(relsymbol) then
  14650. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14651. else
  14652. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14653. { Inserting before the next instruction rather than after the
  14654. current instruction gives more accurate register tracking }
  14655. asml.InsertBefore(hp2, hp1);
  14656. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14657. Result := True;
  14658. end;
  14659. end;
  14660. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14661. var
  14662. hp1, hp2: tai;
  14663. NewRef: TReference;
  14664. Distance: Cardinal;
  14665. TempTracking: TAllUsedRegs;
  14666. DoSubMov2Lea: Boolean;
  14667. begin
  14668. Result := False;
  14669. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14670. MatchOpType(taicpu(p),top_const,top_reg) then
  14671. begin
  14672. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14673. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14674. (hp1.typ <> ait_instruction) or
  14675. not
  14676. (
  14677. (cs_opt_level3 in current_settings.optimizerswitches) or
  14678. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14679. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14680. ) then
  14681. Exit;
  14682. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14683. subq $x, %rax
  14684. movq %rax, %rdx
  14685. sarq $63, %rdx
  14686. (%rax still in use)
  14687. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14688. leaq $-x(%rax),%rdx
  14689. movq $x, %rax
  14690. sarq $63, %rdx
  14691. ...which is okay since it breaks the dependency chain between
  14692. subq and movq, but if OptPass2MOV is called first:
  14693. subq $x, %rax
  14694. cqto
  14695. ...which is better in all ways, taking only 2 cycles to execute
  14696. and much smaller in code size.
  14697. }
  14698. { The extra register tracking is quite strenuous }
  14699. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14700. MatchInstruction(hp1, A_MOV, []) then
  14701. begin
  14702. { Update the register tracking to the MOV instruction }
  14703. CopyUsedRegs(TempTracking);
  14704. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14705. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14706. else
  14707. { p and hp1 will be adjacent }
  14708. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14709. hp2 := hp1;
  14710. if OptPass2MOV(hp1) then
  14711. Include(OptsToCheck, aoc_ForceNewIteration);
  14712. { Reset the tracking to the current instruction }
  14713. RestoreUsedRegs(TempTracking);
  14714. ReleaseUsedRegs(TempTracking);
  14715. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14716. OptPass2SUB get called again }
  14717. if (hp1 <> hp2) then
  14718. begin
  14719. Result := True;
  14720. Exit;
  14721. end;
  14722. end;
  14723. { Change:
  14724. subl/q $x,%reg1
  14725. movl/q %reg1,%reg2
  14726. To:
  14727. leal/q $-x(%reg1),%reg2
  14728. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14729. Breaks the dependency chain and potentially permits the removal of
  14730. a CMP instruction if one follows.
  14731. }
  14732. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14733. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14734. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14735. (
  14736. { Instructions are guaranteed to be adjacent on -O2 and under }
  14737. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14738. (
  14739. { If the flags are used, don't make the optimisation,
  14740. otherwise they will be scrambled. Fixes #41148 }
  14741. (
  14742. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14743. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14744. ) and
  14745. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14746. )
  14747. ) then
  14748. begin
  14749. TransferUsedRegs(TmpUsedRegs);
  14750. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14751. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14752. else
  14753. { p and hp1 will be adjacent }
  14754. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14755. if (
  14756. SetAndTest(
  14757. (
  14758. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14759. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14760. ),
  14761. DoSubMov2Lea
  14762. ) or
  14763. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14764. not (cs_opt_size in current_settings.optimizerswitches)
  14765. ) then
  14766. begin
  14767. { Change the MOV instruction to a LEA instruction, and update the
  14768. first operand }
  14769. reference_reset(NewRef, 1, []);
  14770. NewRef.base := taicpu(p).oper[1]^.reg;
  14771. NewRef.scalefactor := 1;
  14772. NewRef.offset := -taicpu(p).oper[0]^.val;
  14773. taicpu(hp1).opcode := A_LEA;
  14774. taicpu(hp1).loadref(0, NewRef);
  14775. if DoSubMov2Lea then
  14776. begin
  14777. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14778. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14779. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14780. { hp1 may not be the immediate next instruction under -O3 }
  14781. RemoveCurrentp(p)
  14782. else
  14783. RemoveCurrentp(p, hp1);
  14784. end
  14785. else
  14786. begin
  14787. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14788. { Move what is now the LEA instruction to before the SUB instruction }
  14789. Asml.Remove(hp1);
  14790. Asml.InsertBefore(hp1, p);
  14791. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14792. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14793. p := hp1;
  14794. end;
  14795. Result := True;
  14796. end;
  14797. end;
  14798. end;
  14799. end;
  14800. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14801. begin
  14802. { we can skip all instructions not messing with the stack pointer }
  14803. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14804. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14805. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14806. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14807. ({(taicpu(hp1).ops=0) or }
  14808. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14809. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14810. ) and }
  14811. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14812. )
  14813. ) do
  14814. GetNextInstruction(hp1,hp1);
  14815. Result:=assigned(hp1);
  14816. end;
  14817. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14818. var
  14819. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14820. begin
  14821. Result:=false;
  14822. hp5:=nil;
  14823. hp6:=nil;
  14824. hp7:=nil;
  14825. hp8:=nil;
  14826. { replace
  14827. leal(q) x(<stackpointer>),<stackpointer>
  14828. <optional .seh_stackalloc ...>
  14829. <optional .seh_endprologue ...>
  14830. call procname
  14831. <optional NOP>
  14832. leal(q) -x(<stackpointer>),<stackpointer>
  14833. <optional VZEROUPPER>
  14834. ret
  14835. by
  14836. jmp procname
  14837. but do it only on level 4 because it destroys stack back traces
  14838. }
  14839. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14840. MatchOpType(taicpu(p),top_ref,top_reg) and
  14841. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14842. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14843. { the -8, -24, -40 are not required, but bail out early if possible,
  14844. higher values are unlikely }
  14845. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14846. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14847. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14848. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14849. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14850. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14851. GetNextInstruction(p, hp1) and
  14852. { Take a copy of hp1 }
  14853. SetAndTest(hp1, hp4) and
  14854. { trick to skip label }
  14855. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14856. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14857. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14858. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14859. SkipSimpleInstructions(hp1) and
  14860. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14861. GetNextInstruction(hp1, hp2) and
  14862. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14863. { skip nop instruction on win64 }
  14864. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14865. SetAndTest(hp2,hp6) and
  14866. GetNextInstruction(hp2,hp2) and
  14867. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14868. ) and
  14869. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14870. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14871. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14872. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14873. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14874. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14875. { Segment register will be NR_NO }
  14876. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14877. GetNextInstruction(hp2, hp3) and
  14878. { trick to skip label }
  14879. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14880. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14881. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14882. SetAndTest(hp3,hp5) and
  14883. GetNextInstruction(hp3,hp3) and
  14884. MatchInstruction(hp3,A_RET,[S_NO])
  14885. )
  14886. ) and
  14887. (taicpu(hp3).ops=0) then
  14888. begin
  14889. taicpu(hp1).opcode := A_JMP;
  14890. taicpu(hp1).is_jmp := true;
  14891. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14892. { search for the stackalloc directive and remove it }
  14893. hp7:=tai(p.next);
  14894. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14895. begin
  14896. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14897. begin
  14898. { sanity check }
  14899. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14900. Internalerror(2024012201);
  14901. hp8:=tai(hp7.next);
  14902. RemoveInstruction(tai(hp7));
  14903. hp7:=hp8;
  14904. break;
  14905. end
  14906. else
  14907. hp7:=tai(hp7.next);
  14908. end;
  14909. RemoveCurrentP(p, hp4);
  14910. RemoveInstruction(hp2);
  14911. RemoveInstruction(hp3);
  14912. { if there is a vzeroupper instruction then move it before the jmp }
  14913. if Assigned(hp5) then
  14914. begin
  14915. AsmL.Remove(hp5);
  14916. ASmL.InsertBefore(hp5,hp1)
  14917. end;
  14918. { remove nop on win64 }
  14919. if Assigned(hp6) then
  14920. RemoveInstruction(hp6);
  14921. Result:=true;
  14922. end;
  14923. end;
  14924. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14925. {$ifdef x86_64}
  14926. var
  14927. hp1, hp2, hp3, hp4, hp5: tai;
  14928. {$endif x86_64}
  14929. begin
  14930. Result:=false;
  14931. {$ifdef x86_64}
  14932. hp5:=nil;
  14933. { replace
  14934. push %rax
  14935. call procname
  14936. pop %rcx
  14937. ret
  14938. by
  14939. jmp procname
  14940. but do it only on level 4 because it destroys stack back traces
  14941. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14942. for all supported calling conventions
  14943. }
  14944. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14945. MatchOpType(taicpu(p),top_reg) and
  14946. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14947. GetNextInstruction(p, hp1) and
  14948. { Take a copy of hp1 }
  14949. SetAndTest(hp1, hp4) and
  14950. { trick to skip label }
  14951. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14952. SkipSimpleInstructions(hp1) and
  14953. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14954. GetNextInstruction(hp1, hp2) and
  14955. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14956. MatchOpType(taicpu(hp2),top_reg) and
  14957. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14958. GetNextInstruction(hp2, hp3) and
  14959. { trick to skip label }
  14960. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14961. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14962. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14963. SetAndTest(hp3,hp5) and
  14964. GetNextInstruction(hp3,hp3) and
  14965. MatchInstruction(hp3,A_RET,[S_NO])
  14966. )
  14967. ) and
  14968. (taicpu(hp3).ops=0) then
  14969. begin
  14970. taicpu(hp1).opcode := A_JMP;
  14971. taicpu(hp1).is_jmp := true;
  14972. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14973. RemoveCurrentP(p, hp4);
  14974. RemoveInstruction(hp2);
  14975. RemoveInstruction(hp3);
  14976. if Assigned(hp5) then
  14977. begin
  14978. AsmL.Remove(hp5);
  14979. ASmL.InsertBefore(hp5,hp1)
  14980. end;
  14981. Result:=true;
  14982. end;
  14983. {$endif x86_64}
  14984. end;
  14985. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14986. var
  14987. Value, RegName: string;
  14988. hp1: tai;
  14989. begin
  14990. Result:=false;
  14991. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14992. begin
  14993. case taicpu(p).oper[0]^.val of
  14994. 0:
  14995. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14996. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14997. (
  14998. { See if we can still convert the instruction }
  14999. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15000. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15001. ) then
  15002. begin
  15003. { change "mov $0,%reg" into "xor %reg,%reg" }
  15004. taicpu(p).opcode := A_XOR;
  15005. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  15006. Result := True;
  15007. {$ifdef x86_64}
  15008. end
  15009. else if (taicpu(p).opsize = S_Q) then
  15010. begin
  15011. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15012. { The actual optimization }
  15013. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15014. taicpu(p).changeopsize(S_L);
  15015. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15016. Result := True;
  15017. end;
  15018. $1..$FFFFFFFF:
  15019. begin
  15020. { Code size reduction by J. Gareth "Kit" Moreton }
  15021. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  15022. case taicpu(p).opsize of
  15023. S_Q:
  15024. begin
  15025. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15026. Value := debug_tostr(taicpu(p).oper[0]^.val);
  15027. { The actual optimization }
  15028. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15029. taicpu(p).changeopsize(S_L);
  15030. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15031. Result := True;
  15032. end;
  15033. else
  15034. { Do nothing };
  15035. end;
  15036. {$endif x86_64}
  15037. end;
  15038. -1:
  15039. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  15040. if (cs_opt_size in current_settings.optimizerswitches) and
  15041. (taicpu(p).opsize <> S_B) and
  15042. (
  15043. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15044. (
  15045. { See if we can still convert the instruction }
  15046. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15047. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15048. )
  15049. ) then
  15050. begin
  15051. { change "mov $-1,%reg" into "or $-1,%reg" }
  15052. { NOTES:
  15053. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  15054. - This operation creates a false dependency on the register, so only do it when optimising for size
  15055. - 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
  15056. }
  15057. taicpu(p).opcode := A_OR;
  15058. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  15059. Result := True;
  15060. end;
  15061. else
  15062. { Do nothing };
  15063. end;
  15064. end;
  15065. end;
  15066. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  15067. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  15068. begin
  15069. Result := False;
  15070. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  15071. Exit;
  15072. { For sizes less than S_L, the byte size is equal or larger with BTx,
  15073. so don't bother optimising }
  15074. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  15075. Exit;
  15076. if (taicpu(p).oper[0]^.typ <> top_const) or
  15077. { If the value can fit into an 8-bit signed integer, a smaller
  15078. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  15079. falls within this range }
  15080. (
  15081. (taicpu(p).oper[0]^.val > -128) and
  15082. (taicpu(p).oper[0]^.val <= 127)
  15083. ) then
  15084. Exit;
  15085. { If we're optimising for size, this is acceptable }
  15086. if (cs_opt_size in current_settings.optimizerswitches) then
  15087. Exit(True);
  15088. if (taicpu(p).oper[1]^.typ = top_reg) and
  15089. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15090. Exit(True);
  15091. if (taicpu(p).oper[1]^.typ <> top_reg) and
  15092. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15093. Exit(True);
  15094. end;
  15095. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  15096. var
  15097. hp1: tai;
  15098. Value: TCGInt;
  15099. begin
  15100. Result := False;
  15101. if MatchOpType(taicpu(p), top_const, top_reg) then
  15102. begin
  15103. { Detect:
  15104. andw x, %ax (0 <= x < $8000)
  15105. ...
  15106. movzwl %ax,%eax
  15107. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15108. }
  15109. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15110. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15111. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15112. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15113. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15114. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15115. begin
  15116. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15117. taicpu(hp1).opcode := A_CWDE;
  15118. taicpu(hp1).clearop(0);
  15119. taicpu(hp1).clearop(1);
  15120. taicpu(hp1).ops := 0;
  15121. { A change was made, but not with p, so don't set Result, but
  15122. notify the compiler that a change was made }
  15123. Include(OptsToCheck, aoc_ForceNewIteration);
  15124. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15125. end;
  15126. end;
  15127. { If "not x" is a power of 2 (popcnt = 1), change:
  15128. and $x, %reg/ref
  15129. To:
  15130. btr lb(x), %reg/ref
  15131. }
  15132. if IsBTXAcceptable(p) and
  15133. (
  15134. { Make sure a TEST doesn't follow that plays with the register }
  15135. not GetNextInstruction(p, hp1) or
  15136. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15137. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15138. ) then
  15139. begin
  15140. {$push}{$R-}{$Q-}
  15141. { Value is a sign-extended 32-bit integer - just correct it
  15142. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15143. checks to see if this operand is an immediate. }
  15144. Value := not taicpu(p).oper[0]^.val;
  15145. {$pop}
  15146. {$ifdef x86_64}
  15147. if taicpu(p).opsize = S_L then
  15148. {$endif x86_64}
  15149. Value := Value and $FFFFFFFF;
  15150. if (PopCnt(QWord(Value)) = 1) then
  15151. begin
  15152. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15153. taicpu(p).opcode := A_BTR;
  15154. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15155. Result := True;
  15156. Exit;
  15157. end;
  15158. end;
  15159. end;
  15160. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15161. begin
  15162. Result := False;
  15163. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15164. Exit;
  15165. { Convert:
  15166. movswl %ax,%eax -> cwtl
  15167. movslq %eax,%rax -> cdqe
  15168. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15169. refer to the same opcode and depends only on the assembler's
  15170. current operand-size attribute. [Kit]
  15171. }
  15172. with taicpu(p) do
  15173. case opsize of
  15174. S_WL:
  15175. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15176. begin
  15177. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15178. opcode := A_CWDE;
  15179. clearop(0);
  15180. clearop(1);
  15181. ops := 0;
  15182. Result := True;
  15183. end;
  15184. {$ifdef x86_64}
  15185. S_LQ:
  15186. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15187. begin
  15188. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15189. opcode := A_CDQE;
  15190. clearop(0);
  15191. clearop(1);
  15192. ops := 0;
  15193. Result := True;
  15194. end;
  15195. {$endif x86_64}
  15196. else
  15197. ;
  15198. end;
  15199. end;
  15200. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15201. var
  15202. hp1: tai;
  15203. begin
  15204. Result := False;
  15205. { All these optimisations work on "shr const,%reg" }
  15206. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15207. Exit;
  15208. if HandleSHRMerge(p, True) then
  15209. begin
  15210. Result := True;
  15211. Exit;
  15212. end;
  15213. { Detect the following (looking backwards):
  15214. shr %cl,%reg
  15215. shr x, %reg
  15216. Swap the two SHR instructions to minimise a pipeline stall.
  15217. }
  15218. if GetLastInstruction(p, hp1) and
  15219. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15220. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15221. { First operand will be %cl }
  15222. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15223. { Just to be sure }
  15224. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15225. begin
  15226. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15227. { Moving the entries this way ensures the register tracking remains correct }
  15228. Asml.Remove(p);
  15229. Asml.InsertBefore(p, hp1);
  15230. p := hp1;
  15231. { Don't set Result to True because the current instruction is now
  15232. "shr %cl,%reg" and there's nothing more we can do with it }
  15233. end;
  15234. end;
  15235. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15236. var
  15237. hp1, hp2: tai;
  15238. Opposite, SecondOpposite: TAsmOp;
  15239. NewCond: TAsmCond;
  15240. begin
  15241. Result := False;
  15242. { Change:
  15243. add/sub 128,(dest)
  15244. To:
  15245. sub/add -128,(dest)
  15246. This generaally takes fewer bytes to encode because -128 can be stored
  15247. in a signed byte, whereas +128 cannot.
  15248. }
  15249. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15250. begin
  15251. if taicpu(p).opcode = A_ADD then
  15252. Opposite := A_SUB
  15253. else
  15254. Opposite := A_ADD;
  15255. { Be careful if the flags are in use, because the CF flag inverts
  15256. when changing from ADD to SUB and vice versa }
  15257. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15258. GetNextInstruction(p, hp1) then
  15259. begin
  15260. TransferUsedRegs(TmpUsedRegs);
  15261. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15262. hp2 := hp1;
  15263. { Scan ahead to check if everything's safe }
  15264. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15265. begin
  15266. if (hp1.typ <> ait_instruction) then
  15267. { Probably unsafe since the flags are still in use }
  15268. Exit;
  15269. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15270. { Stop searching at an unconditional jump }
  15271. Break;
  15272. if not
  15273. (
  15274. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15275. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15276. ) and
  15277. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15278. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15279. Exit;
  15280. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15281. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15282. { Move to the next instruction }
  15283. GetNextInstruction(hp1, hp1);
  15284. end;
  15285. while Assigned(hp2) and (hp2 <> hp1) do
  15286. begin
  15287. NewCond := C_None;
  15288. case taicpu(hp2).condition of
  15289. C_A, C_NBE:
  15290. NewCond := C_BE;
  15291. C_B, C_C, C_NAE:
  15292. NewCond := C_AE;
  15293. C_AE, C_NB, C_NC:
  15294. NewCond := C_B;
  15295. C_BE, C_NA:
  15296. NewCond := C_A;
  15297. else
  15298. { No change needed };
  15299. end;
  15300. if NewCond <> C_None then
  15301. begin
  15302. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15303. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15304. taicpu(hp2).condition := NewCond;
  15305. end
  15306. else
  15307. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15308. begin
  15309. { Because of the flipping of the carry bit, to ensure
  15310. the operation remains equivalent, ADC becomes SBB
  15311. and vice versa, and the constant is not-inverted.
  15312. If multiple ADCs or SBBs appear in a row, each one
  15313. changed causes the carry bit to invert, so they all
  15314. need to be flipped }
  15315. if taicpu(hp2).opcode = A_ADC then
  15316. SecondOpposite := A_SBB
  15317. else
  15318. SecondOpposite := A_ADC;
  15319. if taicpu(hp2).oper[0]^.typ <> top_const then
  15320. { Should have broken out of this optimisation already }
  15321. InternalError(2021112901);
  15322. 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]^) + ' -> ' +
  15323. 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);
  15324. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15325. taicpu(hp2).opcode := SecondOpposite;
  15326. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15327. end;
  15328. { Move to the next instruction }
  15329. GetNextInstruction(hp2, hp2);
  15330. end;
  15331. if (hp2 <> hp1) then
  15332. InternalError(2021111501);
  15333. end;
  15334. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15335. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15336. taicpu(p).opcode := Opposite;
  15337. taicpu(p).oper[0]^.val := -128;
  15338. { No further optimisations can be made on this instruction, so move
  15339. onto the next one to save time }
  15340. p := tai(p.Next);
  15341. UpdateUsedRegs(p);
  15342. Result := True;
  15343. Exit;
  15344. end;
  15345. { Detect:
  15346. add/sub %reg2,(dest)
  15347. add/sub x, (dest)
  15348. (dest can be a register or a reference)
  15349. Swap the instructions to minimise a pipeline stall. This reverses the
  15350. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15351. optimisations could be made.
  15352. }
  15353. if (taicpu(p).oper[0]^.typ = top_reg) and
  15354. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15355. (
  15356. (
  15357. (taicpu(p).oper[1]^.typ = top_reg) and
  15358. { We can try searching further ahead if we're writing to a register }
  15359. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15360. ) or
  15361. (
  15362. (taicpu(p).oper[1]^.typ = top_ref) and
  15363. GetNextInstruction(p, hp1)
  15364. )
  15365. ) and
  15366. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15367. (taicpu(hp1).oper[0]^.typ = top_const) and
  15368. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15369. begin
  15370. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15371. TransferUsedRegs(TmpUsedRegs);
  15372. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15373. hp2 := p;
  15374. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15375. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15376. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15377. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15378. begin
  15379. asml.remove(hp1);
  15380. asml.InsertBefore(hp1, p);
  15381. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15382. Result := True;
  15383. end;
  15384. end;
  15385. end;
  15386. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15387. var
  15388. hp1: tai;
  15389. begin
  15390. Result:=false;
  15391. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15392. while GetNextInstruction(p, hp1) and
  15393. TrySwapMovCmp(p, hp1) do
  15394. begin
  15395. if MatchInstruction(hp1, A_MOV, []) then
  15396. begin
  15397. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15398. begin
  15399. { A little hacky, but since CMP doesn't read the flags, only
  15400. modify them, it's safe if they get scrambled by MOV -> XOR }
  15401. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15402. Result := PostPeepholeOptMov(hp1);
  15403. {$ifdef x86_64}
  15404. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15405. { Used to shrink instruction size }
  15406. PostPeepholeOptXor(hp1);
  15407. {$endif x86_64}
  15408. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15409. end
  15410. else
  15411. begin
  15412. Result := PostPeepholeOptMov(hp1);
  15413. {$ifdef x86_64}
  15414. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15415. { Used to shrink instruction size }
  15416. PostPeepholeOptXor(hp1);
  15417. {$endif x86_64}
  15418. end;
  15419. end;
  15420. { Enabling this flag is actually a null operation, but it marks
  15421. the code as 'modified' during this pass }
  15422. Include(OptsToCheck, aoc_ForceNewIteration);
  15423. end;
  15424. { change "cmp $0, %reg" to "test %reg, %reg" }
  15425. if MatchOpType(taicpu(p),top_const,top_reg) and
  15426. (taicpu(p).oper[0]^.val = 0) then
  15427. begin
  15428. taicpu(p).opcode := A_TEST;
  15429. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15430. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15431. Result:=true;
  15432. end;
  15433. end;
  15434. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15435. var
  15436. IsTestConstX, IsValid : Boolean;
  15437. hp1,hp2 : tai;
  15438. begin
  15439. Result:=false;
  15440. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15441. if (taicpu(p).opcode = A_TEST) then
  15442. while GetNextInstruction(p, hp1) and
  15443. TrySwapMovCmp(p, hp1) do
  15444. begin
  15445. if MatchInstruction(hp1, A_MOV, []) then
  15446. begin
  15447. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15448. begin
  15449. { A little hacky, but since TEST doesn't read the flags, only
  15450. modify them, it's safe if they get scrambled by MOV -> XOR }
  15451. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15452. Result := PostPeepholeOptMov(hp1);
  15453. {$ifdef x86_64}
  15454. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15455. { Used to shrink instruction size }
  15456. PostPeepholeOptXor(hp1);
  15457. {$endif x86_64}
  15458. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15459. end
  15460. else
  15461. begin
  15462. Result := PostPeepholeOptMov(hp1);
  15463. {$ifdef x86_64}
  15464. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15465. { Used to shrink instruction size }
  15466. PostPeepholeOptXor(hp1);
  15467. {$endif x86_64}
  15468. end;
  15469. end;
  15470. { Enabling this flag is actually a null operation, but it marks
  15471. the code as 'modified' during this pass }
  15472. Include(OptsToCheck, aoc_ForceNewIteration);
  15473. end;
  15474. { If x is a power of 2 (popcnt = 1), change:
  15475. or $x, %reg/ref
  15476. To:
  15477. bts lb(x), %reg/ref
  15478. }
  15479. if (taicpu(p).opcode = A_OR) and
  15480. IsBTXAcceptable(p) and
  15481. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15482. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15483. (
  15484. { Don't optimise if a test instruction follows }
  15485. not GetNextInstruction(p, hp1) or
  15486. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15487. ) then
  15488. begin
  15489. 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);
  15490. taicpu(p).opcode := A_BTS;
  15491. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15492. Result := True;
  15493. Exit;
  15494. end;
  15495. { If x is a power of 2 (popcnt = 1), change:
  15496. test $x, %reg/ref
  15497. je / sete / cmove (or jne / setne)
  15498. To:
  15499. bt lb(x), %reg/ref
  15500. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15501. }
  15502. if (taicpu(p).opcode = A_TEST) and
  15503. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15504. (taicpu(p).oper[0]^.typ = top_const) and
  15505. (
  15506. (cs_opt_size in current_settings.optimizerswitches) or
  15507. (
  15508. (taicpu(p).oper[1]^.typ = top_reg) and
  15509. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15510. ) or
  15511. (
  15512. (taicpu(p).oper[1]^.typ <> top_reg) and
  15513. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15514. )
  15515. ) and
  15516. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15517. { For sizes less than S_L, the byte size is equal or larger with BT,
  15518. so don't bother optimising }
  15519. (taicpu(p).opsize >= S_L) then
  15520. begin
  15521. IsValid := True;
  15522. { Check the next set of instructions, watching the FLAGS register
  15523. and the conditions used }
  15524. TransferUsedRegs(TmpUsedRegs);
  15525. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15526. hp1 := p;
  15527. hp2 := nil;
  15528. while GetNextInstruction(hp1, hp1) do
  15529. begin
  15530. if not Assigned(hp2) then
  15531. { The first instruction after TEST }
  15532. hp2 := hp1;
  15533. if (hp1.typ <> ait_instruction) then
  15534. begin
  15535. { If the flags are no longer in use, everything is fine }
  15536. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15537. IsValid := False;
  15538. Break;
  15539. end;
  15540. case taicpu(hp1).condition of
  15541. C_None:
  15542. begin
  15543. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15544. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15545. { Something is not quite normal, so play safe and don't change }
  15546. IsValid := False;
  15547. Break;
  15548. end;
  15549. C_E, C_Z, C_NE, C_NZ:
  15550. { This is fine };
  15551. else
  15552. begin
  15553. { Unsupported condition }
  15554. IsValid := False;
  15555. Break;
  15556. end;
  15557. end;
  15558. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15559. end;
  15560. if IsValid then
  15561. begin
  15562. while hp2 <> hp1 do
  15563. begin
  15564. case taicpu(hp2).condition of
  15565. C_Z, C_E:
  15566. taicpu(hp2).condition := C_NC;
  15567. C_NZ, C_NE:
  15568. taicpu(hp2).condition := C_C;
  15569. else
  15570. { Should not get this by this point }
  15571. InternalError(2022110701);
  15572. end;
  15573. GetNextInstruction(hp2, hp2);
  15574. end;
  15575. 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);
  15576. taicpu(p).opcode := A_BT;
  15577. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15578. Result := True;
  15579. Exit;
  15580. end;
  15581. end;
  15582. { removes the line marked with (x) from the sequence
  15583. and/or/xor/add/sub/... $x, %y
  15584. test/or %y, %y | test $-1, %y (x)
  15585. j(n)z _Label
  15586. as the first instruction already adjusts the ZF
  15587. %y operand may also be a reference }
  15588. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15589. MatchOperand(taicpu(p).oper[0]^,-1);
  15590. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15591. GetLastInstruction(p, hp1) and
  15592. (tai(hp1).typ = ait_instruction) and
  15593. GetNextInstruction(p,hp2) and
  15594. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15595. case taicpu(hp1).opcode Of
  15596. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15597. { These two instructions set the zero flag if the result is zero }
  15598. A_POPCNT, A_LZCNT:
  15599. begin
  15600. if (
  15601. { With POPCNT, an input of zero will set the zero flag
  15602. because the population count of zero is zero }
  15603. (taicpu(hp1).opcode = A_POPCNT) and
  15604. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15605. (
  15606. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15607. { Faster than going through the second half of the 'or'
  15608. condition below }
  15609. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15610. )
  15611. ) or (
  15612. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15613. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15614. { and in case of carry for A(E)/B(E)/C/NC }
  15615. (
  15616. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15617. (
  15618. (taicpu(hp1).opcode <> A_ADD) and
  15619. (taicpu(hp1).opcode <> A_SUB) and
  15620. (taicpu(hp1).opcode <> A_LZCNT)
  15621. )
  15622. )
  15623. ) then
  15624. begin
  15625. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15626. RemoveCurrentP(p, hp2);
  15627. Result:=true;
  15628. Exit;
  15629. end;
  15630. end;
  15631. A_SHL, A_SAL, A_SHR, A_SAR:
  15632. begin
  15633. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15634. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15635. { therefore, it's only safe to do this optimization for }
  15636. { shifts by a (nonzero) constant }
  15637. (taicpu(hp1).oper[0]^.typ = top_const) and
  15638. (taicpu(hp1).oper[0]^.val <> 0) and
  15639. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15640. { and in case of carry for A(E)/B(E)/C/NC }
  15641. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15642. begin
  15643. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15644. RemoveCurrentP(p, hp2);
  15645. Result:=true;
  15646. Exit;
  15647. end;
  15648. end;
  15649. A_DEC, A_INC, A_NEG:
  15650. begin
  15651. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15652. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15653. { and in case of carry for A(E)/B(E)/C/NC }
  15654. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15655. begin
  15656. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15657. RemoveCurrentP(p, hp2);
  15658. Result:=true;
  15659. Exit;
  15660. end;
  15661. end;
  15662. A_ANDN, A_BZHI:
  15663. begin
  15664. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15665. { Only the zero and sign flags are consistent with what the result is }
  15666. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15667. begin
  15668. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15669. RemoveCurrentP(p, hp2);
  15670. Result:=true;
  15671. Exit;
  15672. end;
  15673. end;
  15674. A_BEXTR:
  15675. begin
  15676. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15677. { Only the zero flag is set }
  15678. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15679. begin
  15680. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15681. RemoveCurrentP(p, hp2);
  15682. Result:=true;
  15683. Exit;
  15684. end;
  15685. end;
  15686. else
  15687. ;
  15688. end; { case }
  15689. { change "test $-1,%reg" into "test %reg,%reg" }
  15690. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15691. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15692. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15693. if MatchInstruction(p, A_OR, []) and
  15694. { Can only match if they're both registers }
  15695. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15696. begin
  15697. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15698. taicpu(p).opcode := A_TEST;
  15699. { No need to set Result to True, as we've done all the optimisations we can }
  15700. end;
  15701. end;
  15702. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15703. var
  15704. hp1,hp3 : tai;
  15705. {$ifndef x86_64}
  15706. hp2 : taicpu;
  15707. {$endif x86_64}
  15708. begin
  15709. Result:=false;
  15710. hp3:=nil;
  15711. {$ifndef x86_64}
  15712. { don't do this on modern CPUs, this really hurts them due to
  15713. broken call/ret pairing }
  15714. if (current_settings.optimizecputype < cpu_Pentium2) and
  15715. not(cs_create_pic in current_settings.moduleswitches) and
  15716. GetNextInstruction(p, hp1) and
  15717. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15718. MatchOpType(taicpu(hp1),top_ref) and
  15719. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15720. begin
  15721. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15722. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15723. InsertLLItem(p.previous, p, hp2);
  15724. taicpu(p).opcode := A_JMP;
  15725. taicpu(p).is_jmp := true;
  15726. RemoveInstruction(hp1);
  15727. Result:=true;
  15728. end
  15729. else
  15730. {$endif x86_64}
  15731. { replace
  15732. call procname
  15733. ret
  15734. by
  15735. jmp procname
  15736. but do it only on level 4 because it destroys stack back traces
  15737. else if the subroutine is marked as no return, remove the ret
  15738. }
  15739. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15740. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15741. GetNextInstruction(p, hp1) and
  15742. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15743. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15744. SetAndTest(hp1,hp3) and
  15745. GetNextInstruction(hp1,hp1) and
  15746. MatchInstruction(hp1,A_RET,[S_NO])
  15747. )
  15748. ) and
  15749. (taicpu(hp1).ops=0) then
  15750. begin
  15751. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15752. { we might destroy stack alignment here if we do not do a call }
  15753. (target_info.stackalign<=sizeof(SizeUInt)) then
  15754. begin
  15755. taicpu(p).opcode := A_JMP;
  15756. taicpu(p).is_jmp := true;
  15757. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15758. end
  15759. else
  15760. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15761. RemoveInstruction(hp1);
  15762. if Assigned(hp3) then
  15763. begin
  15764. AsmL.Remove(hp3);
  15765. AsmL.InsertBefore(hp3,p)
  15766. end;
  15767. Result:=true;
  15768. end;
  15769. end;
  15770. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15771. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15772. begin
  15773. case OpSize of
  15774. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15775. Result := (Val <= $FF) and (Val >= -128);
  15776. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15777. Result := (Val <= $FFFF) and (Val >= -32768);
  15778. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15779. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15780. else
  15781. Result := True;
  15782. end;
  15783. end;
  15784. var
  15785. hp1, hp2 : tai;
  15786. SizeChange: Boolean;
  15787. PreMessage: string;
  15788. begin
  15789. Result := False;
  15790. if (taicpu(p).oper[0]^.typ = top_reg) and
  15791. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15792. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15793. begin
  15794. { Change (using movzbl %al,%eax as an example):
  15795. movzbl %al, %eax movzbl %al, %eax
  15796. cmpl x, %eax testl %eax,%eax
  15797. To:
  15798. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15799. movzbl %al, %eax movzbl %al, %eax
  15800. Smaller instruction and minimises pipeline stall as the CPU
  15801. doesn't have to wait for the register to get zero-extended. [Kit]
  15802. Also allow if the smaller of the two registers is being checked,
  15803. as this still removes the false dependency.
  15804. }
  15805. if
  15806. (
  15807. (
  15808. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15809. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15810. ) or (
  15811. { If MatchOperand returns True, they must both be registers }
  15812. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15813. )
  15814. ) and
  15815. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15816. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15817. begin
  15818. 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);
  15819. asml.Remove(hp1);
  15820. asml.InsertBefore(hp1, p);
  15821. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15822. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15823. begin
  15824. taicpu(hp1).opcode := A_TEST;
  15825. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15826. end;
  15827. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15828. case taicpu(p).opsize of
  15829. S_BW, S_BL:
  15830. begin
  15831. SizeChange := taicpu(hp1).opsize <> S_B;
  15832. taicpu(hp1).changeopsize(S_B);
  15833. end;
  15834. S_WL:
  15835. begin
  15836. SizeChange := taicpu(hp1).opsize <> S_W;
  15837. taicpu(hp1).changeopsize(S_W);
  15838. end
  15839. else
  15840. InternalError(2020112701);
  15841. end;
  15842. UpdateUsedRegs(tai(p.Next));
  15843. { Check if the register is used aferwards - if not, we can
  15844. remove the movzx instruction completely }
  15845. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15846. begin
  15847. { Hp1 is a better position than p for debugging purposes }
  15848. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15849. RemoveCurrentp(p, hp1);
  15850. Result := True;
  15851. end;
  15852. if SizeChange then
  15853. DebugMsg(SPeepholeOptimization + PreMessage +
  15854. 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)
  15855. else
  15856. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15857. Exit;
  15858. end;
  15859. { Change (using movzwl %ax,%eax as an example):
  15860. movzwl %ax, %eax
  15861. movb %al, (dest) (Register is smaller than read register in movz)
  15862. To:
  15863. movb %al, (dest) (Move one back to avoid a false dependency)
  15864. movzwl %ax, %eax
  15865. }
  15866. if (taicpu(hp1).opcode = A_MOV) and
  15867. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15868. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15869. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15870. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15871. begin
  15872. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15873. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15874. asml.Remove(hp1);
  15875. asml.InsertBefore(hp1, p);
  15876. if taicpu(hp1).oper[1]^.typ = top_reg then
  15877. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15878. { Check if the register is used aferwards - if not, we can
  15879. remove the movzx instruction completely }
  15880. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15881. begin
  15882. { Hp1 is a better position than p for debugging purposes }
  15883. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15884. RemoveCurrentp(p, hp1);
  15885. Result := True;
  15886. end;
  15887. Exit;
  15888. end;
  15889. end;
  15890. end;
  15891. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15892. var
  15893. hp1: tai;
  15894. {$ifdef x86_64}
  15895. PreMessage, RegName: string;
  15896. {$endif x86_64}
  15897. begin
  15898. Result := False;
  15899. { If x is a power of 2 (popcnt = 1), change:
  15900. xor $x, %reg/ref
  15901. To:
  15902. btc lb(x), %reg/ref
  15903. }
  15904. if IsBTXAcceptable(p) and
  15905. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15906. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15907. (
  15908. { Don't optimise if a test instruction follows }
  15909. not GetNextInstruction(p, hp1) or
  15910. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15911. ) then
  15912. begin
  15913. 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);
  15914. taicpu(p).opcode := A_BTC;
  15915. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15916. Result := True;
  15917. Exit;
  15918. end;
  15919. {$ifdef x86_64}
  15920. { Code size reduction by J. Gareth "Kit" Moreton }
  15921. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15922. as this removes the REX prefix }
  15923. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15924. Exit;
  15925. if taicpu(p).oper[0]^.typ <> top_reg then
  15926. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15927. InternalError(2018011500);
  15928. case taicpu(p).opsize of
  15929. S_Q:
  15930. begin
  15931. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15932. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15933. { The actual optimization }
  15934. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15935. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15936. taicpu(p).changeopsize(S_L);
  15937. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15938. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15939. end;
  15940. else
  15941. ;
  15942. end;
  15943. {$endif x86_64}
  15944. end;
  15945. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15946. var
  15947. XReg: TRegister;
  15948. begin
  15949. Result := False;
  15950. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15951. Smaller encoding and slightly faster on some platforms (also works for
  15952. ZMM-sized registers) }
  15953. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15954. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15955. begin
  15956. XReg := taicpu(p).oper[0]^.reg;
  15957. if (taicpu(p).oper[1]^.reg = XReg) then
  15958. begin
  15959. taicpu(p).changeopsize(S_XMM);
  15960. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15961. if (cs_opt_size in current_settings.optimizerswitches) then
  15962. begin
  15963. { Change input registers to %xmm0 to reduce size. Note that
  15964. there's a risk of a false dependency doing this, so only
  15965. optimise for size here }
  15966. XReg := NR_XMM0;
  15967. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15968. end
  15969. else
  15970. begin
  15971. setsubreg(XReg, R_SUBMMX);
  15972. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15973. end;
  15974. taicpu(p).oper[0]^.reg := XReg;
  15975. taicpu(p).oper[1]^.reg := XReg;
  15976. Result := True;
  15977. end;
  15978. end;
  15979. end;
  15980. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15981. var
  15982. hp1, p_new: tai;
  15983. begin
  15984. Result := False;
  15985. { Check for:
  15986. ret
  15987. .Lbl:
  15988. ret
  15989. Remove first 'ret'
  15990. }
  15991. if GetNextInstruction(p, hp1) and
  15992. { Remember where the label is }
  15993. SetAndTest(hp1, p_new) and
  15994. (hp1.typ in [ait_align, ait_label]) and
  15995. SkipLabels(hp1, hp1) and
  15996. MatchInstruction(hp1, A_RET, []) and
  15997. { To be safe, make sure the RET instructions are identical }
  15998. (taicpu(p).ops = taicpu(hp1).ops) and
  15999. (
  16000. (taicpu(p).ops = 0) or
  16001. (
  16002. (taicpu(p).ops = 1) and
  16003. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  16004. )
  16005. ) then
  16006. begin
  16007. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  16008. UpdateUsedRegs(tai(p.Next));
  16009. RemoveCurrentP(p, p_new);
  16010. Result := True;
  16011. Exit;
  16012. end;
  16013. end;
  16014. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  16015. var
  16016. OperIdx: Integer;
  16017. begin
  16018. for OperIdx := 0 to p.ops - 1 do
  16019. if p.oper[OperIdx]^.typ = top_ref then
  16020. optimize_ref(p.oper[OperIdx]^.ref^, False);
  16021. end;
  16022. end.