aoptx86.pas 737 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395
  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. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM 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 GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1CMOVcc(var p: tai): Boolean;
  128. function OptPass1_V_MOVAP(var p : tai) : boolean;
  129. function OptPass1VOP(var p : tai) : boolean;
  130. function OptPass1MOV(var p : tai) : boolean;
  131. function OptPass1Movx(var p : tai) : boolean;
  132. function OptPass1MOVXX(var p : tai) : boolean;
  133. function OptPass1OP(var p : tai) : boolean;
  134. function OptPass1LEA(var p : tai) : boolean;
  135. function OptPass1Sub(var p : tai) : boolean;
  136. function OptPass1SHLSAL(var p : tai) : boolean;
  137. function OptPass1SHR(var p : tai) : boolean;
  138. function OptPass1FSTP(var p : tai) : boolean;
  139. function OptPass1FLD(var p : tai) : boolean;
  140. function OptPass1Cmp(var p : tai) : boolean;
  141. function OptPass1PXor(var p : tai) : boolean;
  142. function OptPass1VPXor(var p: tai): boolean;
  143. function OptPass1Imul(var p : tai) : boolean;
  144. function OptPass1Jcc(var p : tai) : boolean;
  145. function OptPass1SHXX(var p: tai): boolean;
  146. function OptPass1VMOVDQ(var p: tai): Boolean;
  147. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  148. function OptPass1STCCLC(var p: tai): Boolean;
  149. function OptPass2STCCLC(var p: tai): Boolean;
  150. function OptPass2CMOVcc(var p: tai): Boolean;
  151. function OptPass2Movx(var p : tai): Boolean;
  152. function OptPass2MOV(var p : tai) : boolean;
  153. function OptPass2Imul(var p : tai) : boolean;
  154. function OptPass2Jmp(var p : tai) : boolean;
  155. function OptPass2Jcc(var p : tai) : boolean;
  156. function OptPass2Lea(var p: tai): Boolean;
  157. function OptPass2SUB(var p: tai): Boolean;
  158. function OptPass2ADD(var p : tai): Boolean;
  159. function OptPass2SETcc(var p : tai) : boolean;
  160. function OptPass2Cmp(var p: tai): Boolean;
  161. function OptPass2Test(var p: tai): Boolean;
  162. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  163. function PostPeepholeOptMov(var p : tai) : Boolean;
  164. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  165. function PostPeepholeOptXor(var p : tai) : Boolean;
  166. function PostPeepholeOptAnd(var p : tai) : boolean;
  167. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  168. function PostPeepholeOptCmp(var p : tai) : Boolean;
  169. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  170. function PostPeepholeOptCall(var p : tai) : Boolean;
  171. function PostPeepholeOptLea(var p : tai) : Boolean;
  172. function PostPeepholeOptPush(var p: tai): Boolean;
  173. function PostPeepholeOptShr(var p : tai) : boolean;
  174. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  175. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  176. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  177. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  178. function TrySwapMovOp(var p, hp1: tai): Boolean;
  179. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  180. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  181. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  182. { Processor-dependent reference optimisation }
  183. class procedure OptimizeRefs(var p: taicpu); static;
  184. end;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  187. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  188. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  189. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  190. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  191. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  192. {$if max_operands>2}
  193. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  194. {$endif max_operands>2}
  195. function RefsEqual(const r1, r2: treference): boolean;
  196. { Note that Result is set to True if the references COULD overlap but the
  197. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  198. might still overlap because %reg2 could be equal to %reg1-4 }
  199. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  200. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  201. { returns true, if ref is a reference using only the registers passed as base and index
  202. and having an offset }
  203. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  204. implementation
  205. uses
  206. cutils,verbose,
  207. systems,
  208. globals,
  209. cpuinfo,
  210. procinfo,
  211. paramgr,
  212. aasmbase,
  213. aoptbase,aoptutils,
  214. symconst,symsym,
  215. cgx86,
  216. itcpugas;
  217. {$ifndef 8086}
  218. const
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. type
  222. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  223. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  224. tsProcessed);
  225. { For OptPass2Jcc }
  226. TCMOVTracking = object
  227. private
  228. CMOVScore, ConstCount: LongInt;
  229. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  230. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  231. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  232. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  233. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  234. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  235. fOptimizer: TX86AsmOptimizer;
  236. fLabel: TAsmSymbol;
  237. fInsertionPoint,
  238. fCondition,
  239. fInitialJump,
  240. fFirstMovBlock,
  241. fFirstMovBlockStop,
  242. fSecondJump,
  243. fThirdJump,
  244. fSecondMovBlock,
  245. fSecondMovBlockStop,
  246. fMidLabel,
  247. fEndLabel,
  248. fAllocationRange: tai;
  249. fState: TCMovTrackingState;
  250. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  251. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  252. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  253. public
  254. RegisterTracking: TAllUsedRegs;
  255. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  256. destructor Done;
  257. procedure Process(out new_p: tai);
  258. property State: TCMovTrackingState read fState;
  259. end;
  260. PCMOVTracking = ^TCMOVTracking;
  261. {$endif 8086}
  262. {$ifdef DEBUG_AOPTCPU}
  263. const
  264. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  265. {$else DEBUG_AOPTCPU}
  266. { Empty strings help the optimizer to remove string concatenations that won't
  267. ever appear to the user on release builds. [Kit] }
  268. const
  269. SPeepholeOptimization = '';
  270. {$endif DEBUG_AOPTCPU}
  271. LIST_STEP_SIZE = 4;
  272. type
  273. TJumpTrackingItem = class(TLinkedListItem)
  274. private
  275. FSymbol: TAsmSymbol;
  276. FRefs: LongInt;
  277. public
  278. constructor Create(ASymbol: TAsmSymbol);
  279. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  280. property Symbol: TAsmSymbol read FSymbol;
  281. property Refs: LongInt read FRefs;
  282. end;
  283. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  284. begin
  285. inherited Create;
  286. FSymbol := ASymbol;
  287. FRefs := 0;
  288. end;
  289. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  290. begin
  291. Inc(FRefs);
  292. end;
  293. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  294. begin
  295. result :=
  296. (instr.typ = ait_instruction) and
  297. (taicpu(instr).opcode = op) and
  298. ((opsize = []) or (taicpu(instr).opsize in opsize));
  299. end;
  300. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. ((taicpu(instr).opcode = op1) or
  305. (taicpu(instr).opcode = op2)
  306. ) and
  307. ((opsize = []) or (taicpu(instr).opsize in opsize));
  308. end;
  309. function MatchInstruction(const instr: tai; const op1,op2,op3: 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) or
  315. (taicpu(instr).opcode = op3)
  316. ) and
  317. ((opsize = []) or (taicpu(instr).opsize in opsize));
  318. end;
  319. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  320. const opsize : topsizes) : boolean;
  321. var
  322. op : TAsmOp;
  323. begin
  324. result:=false;
  325. if (instr.typ <> ait_instruction) or
  326. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  327. exit;
  328. for op in ops do
  329. begin
  330. if taicpu(instr).opcode = op then
  331. begin
  332. result:=true;
  333. exit;
  334. end;
  335. end;
  336. end;
  337. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  338. begin
  339. result := (oper.typ = top_reg) and (oper.reg = reg);
  340. end;
  341. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  342. begin
  343. result := (oper.typ = top_const) and (oper.val = a);
  344. end;
  345. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  346. begin
  347. result := oper1.typ = oper2.typ;
  348. if result then
  349. case oper1.typ of
  350. top_const:
  351. Result:=oper1.val = oper2.val;
  352. top_reg:
  353. Result:=oper1.reg = oper2.reg;
  354. top_ref:
  355. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  356. else
  357. internalerror(2013102801);
  358. end
  359. end;
  360. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  361. begin
  362. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  363. if result then
  364. case oper1.typ of
  365. top_const:
  366. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  367. top_reg:
  368. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  369. top_ref:
  370. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  371. else
  372. internalerror(2020052401);
  373. end
  374. end;
  375. function RefsEqual(const r1, r2: treference): boolean;
  376. begin
  377. RefsEqual :=
  378. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  379. (r1.relsymbol = r2.relsymbol) and
  380. (r1.segment = r2.segment) and (r1.base = r2.base) and
  381. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  382. (r1.offset = r2.offset) and
  383. (r1.volatility + r2.volatility = []);
  384. end;
  385. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  386. begin
  387. if (r1.symbol<>r2.symbol) then
  388. { If the index registers are different, there's a chance one could
  389. be set so it equals the other symbol }
  390. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  391. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  392. (r1.relsymbol = r2.relsymbol) and
  393. (r1.segment = r2.segment) and (r1.base = r2.base) and
  394. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  395. (r1.volatility + r2.volatility = []) then
  396. { In this case, it all depends on the offsets }
  397. Exit(abs(r1.offset - r2.offset) < Range);
  398. { There's a chance things MIGHT overlap, so take no chances }
  399. Result := True;
  400. end;
  401. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  402. begin
  403. Result:=(ref.offset=0) and
  404. (ref.scalefactor in [0,1]) and
  405. (ref.segment=NR_NO) and
  406. (ref.symbol=nil) and
  407. (ref.relsymbol=nil) and
  408. ((base=NR_INVALID) or
  409. (ref.base=base)) and
  410. ((index=NR_INVALID) or
  411. (ref.index=index)) and
  412. (ref.volatility=[]);
  413. end;
  414. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  415. begin
  416. Result:=(ref.scalefactor in [0,1]) and
  417. (ref.segment=NR_NO) and
  418. (ref.symbol=nil) and
  419. (ref.relsymbol=nil) and
  420. ((base=NR_INVALID) or
  421. (ref.base=base)) and
  422. ((index=NR_INVALID) or
  423. (ref.index=index)) and
  424. (ref.volatility=[]);
  425. end;
  426. function InstrReadsFlags(p: tai): boolean;
  427. begin
  428. InstrReadsFlags := true;
  429. case p.typ of
  430. ait_instruction:
  431. if InsProp[taicpu(p).opcode].Ch*
  432. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  433. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  434. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  435. exit;
  436. ait_label:
  437. exit;
  438. else
  439. ;
  440. end;
  441. InstrReadsFlags := false;
  442. end;
  443. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  444. begin
  445. Next:=Current;
  446. repeat
  447. Result:=GetNextInstruction(Next,Next);
  448. until not (Result) or
  449. not(cs_opt_level3 in current_settings.optimizerswitches) or
  450. (Next.typ<>ait_instruction) or
  451. RegInInstruction(reg,Next) or
  452. is_calljmp(taicpu(Next).opcode);
  453. end;
  454. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  455. var
  456. GetNextResult: Boolean;
  457. begin
  458. Result:=0;
  459. Next:=Current;
  460. repeat
  461. GetNextResult := GetNextInstruction(Next,Next);
  462. if GetNextResult then
  463. Inc(Result)
  464. else
  465. { Must return zero upon hitting the end of the linked list without a match }
  466. Result := 0;
  467. until not (GetNextResult) 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.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  474. procedure TrackJump(Symbol: TAsmSymbol);
  475. var
  476. Search: TJumpTrackingItem;
  477. begin
  478. { See if an entry already exists in our jump tracking list
  479. (faster to search backwards due to the higher chance of
  480. matching destinations) }
  481. Search := TJumpTrackingItem(JumpTracking.Last);
  482. while Assigned(Search) do
  483. begin
  484. if Search.Symbol = Symbol then
  485. begin
  486. { Found it - remove it so it can be pushed to the front }
  487. JumpTracking.Remove(Search);
  488. Break;
  489. end;
  490. Search := TJumpTrackingItem(Search.Previous);
  491. end;
  492. if not Assigned(Search) then
  493. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  494. JumpTracking.Concat(Search);
  495. Search.IncRefs;
  496. end;
  497. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  498. var
  499. Search: TJumpTrackingItem;
  500. begin
  501. Result := False;
  502. { See if this label appears in the tracking list }
  503. Search := TJumpTrackingItem(JumpTracking.Last);
  504. while Assigned(Search) do
  505. begin
  506. if Search.Symbol = Symbol then
  507. begin
  508. { Found it - let's see what we can discover }
  509. if Search.Symbol.getrefs = Search.Refs then
  510. begin
  511. { Success - all the references are accounted for }
  512. JumpTracking.Remove(Search);
  513. Search.Free;
  514. { It is logically impossible for CrossJump to be false here
  515. because we must have run into a conditional jump for
  516. this label at some point }
  517. if not CrossJump then
  518. InternalError(2022041710);
  519. if JumpTracking.First = nil then
  520. { Tracking list is now empty - no more cross jumps }
  521. CrossJump := False;
  522. Result := True;
  523. Exit;
  524. end;
  525. { If the references don't match, it's possible to enter
  526. this label through other means, so drop out }
  527. Exit;
  528. end;
  529. Search := TJumpTrackingItem(Search.Previous);
  530. end;
  531. end;
  532. var
  533. Next_Label: tai;
  534. begin
  535. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  536. Next := Current;
  537. repeat
  538. Result := GetNextInstruction(Next,Next);
  539. if not Result then
  540. Break;
  541. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  542. if is_calljmpuncondret(taicpu(Next).opcode) then
  543. begin
  544. if (taicpu(Next).opcode = A_JMP) and
  545. { Remove dead code now to save time }
  546. RemoveDeadCodeAfterJump(taicpu(Next)) then
  547. { A jump was removed, but not the current instruction, and
  548. Result doesn't necessarily translate into an optimisation
  549. routine's Result, so use the "Force New Iteration" flag so
  550. mark a new pass }
  551. Include(OptsToCheck, aoc_ForceNewIteration);
  552. if not Assigned(JumpTracking) then
  553. begin
  554. { Cross-label optimisations often causes other optimisations
  555. to perform worse because they're not given the chance to
  556. optimise locally. In this case, don't do the cross-label
  557. optimisations yet, but flag them as a potential possibility
  558. for the next iteration of Pass 1 }
  559. if not NotFirstIteration then
  560. Include(OptsToCheck, aoc_ForceNewIteration);
  561. end
  562. else if IsJumpToLabel(taicpu(Next)) and
  563. GetNextInstruction(Next, Next_Label) then
  564. begin
  565. { If we have JMP .lbl, and the label after it has all of its
  566. references tracked, then this is probably an if-else style of
  567. block and we can keep tracking. If the label for this jump
  568. then appears later and is fully tracked, then it's the end
  569. of the if-else blocks and the code paths converge (thus
  570. marking the end of the cross-jump) }
  571. if (Next_Label.typ = ait_label) then
  572. begin
  573. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  574. begin
  575. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  576. Next := Next_Label;
  577. { CrossJump gets set to false by LabelAccountedFor if the
  578. list is completely emptied (as it indicates that all
  579. code paths have converged). We could avoid this nuance
  580. by moving the TrackJump call to before the
  581. LabelAccountedFor call, but this is slower in situations
  582. where LabelAccountedFor would return False due to the
  583. creation of a new object that is not used and destroyed
  584. soon after. }
  585. CrossJump := True;
  586. Continue;
  587. end;
  588. end
  589. else if (Next_Label.typ <> ait_marker) then
  590. { We just did a RemoveDeadCodeAfterJump, so either we find
  591. a label, the end of the procedure or some kind of marker}
  592. InternalError(2022041720);
  593. end;
  594. Result := False;
  595. Exit;
  596. end
  597. else
  598. begin
  599. if not Assigned(JumpTracking) then
  600. begin
  601. { Cross-label optimisations often causes other optimisations
  602. to perform worse because they're not given the chance to
  603. optimise locally. In this case, don't do the cross-label
  604. optimisations yet, but flag them as a potential possibility
  605. for the next iteration of Pass 1 }
  606. if not NotFirstIteration then
  607. Include(OptsToCheck, aoc_ForceNewIteration);
  608. end
  609. else if IsJumpToLabel(taicpu(Next)) then
  610. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  611. else
  612. { Conditional jumps should always be a jump to label }
  613. InternalError(2022041701);
  614. CrossJump := True;
  615. Continue;
  616. end;
  617. if Next.typ = ait_label then
  618. begin
  619. if not Assigned(JumpTracking) then
  620. begin
  621. { Cross-label optimisations often causes other optimisations
  622. to perform worse because they're not given the chance to
  623. optimise locally. In this case, don't do the cross-label
  624. optimisations yet, but flag them as a potential possibility
  625. for the next iteration of Pass 1 }
  626. if not NotFirstIteration then
  627. Include(OptsToCheck, aoc_ForceNewIteration);
  628. end
  629. else if LabelAccountedFor(tai_label(Next).labsym) then
  630. Continue;
  631. { If we reach here, we're at a label that hasn't been seen before
  632. (or JumpTracking was nil) }
  633. Break;
  634. end;
  635. until not Result or
  636. not (cs_opt_level3 in current_settings.optimizerswitches) or
  637. not (Next.typ in [ait_label, ait_instruction]) or
  638. RegInInstruction(reg,Next);
  639. end;
  640. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  641. begin
  642. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  643. begin
  644. Result:=GetNextInstruction(Current,Next);
  645. exit;
  646. end;
  647. Next:=tai(Current.Next);
  648. Result:=false;
  649. while assigned(Next) do
  650. begin
  651. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  652. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  653. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  654. exit
  655. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  656. begin
  657. Result:=true;
  658. exit;
  659. end;
  660. Next:=tai(Next.Next);
  661. end;
  662. end;
  663. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  664. begin
  665. Result:=RegReadByInstruction(reg,hp);
  666. end;
  667. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  668. var
  669. p: taicpu;
  670. opcount: longint;
  671. begin
  672. RegReadByInstruction := false;
  673. if hp.typ <> ait_instruction then
  674. exit;
  675. p := taicpu(hp);
  676. case p.opcode of
  677. A_CALL:
  678. regreadbyinstruction := true;
  679. A_IMUL:
  680. case p.ops of
  681. 1:
  682. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  683. (
  684. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  685. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  686. );
  687. 2,3:
  688. regReadByInstruction :=
  689. reginop(reg,p.oper[0]^) or
  690. reginop(reg,p.oper[1]^);
  691. else
  692. InternalError(2019112801);
  693. end;
  694. A_MUL:
  695. begin
  696. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  697. (
  698. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  699. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  700. );
  701. end;
  702. A_IDIV,A_DIV:
  703. begin
  704. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  705. (
  706. (getregtype(reg)=R_INTREGISTER) and
  707. (
  708. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  709. )
  710. );
  711. end;
  712. else
  713. begin
  714. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  715. begin
  716. RegReadByInstruction := false;
  717. exit;
  718. end;
  719. for opcount := 0 to p.ops-1 do
  720. if (p.oper[opCount]^.typ = top_ref) and
  721. RegInRef(reg,p.oper[opcount]^.ref^) then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. { special handling for SSE MOVSD }
  727. if (p.opcode=A_MOVSD) and (p.ops>0) then
  728. begin
  729. if p.ops<>2 then
  730. internalerror(2017042702);
  731. regReadByInstruction := reginop(reg,p.oper[0]^) or
  732. (
  733. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  734. );
  735. exit;
  736. end;
  737. with insprop[p.opcode] do
  738. begin
  739. case getregtype(reg) of
  740. R_INTREGISTER:
  741. begin
  742. case getsupreg(reg) of
  743. RS_EAX:
  744. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  745. begin
  746. RegReadByInstruction := true;
  747. exit
  748. end;
  749. RS_ECX:
  750. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. RS_EDX:
  756. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  757. begin
  758. RegReadByInstruction := true;
  759. exit
  760. end;
  761. RS_EBX:
  762. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ESP:
  768. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EBP:
  774. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_ESI:
  780. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_EDI:
  786. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. end;
  792. end;
  793. R_MMREGISTER:
  794. begin
  795. case getsupreg(reg) of
  796. RS_XMM0:
  797. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. end;
  803. end;
  804. else
  805. ;
  806. end;
  807. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  808. begin
  809. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  810. begin
  811. case p.condition of
  812. C_A,C_NBE, { CF=0 and ZF=0 }
  813. C_BE,C_NA: { CF=1 or ZF=1 }
  814. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  815. C_AE,C_NB,C_NC, { CF=0 }
  816. C_B,C_NAE,C_C: { CF=1 }
  817. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  818. C_NE,C_NZ, { ZF=0 }
  819. C_E,C_Z: { ZF=1 }
  820. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  821. C_G,C_NLE, { ZF=0 and SF=OF }
  822. C_LE,C_NG: { ZF=1 or SF<>OF }
  823. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  824. C_GE,C_NL, { SF=OF }
  825. C_L,C_NGE: { SF<>OF }
  826. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  827. C_NO, { OF=0 }
  828. C_O: { OF=1 }
  829. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  830. C_NP,C_PO, { PF=0 }
  831. C_P,C_PE: { PF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  833. C_NS, { SF=0 }
  834. C_S: { SF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  836. else
  837. internalerror(2017042701);
  838. end;
  839. if RegReadByInstruction then
  840. exit;
  841. end;
  842. case getsubreg(reg) of
  843. R_SUBW,R_SUBD,R_SUBQ:
  844. RegReadByInstruction :=
  845. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  846. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  847. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  848. R_SUBFLAGCARRY:
  849. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGPARITY:
  851. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGAUXILIARY:
  853. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGZERO:
  855. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGSIGN:
  857. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGOVERFLOW:
  859. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGINTERRUPT:
  861. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. R_SUBFLAGDIRECTION:
  863. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  864. else
  865. internalerror(2017042601);
  866. end;
  867. exit;
  868. end;
  869. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  870. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  871. (p.oper[0]^.reg=p.oper[1]^.reg) then
  872. exit;
  873. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  874. begin
  875. RegReadByInstruction := true;
  876. exit
  877. end;
  878. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  879. begin
  880. RegReadByInstruction := true;
  881. exit
  882. end;
  883. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  884. begin
  885. RegReadByInstruction := true;
  886. exit
  887. end;
  888. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  889. begin
  890. RegReadByInstruction := true;
  891. exit
  892. end;
  893. end;
  894. end;
  895. end;
  896. end;
  897. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  898. begin
  899. result:=false;
  900. if p1.typ<>ait_instruction then
  901. exit;
  902. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  903. exit(true);
  904. if (getregtype(reg)=R_INTREGISTER) and
  905. { change information for xmm movsd are not correct }
  906. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  907. begin
  908. { Handle instructions that behave differently depending on the size and operand count }
  909. case taicpu(p1).opcode of
  910. A_MUL, A_DIV, A_IDIV:
  911. if taicpu(p1).opsize = S_B then
  912. Result := (getsupreg(Reg) = RS_EAX)
  913. else
  914. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  915. A_IMUL:
  916. if taicpu(p1).ops = 1 then
  917. begin
  918. if taicpu(p1).opsize = S_B then
  919. Result := (getsupreg(Reg) = RS_EAX)
  920. else
  921. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  922. end;
  923. { If ops are greater than 1, call inherited method }
  924. else
  925. case getsupreg(reg) of
  926. { RS_EAX = RS_RAX on x86-64 }
  927. RS_EAX:
  928. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_ECX:
  930. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EDX:
  932. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_EBX:
  934. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_ESP:
  936. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_EBP:
  938. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_ESI:
  940. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. RS_EDI:
  942. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  943. else
  944. ;
  945. end;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if getregtype(reg)=R_MMREGISTER then
  951. begin
  952. case getsupreg(reg) of
  953. RS_XMM0:
  954. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. else
  956. ;
  957. end;
  958. if result then
  959. exit;
  960. end
  961. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  962. begin
  963. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  964. exit(true);
  965. case getsubreg(reg) of
  966. R_SUBFLAGCARRY:
  967. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGPARITY:
  969. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGAUXILIARY:
  971. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGZERO:
  973. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGSIGN:
  975. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGOVERFLOW:
  977. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGINTERRUPT:
  979. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBFLAGDIRECTION:
  981. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  982. R_SUBW,R_SUBD,R_SUBQ:
  983. { Everything except the direction bits }
  984. Result:=
  985. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  986. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  987. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  988. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  989. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  990. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  991. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. else
  993. ;
  994. end;
  995. if result then
  996. exit;
  997. end
  998. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  999. exit(true);
  1000. Result:=inherited RegInInstruction(Reg, p1);
  1001. end;
  1002. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1003. const
  1004. WriteOps: array[0..3] of set of TInsChange =
  1005. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1006. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1007. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1008. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1009. var
  1010. OperIdx: Integer;
  1011. begin
  1012. Result := False;
  1013. if p1.typ <> ait_instruction then
  1014. exit;
  1015. with insprop[taicpu(p1).opcode] do
  1016. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1017. begin
  1018. case getsubreg(reg) of
  1019. R_SUBW,R_SUBD,R_SUBQ:
  1020. Result :=
  1021. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1022. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1023. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1024. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1025. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1026. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGCARRY:
  1028. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGPARITY:
  1030. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGAUXILIARY:
  1032. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGZERO:
  1034. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGSIGN:
  1036. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGOVERFLOW:
  1038. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGINTERRUPT:
  1040. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. R_SUBFLAGDIRECTION:
  1042. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. else
  1044. internalerror(2017042602);
  1045. end;
  1046. exit;
  1047. end;
  1048. case taicpu(p1).opcode of
  1049. A_CALL:
  1050. { We could potentially set Result to False if the register in
  1051. question is non-volatile for the subroutine's calling convention,
  1052. but this would require detecting the calling convention in use and
  1053. also assuming that the routine doesn't contain malformed assembly
  1054. language, for example... so it could only be done under -O4 as it
  1055. would be considered a side-effect. [Kit] }
  1056. Result := True;
  1057. A_MOVSD:
  1058. { special handling for SSE MOVSD }
  1059. if (taicpu(p1).ops>0) then
  1060. begin
  1061. if taicpu(p1).ops<>2 then
  1062. internalerror(2017042703);
  1063. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1064. end;
  1065. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1066. so fix it here (FK)
  1067. }
  1068. A_VMOVSS,
  1069. A_VMOVSD:
  1070. begin
  1071. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1072. exit;
  1073. end;
  1074. A_MUL, A_DIV, A_IDIV:
  1075. begin
  1076. if taicpu(p1).opsize = S_B then
  1077. Result := (getsupreg(Reg) = RS_EAX)
  1078. else
  1079. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1080. end;
  1081. A_IMUL:
  1082. begin
  1083. if taicpu(p1).ops = 1 then
  1084. begin
  1085. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1086. end
  1087. else
  1088. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1089. Exit;
  1090. end;
  1091. else
  1092. ;
  1093. end;
  1094. if Result then
  1095. exit;
  1096. with insprop[taicpu(p1).opcode] do
  1097. begin
  1098. if getregtype(reg)=R_INTREGISTER then
  1099. begin
  1100. case getsupreg(reg) of
  1101. RS_EAX:
  1102. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1103. begin
  1104. Result := True;
  1105. exit
  1106. end;
  1107. RS_ECX:
  1108. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1109. begin
  1110. Result := True;
  1111. exit
  1112. end;
  1113. RS_EDX:
  1114. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1115. begin
  1116. Result := True;
  1117. exit
  1118. end;
  1119. RS_EBX:
  1120. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ESP:
  1126. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EBP:
  1132. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_ESI:
  1138. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_EDI:
  1144. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. end;
  1150. end;
  1151. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1152. if (WriteOps[OperIdx]*Ch<>[]) and
  1153. { The register doesn't get modified inside a reference }
  1154. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1155. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1156. begin
  1157. Result := true;
  1158. exit
  1159. end;
  1160. end;
  1161. end;
  1162. {$ifdef DEBUG_AOPTCPU}
  1163. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1164. begin
  1165. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1166. end;
  1167. function debug_tostr(i: tcgint): string; inline;
  1168. begin
  1169. Result := tostr(i);
  1170. end;
  1171. function debug_hexstr(i: tcgint): string;
  1172. begin
  1173. Result := '0x';
  1174. case i of
  1175. 0..$FF:
  1176. Result := Result + hexstr(i, 2);
  1177. $100..$FFFF:
  1178. Result := Result + hexstr(i, 4);
  1179. $10000..$FFFFFF:
  1180. Result := Result + hexstr(i, 6);
  1181. $1000000..$FFFFFFFF:
  1182. Result := Result + hexstr(i, 8);
  1183. else
  1184. Result := Result + hexstr(i, 16);
  1185. end;
  1186. end;
  1187. function debug_regname(r: TRegister): string; inline;
  1188. begin
  1189. Result := '%' + std_regname(r);
  1190. end;
  1191. { Debug output function - creates a string representation of an operator }
  1192. function debug_operstr(oper: TOper): string;
  1193. begin
  1194. case oper.typ of
  1195. top_const:
  1196. Result := '$' + debug_tostr(oper.val);
  1197. top_reg:
  1198. Result := debug_regname(oper.reg);
  1199. top_ref:
  1200. begin
  1201. if oper.ref^.offset <> 0 then
  1202. Result := debug_tostr(oper.ref^.offset) + '('
  1203. else
  1204. Result := '(';
  1205. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1206. begin
  1207. Result := Result + debug_regname(oper.ref^.base);
  1208. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1209. Result := Result + ',' + debug_regname(oper.ref^.index);
  1210. end
  1211. else
  1212. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1213. Result := Result + debug_regname(oper.ref^.index);
  1214. if (oper.ref^.scalefactor > 1) then
  1215. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1216. else
  1217. Result := Result + ')';
  1218. end;
  1219. else
  1220. Result := '[UNKNOWN]';
  1221. end;
  1222. end;
  1223. function debug_op2str(opcode: tasmop): string; inline;
  1224. begin
  1225. Result := std_op2str[opcode];
  1226. end;
  1227. function debug_opsize2str(opsize: topsize): string; inline;
  1228. begin
  1229. Result := gas_opsize2str[opsize];
  1230. end;
  1231. {$else DEBUG_AOPTCPU}
  1232. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1233. begin
  1234. end;
  1235. function debug_tostr(i: tcgint): string; inline;
  1236. begin
  1237. Result := '';
  1238. end;
  1239. function debug_hexstr(i: tcgint): string; inline;
  1240. begin
  1241. Result := '';
  1242. end;
  1243. function debug_regname(r: TRegister): string; inline;
  1244. begin
  1245. Result := '';
  1246. end;
  1247. function debug_operstr(oper: TOper): string; inline;
  1248. begin
  1249. Result := '';
  1250. end;
  1251. function debug_op2str(opcode: tasmop): string; inline;
  1252. begin
  1253. Result := '';
  1254. end;
  1255. function debug_opsize2str(opsize: topsize): string; inline;
  1256. begin
  1257. Result := '';
  1258. end;
  1259. {$endif DEBUG_AOPTCPU}
  1260. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1261. begin
  1262. {$ifdef x86_64}
  1263. { Always fine on x86-64 }
  1264. Result := True;
  1265. {$else x86_64}
  1266. Result :=
  1267. {$ifdef i8086}
  1268. (current_settings.cputype >= cpu_386) and
  1269. {$endif i8086}
  1270. (
  1271. { Always accept if optimising for size }
  1272. (cs_opt_size in current_settings.optimizerswitches) or
  1273. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1274. (current_settings.optimizecputype >= cpu_Pentium2)
  1275. );
  1276. {$endif x86_64}
  1277. end;
  1278. { Attempts to allocate a volatile integer register for use between p and hp,
  1279. using AUsedRegs for the current register usage information. Returns NR_NO
  1280. if no free register could be found }
  1281. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1282. var
  1283. RegSet: TCPURegisterSet;
  1284. CurrentSuperReg: Integer;
  1285. CurrentReg: TRegister;
  1286. Currentp: tai;
  1287. Breakout: Boolean;
  1288. begin
  1289. Result := NR_NO;
  1290. RegSet :=
  1291. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1292. current_procinfo.saved_regs_int;
  1293. (*
  1294. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1295. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1296. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1297. *)
  1298. for CurrentSuperReg in RegSet do
  1299. begin
  1300. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1301. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1302. {$if defined(i386) or defined(i8086)}
  1303. { If the target size is 8-bit, make sure we can actually encode it }
  1304. and (
  1305. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1306. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1307. )
  1308. {$endif i386 or i8086}
  1309. then
  1310. begin
  1311. Currentp := p;
  1312. Breakout := False;
  1313. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1314. begin
  1315. case Currentp.typ of
  1316. ait_instruction:
  1317. begin
  1318. if RegInInstruction(CurrentReg, Currentp) then
  1319. begin
  1320. Breakout := True;
  1321. Break;
  1322. end;
  1323. { Cannot allocate across an unconditional jump }
  1324. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1325. Exit;
  1326. end;
  1327. ait_marker:
  1328. { Don't try anything more if a marker is hit }
  1329. Exit;
  1330. ait_regalloc:
  1331. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1332. begin
  1333. Breakout := True;
  1334. Break;
  1335. end;
  1336. else
  1337. ;
  1338. end;
  1339. end;
  1340. if Breakout then
  1341. { Try the next register }
  1342. Continue;
  1343. { We have a free register available }
  1344. Result := CurrentReg;
  1345. if not DontAlloc then
  1346. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1347. Exit;
  1348. end;
  1349. end;
  1350. end;
  1351. { Attempts to allocate a volatile MM register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_mm;
  1366. for CurrentSuperReg in RegSet do
  1367. begin
  1368. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1369. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1370. begin
  1371. Currentp := p;
  1372. Breakout := False;
  1373. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1374. begin
  1375. case Currentp.typ of
  1376. ait_instruction:
  1377. begin
  1378. if RegInInstruction(CurrentReg, Currentp) then
  1379. begin
  1380. Breakout := True;
  1381. Break;
  1382. end;
  1383. { Cannot allocate across an unconditional jump }
  1384. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1385. Exit;
  1386. end;
  1387. ait_marker:
  1388. { Don't try anything more if a marker is hit }
  1389. Exit;
  1390. ait_regalloc:
  1391. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. else
  1397. ;
  1398. end;
  1399. end;
  1400. if Breakout then
  1401. { Try the next register }
  1402. Continue;
  1403. { We have a free register available }
  1404. Result := CurrentReg;
  1405. if not DontAlloc then
  1406. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1407. Exit;
  1408. end;
  1409. end;
  1410. end;
  1411. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1412. begin
  1413. if not SuperRegistersEqual(reg1,reg2) then
  1414. exit(false);
  1415. if getregtype(reg1)<>R_INTREGISTER then
  1416. exit(true); {because SuperRegisterEqual is true}
  1417. case getsubreg(reg1) of
  1418. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1419. higher, it preserves the high bits, so the new value depends on
  1420. reg2's previous value. In other words, it is equivalent to doing:
  1421. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1422. R_SUBL:
  1423. exit(getsubreg(reg2)=R_SUBL);
  1424. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1425. higher, it actually does a:
  1426. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1427. R_SUBH:
  1428. exit(getsubreg(reg2)=R_SUBH);
  1429. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1430. bits of reg2:
  1431. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1432. R_SUBW:
  1433. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1434. { a write to R_SUBD always overwrites every other subregister,
  1435. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1436. R_SUBD,
  1437. R_SUBQ:
  1438. exit(true);
  1439. else
  1440. internalerror(2017042801);
  1441. end;
  1442. end;
  1443. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1444. begin
  1445. if not SuperRegistersEqual(reg1,reg2) then
  1446. exit(false);
  1447. if getregtype(reg1)<>R_INTREGISTER then
  1448. exit(true); {because SuperRegisterEqual is true}
  1449. case getsubreg(reg1) of
  1450. R_SUBL:
  1451. exit(getsubreg(reg2)<>R_SUBH);
  1452. R_SUBH:
  1453. exit(getsubreg(reg2)<>R_SUBL);
  1454. R_SUBW,
  1455. R_SUBD,
  1456. R_SUBQ:
  1457. exit(true);
  1458. else
  1459. internalerror(2017042802);
  1460. end;
  1461. end;
  1462. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1463. var
  1464. hp1 : tai;
  1465. l : TCGInt;
  1466. begin
  1467. result:=false;
  1468. if not(GetNextInstruction(p, hp1)) then
  1469. exit;
  1470. { changes the code sequence
  1471. shr/sar const1, x
  1472. shl const2, x
  1473. to
  1474. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1475. if (taicpu(p).oper[0]^.typ = top_const) and
  1476. MatchInstruction(hp1,A_SHL,[]) and
  1477. (taicpu(hp1).oper[0]^.typ = top_const) and
  1478. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1479. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1480. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1481. begin
  1482. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1483. not(cs_opt_size in current_settings.optimizerswitches) then
  1484. begin
  1485. { shr/sar const1, %reg
  1486. shl const2, %reg
  1487. with const1 > const2 }
  1488. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1489. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1490. taicpu(hp1).opcode := A_AND;
  1491. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1492. case taicpu(p).opsize Of
  1493. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1494. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1495. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1496. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1497. else
  1498. Internalerror(2017050703)
  1499. end;
  1500. end
  1501. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1502. not(cs_opt_size in current_settings.optimizerswitches) then
  1503. begin
  1504. { shr/sar const1, %reg
  1505. shl const2, %reg
  1506. with const1 < const2 }
  1507. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1508. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1509. taicpu(p).opcode := A_AND;
  1510. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1511. case taicpu(p).opsize Of
  1512. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1513. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1514. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1515. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1516. else
  1517. Internalerror(2017050702)
  1518. end;
  1519. end
  1520. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1521. begin
  1522. { shr/sar const1, %reg
  1523. shl const2, %reg
  1524. with const1 = const2 }
  1525. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1526. taicpu(p).opcode := A_AND;
  1527. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1528. case taicpu(p).opsize Of
  1529. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1530. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1531. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1532. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1533. else
  1534. Internalerror(2017050701)
  1535. end;
  1536. RemoveInstruction(hp1);
  1537. end;
  1538. end;
  1539. end;
  1540. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1541. var
  1542. opsize : topsize;
  1543. hp1, hp2 : tai;
  1544. tmpref : treference;
  1545. ShiftValue : Cardinal;
  1546. BaseValue : TCGInt;
  1547. begin
  1548. result:=false;
  1549. opsize:=taicpu(p).opsize;
  1550. { changes certain "imul const, %reg"'s to lea sequences }
  1551. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1552. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1553. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1554. if (taicpu(p).oper[0]^.val = 1) then
  1555. if (taicpu(p).ops = 2) then
  1556. { remove "imul $1, reg" }
  1557. begin
  1558. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1559. Result := RemoveCurrentP(p);
  1560. end
  1561. else
  1562. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1563. begin
  1564. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1565. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1566. asml.InsertAfter(hp1, p);
  1567. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1568. RemoveCurrentP(p, hp1);
  1569. Result := True;
  1570. end
  1571. else if ((taicpu(p).ops <= 2) or
  1572. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) and
  1574. (not(GetNextInstruction(p, hp1)) or
  1575. not((tai(hp1).typ = ait_instruction) and
  1576. ((taicpu(hp1).opcode=A_Jcc) and
  1577. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1578. begin
  1579. {
  1580. imul X, reg1, reg2 to
  1581. lea (reg1,reg1,Y), reg2
  1582. shl ZZ,reg2
  1583. imul XX, reg1 to
  1584. lea (reg1,reg1,YY), reg1
  1585. shl ZZ,reg2
  1586. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1587. it does not exist as a separate optimization target in FPC though.
  1588. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1589. at most two zeros
  1590. }
  1591. reference_reset(tmpref,1,[]);
  1592. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1593. begin
  1594. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1595. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1596. TmpRef.base := taicpu(p).oper[1]^.reg;
  1597. TmpRef.index := taicpu(p).oper[1]^.reg;
  1598. if not(BaseValue in [3,5,9]) then
  1599. Internalerror(2018110101);
  1600. TmpRef.ScaleFactor := BaseValue-1;
  1601. if (taicpu(p).ops = 2) then
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1603. else
  1604. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1605. AsmL.InsertAfter(hp1,p);
  1606. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1607. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1608. RemoveCurrentP(p, hp1);
  1609. if ShiftValue>0 then
  1610. begin
  1611. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1612. AsmL.InsertAfter(hp2,hp1);
  1613. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1614. end;
  1615. Result := True;
  1616. end;
  1617. end;
  1618. end;
  1619. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1620. begin
  1621. Result := False;
  1622. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1623. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1624. begin
  1625. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1626. taicpu(p).opcode := A_MOV;
  1627. Result := True;
  1628. end;
  1629. end;
  1630. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1631. var
  1632. p: taicpu absolute hp; { Implicit typecast }
  1633. i: Integer;
  1634. begin
  1635. Result := False;
  1636. if not assigned(hp) or
  1637. (hp.typ <> ait_instruction) then
  1638. Exit;
  1639. Prefetch(insprop[p.opcode]);
  1640. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1641. with insprop[p.opcode] do
  1642. begin
  1643. case getsubreg(reg) of
  1644. R_SUBW,R_SUBD,R_SUBQ:
  1645. Result:=
  1646. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1647. uncommon flags are checked first }
  1648. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1649. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1652. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1653. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1654. R_SUBFLAGCARRY:
  1655. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGPARITY:
  1657. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGAUXILIARY:
  1659. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGZERO:
  1661. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGSIGN:
  1663. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGOVERFLOW:
  1665. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGINTERRUPT:
  1667. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1668. R_SUBFLAGDIRECTION:
  1669. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1670. else
  1671. internalerror(2017050501);
  1672. end;
  1673. exit;
  1674. end;
  1675. { Handle special cases first }
  1676. case p.opcode of
  1677. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1678. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1679. begin
  1680. Result :=
  1681. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1682. (p.oper[1]^.typ = top_reg) and
  1683. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1684. (
  1685. (p.oper[0]^.typ = top_const) or
  1686. (
  1687. (p.oper[0]^.typ = top_reg) and
  1688. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1689. ) or (
  1690. (p.oper[0]^.typ = top_ref) and
  1691. not RegInRef(reg,p.oper[0]^.ref^)
  1692. )
  1693. );
  1694. end;
  1695. A_MUL, A_IMUL:
  1696. Result :=
  1697. (
  1698. (p.ops=3) and { IMUL only }
  1699. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1700. (
  1701. (
  1702. (p.oper[1]^.typ=top_reg) and
  1703. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1704. ) or (
  1705. (p.oper[1]^.typ=top_ref) and
  1706. not RegInRef(reg,p.oper[1]^.ref^)
  1707. )
  1708. )
  1709. ) or (
  1710. (
  1711. (p.ops=1) and
  1712. (
  1713. (
  1714. (
  1715. (p.oper[0]^.typ=top_reg) and
  1716. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1717. )
  1718. ) or (
  1719. (p.oper[0]^.typ=top_ref) and
  1720. not RegInRef(reg,p.oper[0]^.ref^)
  1721. )
  1722. ) and (
  1723. (
  1724. (p.opsize=S_B) and
  1725. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1726. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1727. ) or (
  1728. (p.opsize=S_W) and
  1729. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1730. ) or (
  1731. (p.opsize=S_L) and
  1732. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1733. {$ifdef x86_64}
  1734. ) or (
  1735. (p.opsize=S_Q) and
  1736. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1737. {$endif x86_64}
  1738. )
  1739. )
  1740. )
  1741. );
  1742. A_CBW:
  1743. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1744. {$ifndef x86_64}
  1745. A_LDS:
  1746. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. A_LES:
  1748. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1749. {$endif not x86_64}
  1750. A_LFS:
  1751. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LGS:
  1753. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LSS:
  1755. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1756. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1758. A_LODSB:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1760. A_LODSW:
  1761. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1762. {$ifdef x86_64}
  1763. A_LODSQ:
  1764. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1765. {$endif x86_64}
  1766. A_LODSD:
  1767. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1768. A_FSTSW, A_FNSTSW:
  1769. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1770. else
  1771. begin
  1772. with insprop[p.opcode] do
  1773. begin
  1774. if (
  1775. { xor %reg,%reg etc. is classed as a new value }
  1776. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1777. MatchOpType(p, top_reg, top_reg) and
  1778. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1779. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1780. ) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. { Make sure the entire register is overwritten }
  1786. if (getregtype(reg) = R_INTREGISTER) then
  1787. begin
  1788. if (p.ops > 0) then
  1789. begin
  1790. if RegInOp(reg, p.oper[0]^) then
  1791. begin
  1792. if (p.oper[0]^.typ = top_ref) then
  1793. begin
  1794. if RegInRef(reg, p.oper[0]^.ref^) then
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end
  1800. else if (p.oper[0]^.typ = top_reg) then
  1801. begin
  1802. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1803. begin
  1804. Result := False;
  1805. Exit;
  1806. end
  1807. else if ([Ch_WOp1]*Ch<>[]) then
  1808. begin
  1809. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1810. Result := True
  1811. else
  1812. begin
  1813. Result := False;
  1814. Exit;
  1815. end;
  1816. end;
  1817. end;
  1818. end;
  1819. if (p.ops > 1) then
  1820. begin
  1821. if RegInOp(reg, p.oper[1]^) then
  1822. begin
  1823. if (p.oper[1]^.typ = top_ref) then
  1824. begin
  1825. if RegInRef(reg, p.oper[1]^.ref^) then
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end
  1831. else if (p.oper[1]^.typ = top_reg) then
  1832. begin
  1833. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1834. begin
  1835. Result := False;
  1836. Exit;
  1837. end
  1838. else if ([Ch_WOp2]*Ch<>[]) then
  1839. begin
  1840. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1841. Result := True
  1842. else
  1843. begin
  1844. Result := False;
  1845. Exit;
  1846. end;
  1847. end;
  1848. end;
  1849. end;
  1850. if (p.ops > 2) then
  1851. begin
  1852. if RegInOp(reg, p.oper[2]^) then
  1853. begin
  1854. if (p.oper[2]^.typ = top_ref) then
  1855. begin
  1856. if RegInRef(reg, p.oper[2]^.ref^) then
  1857. begin
  1858. Result := False;
  1859. Exit;
  1860. end;
  1861. end
  1862. else if (p.oper[2]^.typ = top_reg) then
  1863. begin
  1864. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1865. begin
  1866. Result := False;
  1867. Exit;
  1868. end
  1869. else if ([Ch_WOp3]*Ch<>[]) then
  1870. begin
  1871. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1872. Result := True
  1873. else
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end;
  1878. end;
  1879. end;
  1880. end;
  1881. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1882. begin
  1883. if (p.oper[3]^.typ = top_ref) then
  1884. begin
  1885. if RegInRef(reg, p.oper[3]^.ref^) then
  1886. begin
  1887. Result := False;
  1888. Exit;
  1889. end;
  1890. end
  1891. else if (p.oper[3]^.typ = top_reg) then
  1892. begin
  1893. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1894. begin
  1895. Result := False;
  1896. Exit;
  1897. end
  1898. else if ([Ch_WOp4]*Ch<>[]) then
  1899. begin
  1900. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1901. Result := True
  1902. else
  1903. begin
  1904. Result := False;
  1905. Exit;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1914. case getsupreg(reg) of
  1915. RS_EAX:
  1916. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1917. begin
  1918. Result := True;
  1919. Exit;
  1920. end;
  1921. RS_ECX:
  1922. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1923. begin
  1924. Result := True;
  1925. Exit;
  1926. end;
  1927. RS_EDX:
  1928. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1929. begin
  1930. Result := True;
  1931. Exit;
  1932. end;
  1933. RS_EBX:
  1934. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1935. begin
  1936. Result := True;
  1937. Exit;
  1938. end;
  1939. RS_ESP:
  1940. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1941. begin
  1942. Result := True;
  1943. Exit;
  1944. end;
  1945. RS_EBP:
  1946. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1947. begin
  1948. Result := True;
  1949. Exit;
  1950. end;
  1951. RS_ESI:
  1952. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1953. begin
  1954. Result := True;
  1955. Exit;
  1956. end;
  1957. RS_EDI:
  1958. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1959. begin
  1960. Result := True;
  1961. Exit;
  1962. end;
  1963. else
  1964. ;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. end;
  1970. end;
  1971. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1972. var
  1973. hp2,hp3 : tai;
  1974. begin
  1975. { some x86-64 issue a NOP before the real exit code }
  1976. if MatchInstruction(p,A_NOP,[]) then
  1977. GetNextInstruction(p,p);
  1978. result:=assigned(p) and (p.typ=ait_instruction) and
  1979. ((taicpu(p).opcode = A_RET) or
  1980. ((taicpu(p).opcode=A_LEAVE) and
  1981. GetNextInstruction(p,hp2) and
  1982. MatchInstruction(hp2,A_RET,[S_NO])
  1983. ) or
  1984. (((taicpu(p).opcode=A_LEA) and
  1985. MatchOpType(taicpu(p),top_ref,top_reg) and
  1986. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1987. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1988. ) and
  1989. GetNextInstruction(p,hp2) and
  1990. MatchInstruction(hp2,A_RET,[S_NO])
  1991. ) or
  1992. ((((taicpu(p).opcode=A_MOV) and
  1993. MatchOpType(taicpu(p),top_reg,top_reg) and
  1994. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1995. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1996. ((taicpu(p).opcode=A_LEA) and
  1997. MatchOpType(taicpu(p),top_ref,top_reg) and
  1998. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1999. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2000. )
  2001. ) and
  2002. GetNextInstruction(p,hp2) and
  2003. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2004. MatchOpType(taicpu(hp2),top_reg) and
  2005. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2006. GetNextInstruction(hp2,hp3) and
  2007. MatchInstruction(hp3,A_RET,[S_NO])
  2008. )
  2009. );
  2010. end;
  2011. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2012. begin
  2013. isFoldableArithOp := False;
  2014. case hp1.opcode of
  2015. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2016. isFoldableArithOp :=
  2017. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2018. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2020. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2021. (taicpu(hp1).oper[1]^.reg = reg);
  2022. A_INC,A_DEC,A_NEG,A_NOT:
  2023. isFoldableArithOp :=
  2024. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2025. (taicpu(hp1).oper[0]^.reg = reg);
  2026. else
  2027. ;
  2028. end;
  2029. end;
  2030. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2031. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2032. var
  2033. hp2: tai;
  2034. begin
  2035. hp2 := p;
  2036. repeat
  2037. hp2 := tai(hp2.previous);
  2038. if assigned(hp2) and
  2039. (hp2.typ = ait_regalloc) and
  2040. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2041. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2042. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2043. begin
  2044. RemoveInstruction(hp2);
  2045. break;
  2046. end;
  2047. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2048. end;
  2049. begin
  2050. case current_procinfo.procdef.returndef.typ of
  2051. arraydef,recorddef,pointerdef,
  2052. stringdef,enumdef,procdef,objectdef,errordef,
  2053. filedef,setdef,procvardef,
  2054. classrefdef,forwarddef:
  2055. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2056. orddef:
  2057. if current_procinfo.procdef.returndef.size <> 0 then
  2058. begin
  2059. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2060. { for int64/qword }
  2061. if current_procinfo.procdef.returndef.size = 8 then
  2062. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2063. end;
  2064. else
  2065. ;
  2066. end;
  2067. end;
  2068. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2069. var
  2070. hp1: tai;
  2071. operswap: poper;
  2072. begin
  2073. Result := False;
  2074. { Optimise:
  2075. cmov(c) %reg1,%reg2
  2076. mov %reg2,%reg1
  2077. (%reg2 dealloc.)
  2078. To:
  2079. cmov(~c) %reg2,%reg1
  2080. }
  2081. if (taicpu(p).oper[0]^.typ = top_reg) then
  2082. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2083. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2084. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2085. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2086. begin
  2087. TransferUsedRegs(TmpUsedRegs);
  2088. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2089. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2090. begin
  2091. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2092. { Save time by swapping the pointers (they're both registers, so
  2093. we don't need to worry about reference counts) }
  2094. operswap := taicpu(p).oper[0];
  2095. taicpu(p).oper[0] := taicpu(p).oper[1];
  2096. taicpu(p).oper[1] := operswap;
  2097. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2098. RemoveInstruction(hp1);
  2099. { It's still a CMOV, so we can look further ahead }
  2100. Include(OptsToCheck, aoc_ForceNewIteration);
  2101. { But first, let's see if this will get optimised again
  2102. (probably won't happen, but best to be sure) }
  2103. Continue;
  2104. end;
  2105. Break;
  2106. end;
  2107. end;
  2108. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2109. var
  2110. hp1,hp2 : tai;
  2111. begin
  2112. result:=false;
  2113. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2114. begin
  2115. { vmova* reg1,reg1
  2116. =>
  2117. <nop> }
  2118. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2119. begin
  2120. RemoveCurrentP(p);
  2121. result:=true;
  2122. exit;
  2123. end;
  2124. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2125. (hp1.typ = ait_instruction) and
  2126. (
  2127. { Under -O2 and below, the instructions are always adjacent }
  2128. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2129. (taicpu(hp1).ops <= 1) or
  2130. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2131. { If reg1 = reg3, reg1 must not be modified in between }
  2132. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2133. ) then
  2134. begin
  2135. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2136. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2137. begin
  2138. { vmova* reg1,reg2
  2139. ...
  2140. vmova* reg2,reg3
  2141. dealloc reg2
  2142. =>
  2143. vmova* reg1,reg3 }
  2144. TransferUsedRegs(TmpUsedRegs);
  2145. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2146. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2147. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2148. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2151. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2152. TransferUsedRegs(TmpUsedRegs);
  2153. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2154. RemoveInstruction(hp1);
  2155. result:=true;
  2156. exit;
  2157. end;
  2158. { special case:
  2159. vmova* reg1,<op>
  2160. ...
  2161. vmova* <op>,reg1
  2162. =>
  2163. vmova* reg1,<op> }
  2164. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2165. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2166. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2167. ) then
  2168. begin
  2169. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2170. RemoveInstruction(hp1);
  2171. result:=true;
  2172. exit;
  2173. end
  2174. end
  2175. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2176. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2177. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2178. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2179. ) and
  2180. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2181. begin
  2182. { vmova* reg1,reg2
  2183. ...
  2184. vmovs* reg2,<op>
  2185. dealloc reg2
  2186. =>
  2187. vmovs* reg1,<op> }
  2188. TransferUsedRegs(TmpUsedRegs);
  2189. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2190. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2191. begin
  2192. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2193. taicpu(p).opcode:=taicpu(hp1).opcode;
  2194. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2195. TransferUsedRegs(TmpUsedRegs);
  2196. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2197. RemoveInstruction(hp1);
  2198. result:=true;
  2199. exit;
  2200. end
  2201. end;
  2202. if MatchInstruction(hp1,[A_VFMADDPD,
  2203. A_VFMADD132PD,
  2204. A_VFMADD132PS,
  2205. A_VFMADD132SD,
  2206. A_VFMADD132SS,
  2207. A_VFMADD213PD,
  2208. A_VFMADD213PS,
  2209. A_VFMADD213SD,
  2210. A_VFMADD213SS,
  2211. A_VFMADD231PD,
  2212. A_VFMADD231PS,
  2213. A_VFMADD231SD,
  2214. A_VFMADD231SS,
  2215. A_VFMADDSUB132PD,
  2216. A_VFMADDSUB132PS,
  2217. A_VFMADDSUB213PD,
  2218. A_VFMADDSUB213PS,
  2219. A_VFMADDSUB231PD,
  2220. A_VFMADDSUB231PS,
  2221. A_VFMSUB132PD,
  2222. A_VFMSUB132PS,
  2223. A_VFMSUB132SD,
  2224. A_VFMSUB132SS,
  2225. A_VFMSUB213PD,
  2226. A_VFMSUB213PS,
  2227. A_VFMSUB213SD,
  2228. A_VFMSUB213SS,
  2229. A_VFMSUB231PD,
  2230. A_VFMSUB231PS,
  2231. A_VFMSUB231SD,
  2232. A_VFMSUB231SS,
  2233. A_VFMSUBADD132PD,
  2234. A_VFMSUBADD132PS,
  2235. A_VFMSUBADD213PD,
  2236. A_VFMSUBADD213PS,
  2237. A_VFMSUBADD231PD,
  2238. A_VFMSUBADD231PS,
  2239. A_VFNMADD132PD,
  2240. A_VFNMADD132PS,
  2241. A_VFNMADD132SD,
  2242. A_VFNMADD132SS,
  2243. A_VFNMADD213PD,
  2244. A_VFNMADD213PS,
  2245. A_VFNMADD213SD,
  2246. A_VFNMADD213SS,
  2247. A_VFNMADD231PD,
  2248. A_VFNMADD231PS,
  2249. A_VFNMADD231SD,
  2250. A_VFNMADD231SS,
  2251. A_VFNMSUB132PD,
  2252. A_VFNMSUB132PS,
  2253. A_VFNMSUB132SD,
  2254. A_VFNMSUB132SS,
  2255. A_VFNMSUB213PD,
  2256. A_VFNMSUB213PS,
  2257. A_VFNMSUB213SD,
  2258. A_VFNMSUB213SS,
  2259. A_VFNMSUB231PD,
  2260. A_VFNMSUB231PS,
  2261. A_VFNMSUB231SD,
  2262. A_VFNMSUB231SS],[S_NO]) and
  2263. { we mix single and double opperations here because we assume that the compiler
  2264. generates vmovapd only after double operations and vmovaps only after single operations }
  2265. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2266. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2267. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2268. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2269. begin
  2270. TransferUsedRegs(TmpUsedRegs);
  2271. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2272. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2273. begin
  2274. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2275. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2276. RemoveCurrentP(p)
  2277. else
  2278. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2279. RemoveInstruction(hp2);
  2280. end;
  2281. end
  2282. else if (hp1.typ = ait_instruction) and
  2283. (((taicpu(p).opcode=A_MOVAPS) and
  2284. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2285. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2286. ((taicpu(p).opcode=A_MOVAPD) and
  2287. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2288. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2289. ) and
  2290. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2291. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2292. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2293. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2294. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2295. { change
  2296. movapX reg,reg2
  2297. addsX/subsX/... reg3, reg2
  2298. movapX reg2,reg
  2299. to
  2300. addsX/subsX/... reg3,reg
  2301. }
  2302. begin
  2303. TransferUsedRegs(TmpUsedRegs);
  2304. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2305. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2306. begin
  2307. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2308. debug_op2str(taicpu(p).opcode)+' '+
  2309. debug_op2str(taicpu(hp1).opcode)+' '+
  2310. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2311. { we cannot eliminate the first move if
  2312. the operations uses the same register for source and dest }
  2313. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2314. { Remember that hp1 is not necessarily the immediate
  2315. next instruction }
  2316. RemoveCurrentP(p);
  2317. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2318. RemoveInstruction(hp2);
  2319. result:=true;
  2320. end;
  2321. end
  2322. else if (hp1.typ = ait_instruction) and
  2323. (((taicpu(p).opcode=A_VMOVAPD) and
  2324. (taicpu(hp1).opcode=A_VCOMISD)) or
  2325. ((taicpu(p).opcode=A_VMOVAPS) and
  2326. ((taicpu(hp1).opcode=A_VCOMISS))
  2327. )
  2328. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2329. { change
  2330. movapX reg,reg1
  2331. vcomisX reg1,reg1
  2332. to
  2333. vcomisX reg,reg
  2334. }
  2335. begin
  2336. TransferUsedRegs(TmpUsedRegs);
  2337. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2338. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2339. begin
  2340. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2341. debug_op2str(taicpu(p).opcode)+' '+
  2342. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2343. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2344. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2345. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2346. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2347. RemoveCurrentP(p);
  2348. result:=true;
  2349. exit;
  2350. end;
  2351. end
  2352. end;
  2353. end;
  2354. end;
  2355. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2356. var
  2357. hp1 : tai;
  2358. begin
  2359. result:=false;
  2360. { replace
  2361. V<Op>X %mreg1,%mreg2,%mreg3
  2362. VMovX %mreg3,%mreg4
  2363. dealloc %mreg3
  2364. by
  2365. V<Op>X %mreg1,%mreg2,%mreg4
  2366. ?
  2367. }
  2368. if GetNextInstruction(p,hp1) and
  2369. { we mix single and double operations here because we assume that the compiler
  2370. generates vmovapd only after double operations and vmovaps only after single operations }
  2371. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2372. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2373. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2377. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2378. begin
  2379. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2380. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2381. RemoveInstruction(hp1);
  2382. result:=true;
  2383. end;
  2384. end;
  2385. end;
  2386. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2387. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2388. begin
  2389. Result := False;
  2390. { For safety reasons, only check for exact register matches }
  2391. { Check base register }
  2392. if (ref.base = AOldReg) then
  2393. begin
  2394. ref.base := ANewReg;
  2395. Result := True;
  2396. end;
  2397. { Check index register }
  2398. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2399. begin
  2400. ref.index := ANewReg;
  2401. Result := True;
  2402. end;
  2403. end;
  2404. { Replaces all references to AOldReg in an operand to ANewReg }
  2405. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2406. var
  2407. OldSupReg, NewSupReg: TSuperRegister;
  2408. OldSubReg, NewSubReg: TSubRegister;
  2409. OldRegType: TRegisterType;
  2410. ThisOper: POper;
  2411. begin
  2412. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2413. Result := False;
  2414. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2415. InternalError(2020011801);
  2416. OldSupReg := getsupreg(AOldReg);
  2417. OldSubReg := getsubreg(AOldReg);
  2418. OldRegType := getregtype(AOldReg);
  2419. NewSupReg := getsupreg(ANewReg);
  2420. NewSubReg := getsubreg(ANewReg);
  2421. if OldRegType <> getregtype(ANewReg) then
  2422. InternalError(2020011802);
  2423. if OldSubReg <> NewSubReg then
  2424. InternalError(2020011803);
  2425. case ThisOper^.typ of
  2426. top_reg:
  2427. if (
  2428. (ThisOper^.reg = AOldReg) or
  2429. (
  2430. (OldRegType = R_INTREGISTER) and
  2431. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2432. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2433. (
  2434. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2435. {$ifndef x86_64}
  2436. and (
  2437. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2438. don't have an 8-bit representation }
  2439. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2440. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2441. )
  2442. {$endif x86_64}
  2443. )
  2444. )
  2445. ) then
  2446. begin
  2447. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2448. Result := True;
  2449. end;
  2450. top_ref:
  2451. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2452. Result := True;
  2453. else
  2454. ;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in an instruction to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2459. const
  2460. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2461. var
  2462. OperIdx: Integer;
  2463. begin
  2464. Result := False;
  2465. for OperIdx := 0 to p.ops - 1 do
  2466. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2467. begin
  2468. { The shift and rotate instructions can only use CL }
  2469. if not (
  2470. (OperIdx = 0) and
  2471. { This second condition just helps to avoid unnecessarily
  2472. calling MatchInstruction for 10 different opcodes }
  2473. (p.oper[0]^.reg = NR_CL) and
  2474. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2475. ) then
  2476. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2477. end
  2478. else if p.oper[OperIdx]^.typ = top_ref then
  2479. { It's okay to replace registers in references that get written to }
  2480. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2481. end;
  2482. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2483. begin
  2484. Result :=
  2485. (ref^.index = NR_NO) and
  2486. (
  2487. {$ifdef x86_64}
  2488. (
  2489. (ref^.base = NR_RIP) and
  2490. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2491. ) or
  2492. {$endif x86_64}
  2493. (ref^.refaddr = addr_full) or
  2494. (ref^.base = NR_STACK_POINTER_REG) or
  2495. (ref^.base = current_procinfo.framepointer)
  2496. );
  2497. end;
  2498. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2499. var
  2500. l: asizeint;
  2501. begin
  2502. Result := False;
  2503. { Should have been checked previously }
  2504. if p.opcode <> A_LEA then
  2505. InternalError(2020072501);
  2506. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2507. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2508. not(cs_opt_size in current_settings.optimizerswitches) then
  2509. exit;
  2510. with p.oper[0]^.ref^ do
  2511. begin
  2512. if (base <> p.oper[1]^.reg) or
  2513. (index <> NR_NO) or
  2514. assigned(symbol) then
  2515. exit;
  2516. l:=offset;
  2517. if (l=1) and UseIncDec then
  2518. begin
  2519. p.opcode:=A_INC;
  2520. p.loadreg(0,p.oper[1]^.reg);
  2521. p.ops:=1;
  2522. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2523. end
  2524. else if (l=-1) and UseIncDec then
  2525. begin
  2526. p.opcode:=A_DEC;
  2527. p.loadreg(0,p.oper[1]^.reg);
  2528. p.ops:=1;
  2529. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2530. end
  2531. else
  2532. begin
  2533. if (l<0) and (l<>-2147483648) then
  2534. begin
  2535. p.opcode:=A_SUB;
  2536. p.loadConst(0,-l);
  2537. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2538. end
  2539. else
  2540. begin
  2541. p.opcode:=A_ADD;
  2542. p.loadConst(0,l);
  2543. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2544. end;
  2545. end;
  2546. end;
  2547. Result := True;
  2548. end;
  2549. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2550. var
  2551. CurrentReg, ReplaceReg: TRegister;
  2552. begin
  2553. Result := False;
  2554. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2555. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2556. case hp.opcode of
  2557. A_FSTSW, A_FNSTSW,
  2558. A_IN, A_INS, A_OUT, A_OUTS,
  2559. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2560. { These routines have explicit operands, but they are restricted in
  2561. what they can be (e.g. IN and OUT can only read from AL, AX or
  2562. EAX. }
  2563. Exit;
  2564. A_IMUL:
  2565. begin
  2566. { The 1-operand version writes to implicit registers
  2567. The 2-operand version reads from the first operator, and reads
  2568. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2569. the 3-operand version reads from a register that it doesn't write to
  2570. }
  2571. case hp.ops of
  2572. 1:
  2573. if (
  2574. (
  2575. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2576. ) or
  2577. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2578. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2579. begin
  2580. Result := True;
  2581. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2582. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2583. end;
  2584. 2:
  2585. { Only modify the first parameter }
  2586. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2587. begin
  2588. Result := True;
  2589. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2590. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2591. end;
  2592. 3:
  2593. { Only modify the second parameter }
  2594. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2595. begin
  2596. Result := True;
  2597. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2598. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2599. end;
  2600. else
  2601. InternalError(2020012901);
  2602. end;
  2603. end;
  2604. else
  2605. if (hp.ops > 0) and
  2606. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2607. begin
  2608. Result := True;
  2609. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2610. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2611. end;
  2612. end;
  2613. end;
  2614. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2615. var
  2616. hp2, hp_regalloc: tai;
  2617. p_SourceReg, p_TargetReg: TRegister;
  2618. begin
  2619. Result := False;
  2620. { Backward optimisation. If we have:
  2621. func. %reg1,%reg2
  2622. mov %reg2,%reg3
  2623. (dealloc %reg2)
  2624. Change to:
  2625. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2626. Perform similar optimisations with 1, 3 and 4-operand instructions
  2627. that only have one output.
  2628. }
  2629. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2630. begin
  2631. p_SourceReg := taicpu(p).oper[0]^.reg;
  2632. p_TargetReg := taicpu(p).oper[1]^.reg;
  2633. TransferUsedRegs(TmpUsedRegs);
  2634. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2635. GetLastInstruction(p, hp2) and
  2636. (hp2.typ = ait_instruction) and
  2637. { Have to make sure it's an instruction that only reads from
  2638. the first operands and only writes (not reads or modifies) to
  2639. the last one; in essence, a pure function such as BSR, POPCNT
  2640. or ANDN }
  2641. (
  2642. (
  2643. (taicpu(hp2).ops = 1) and
  2644. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2645. ) or
  2646. (
  2647. (taicpu(hp2).ops = 2) and
  2648. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2649. ) or
  2650. (
  2651. (taicpu(hp2).ops = 3) and
  2652. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2653. ) or
  2654. (
  2655. (taicpu(hp2).ops = 4) and
  2656. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2657. )
  2658. ) and
  2659. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2660. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2661. begin
  2662. case taicpu(hp2).opcode of
  2663. A_FSTSW, A_FNSTSW,
  2664. A_IN, A_INS, A_OUT, A_OUTS,
  2665. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2666. { These routines have explicit operands, but they are restricted in
  2667. what they can be (e.g. IN and OUT can only read from AL, AX or
  2668. EAX. }
  2669. ;
  2670. else
  2671. begin
  2672. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2673. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2674. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2675. if Assigned(hp_regalloc) then
  2676. begin
  2677. Asml.Remove(hp_regalloc);
  2678. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2679. begin
  2680. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2681. hp_regalloc.Free;
  2682. end
  2683. else
  2684. { If the register is not explicitly deallocated, it's
  2685. being reused, so move the allocation to after func. }
  2686. AsmL.InsertAfter(hp_regalloc, hp2);
  2687. end;
  2688. if not RegInInstruction(p_TargetReg, hp2) then
  2689. begin
  2690. TransferUsedRegs(TmpUsedRegs);
  2691. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2692. end;
  2693. { Actually make the changes }
  2694. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2695. RemoveCurrentp(p, hp1);
  2696. { If the Func was another MOV instruction, we might get
  2697. "mov %reg,%reg" that doesn't get removed in Pass 2
  2698. otherwise, so deal with it here (also do something
  2699. similar with lea (%reg),%reg}
  2700. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2701. begin
  2702. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2703. if p = hp2 then
  2704. RemoveCurrentp(p)
  2705. else
  2706. RemoveInstruction(hp2);
  2707. end;
  2708. Result := True;
  2709. Exit;
  2710. end;
  2711. end;
  2712. end;
  2713. end;
  2714. end;
  2715. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2716. begin
  2717. Result := False;
  2718. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2719. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2720. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2721. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2722. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2723. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2724. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2725. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2726. begin
  2727. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2728. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2729. Result := True;
  2730. end;
  2731. end;
  2732. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2733. var
  2734. hp1, hp2, hp3, hp4: tai;
  2735. DoOptimisation, TempBool: Boolean;
  2736. {$ifdef x86_64}
  2737. NewConst: TCGInt;
  2738. {$endif x86_64}
  2739. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2740. begin
  2741. if taicpu(hp1).opcode = signed_movop then
  2742. begin
  2743. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2744. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2745. end
  2746. else
  2747. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2748. end;
  2749. function TryConstMerge(var p1, p2: tai): Boolean;
  2750. var
  2751. ThisRef: TReference;
  2752. begin
  2753. Result := False;
  2754. ThisRef := taicpu(p2).oper[1]^.ref^;
  2755. { Only permit writes to the stack, since we can guarantee alignment with that }
  2756. if (ThisRef.index = NR_NO) and
  2757. (
  2758. (ThisRef.base = NR_STACK_POINTER_REG) or
  2759. (ThisRef.base = current_procinfo.framepointer)
  2760. ) then
  2761. begin
  2762. case taicpu(p).opsize of
  2763. S_B:
  2764. begin
  2765. { Word writes must be on a 2-byte boundary }
  2766. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2767. begin
  2768. { Reduce offset of second reference to see if it is sequential with the first }
  2769. Dec(ThisRef.offset, 1);
  2770. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2771. begin
  2772. { Make sure the constants aren't represented as a
  2773. negative number, as these won't merge properly }
  2774. taicpu(p1).opsize := S_W;
  2775. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2776. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2777. RemoveInstruction(p2);
  2778. Result := True;
  2779. end;
  2780. end;
  2781. end;
  2782. S_W:
  2783. begin
  2784. { Longword writes must be on a 4-byte boundary }
  2785. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2786. begin
  2787. { Reduce offset of second reference to see if it is sequential with the first }
  2788. Dec(ThisRef.offset, 2);
  2789. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2790. begin
  2791. { Make sure the constants aren't represented as a
  2792. negative number, as these won't merge properly }
  2793. taicpu(p1).opsize := S_L;
  2794. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2795. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2796. RemoveInstruction(p2);
  2797. Result := True;
  2798. end;
  2799. end;
  2800. end;
  2801. {$ifdef x86_64}
  2802. S_L:
  2803. begin
  2804. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2805. see if the constants can be encoded this way. }
  2806. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2807. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2808. { Quadword writes must be on an 8-byte boundary }
  2809. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2810. begin
  2811. { Reduce offset of second reference to see if it is sequential with the first }
  2812. Dec(ThisRef.offset, 4);
  2813. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2814. begin
  2815. { Make sure the constants aren't represented as a
  2816. negative number, as these won't merge properly }
  2817. taicpu(p1).opsize := S_Q;
  2818. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2819. taicpu(p1).oper[0]^.val := NewConst;
  2820. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2821. RemoveInstruction(p2);
  2822. Result := True;
  2823. end;
  2824. end;
  2825. end;
  2826. {$endif x86_64}
  2827. else
  2828. ;
  2829. end;
  2830. end;
  2831. end;
  2832. var
  2833. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2834. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2835. NewSize: topsize; NewOffset: asizeint;
  2836. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2837. SourceRef, TargetRef: TReference;
  2838. MovAligned, MovUnaligned: TAsmOp;
  2839. ThisRef: TReference;
  2840. JumpTracking: TLinkedList;
  2841. begin
  2842. Result:=false;
  2843. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2844. { remove mov reg1,reg1? }
  2845. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2846. then
  2847. begin
  2848. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2849. { take care of the register (de)allocs following p }
  2850. RemoveCurrentP(p, hp1);
  2851. Result:=true;
  2852. exit;
  2853. end;
  2854. { All the next optimisations require a next instruction }
  2855. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2856. Exit;
  2857. { Prevent compiler warnings }
  2858. p_TargetReg := NR_NO;
  2859. if taicpu(p).oper[1]^.typ = top_reg then
  2860. begin
  2861. { Saves on a large number of dereferences }
  2862. p_TargetReg := taicpu(p).oper[1]^.reg;
  2863. { Look for:
  2864. mov %reg1,%reg2
  2865. ??? %reg2,r/m
  2866. Change to:
  2867. mov %reg1,%reg2
  2868. ??? %reg1,r/m
  2869. }
  2870. if taicpu(p).oper[0]^.typ = top_reg then
  2871. begin
  2872. if RegReadByInstruction(p_TargetReg, hp1) and
  2873. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2874. begin
  2875. { A change has occurred, just not in p }
  2876. Result := True;
  2877. TransferUsedRegs(TmpUsedRegs);
  2878. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2879. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2880. { Just in case something didn't get modified (e.g. an
  2881. implicit register) }
  2882. not RegReadByInstruction(p_TargetReg, hp1) then
  2883. begin
  2884. { We can remove the original MOV }
  2885. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2886. RemoveCurrentp(p, hp1);
  2887. { UsedRegs got updated by RemoveCurrentp }
  2888. Result := True;
  2889. Exit;
  2890. end;
  2891. { If we know a MOV instruction has become a null operation, we might as well
  2892. get rid of it now to save time. }
  2893. if (taicpu(hp1).opcode = A_MOV) and
  2894. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2895. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2896. { Just being a register is enough to confirm it's a null operation }
  2897. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2898. begin
  2899. Result := True;
  2900. { Speed-up to reduce a pipeline stall... if we had something like...
  2901. movl %eax,%edx
  2902. movw %dx,%ax
  2903. ... the second instruction would change to movw %ax,%ax, but
  2904. given that it is now %ax that's active rather than %eax,
  2905. penalties might occur due to a partial register write, so instead,
  2906. change it to a MOVZX instruction when optimising for speed.
  2907. }
  2908. if not (cs_opt_size in current_settings.optimizerswitches) and
  2909. IsMOVZXAcceptable and
  2910. (taicpu(hp1).opsize < taicpu(p).opsize)
  2911. {$ifdef x86_64}
  2912. { operations already implicitly set the upper 64 bits to zero }
  2913. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2914. {$endif x86_64}
  2915. then
  2916. begin
  2917. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2918. case taicpu(p).opsize of
  2919. S_W:
  2920. if taicpu(hp1).opsize = S_B then
  2921. taicpu(hp1).opsize := S_BL
  2922. else
  2923. InternalError(2020012911);
  2924. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2925. case taicpu(hp1).opsize of
  2926. S_B:
  2927. taicpu(hp1).opsize := S_BL;
  2928. S_W:
  2929. taicpu(hp1).opsize := S_WL;
  2930. else
  2931. InternalError(2020012912);
  2932. end;
  2933. else
  2934. InternalError(2020012910);
  2935. end;
  2936. taicpu(hp1).opcode := A_MOVZX;
  2937. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2938. end
  2939. else
  2940. begin
  2941. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2942. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2943. RemoveInstruction(hp1);
  2944. { The instruction after what was hp1 is now the immediate next instruction,
  2945. so we can continue to make optimisations if it's present }
  2946. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2947. Exit;
  2948. hp1 := hp2;
  2949. end;
  2950. end;
  2951. end;
  2952. end;
  2953. end;
  2954. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2955. overwrites the original destination register. e.g.
  2956. movl ###,%reg2d
  2957. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2958. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2959. }
  2960. if (taicpu(p).oper[1]^.typ = top_reg) and
  2961. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2962. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2963. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2964. begin
  2965. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2966. begin
  2967. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2968. case taicpu(p).oper[0]^.typ of
  2969. top_const:
  2970. { We have something like:
  2971. movb $x, %regb
  2972. movzbl %regb,%regd
  2973. Change to:
  2974. movl $x, %regd
  2975. }
  2976. begin
  2977. case taicpu(hp1).opsize of
  2978. S_BW:
  2979. begin
  2980. convert_mov_value(A_MOVSX, $FF);
  2981. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2982. taicpu(p).opsize := S_W;
  2983. end;
  2984. S_BL:
  2985. begin
  2986. convert_mov_value(A_MOVSX, $FF);
  2987. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2988. taicpu(p).opsize := S_L;
  2989. end;
  2990. S_WL:
  2991. begin
  2992. convert_mov_value(A_MOVSX, $FFFF);
  2993. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2994. taicpu(p).opsize := S_L;
  2995. end;
  2996. {$ifdef x86_64}
  2997. S_BQ:
  2998. begin
  2999. convert_mov_value(A_MOVSX, $FF);
  3000. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3001. taicpu(p).opsize := S_Q;
  3002. end;
  3003. S_WQ:
  3004. begin
  3005. convert_mov_value(A_MOVSX, $FFFF);
  3006. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3007. taicpu(p).opsize := S_Q;
  3008. end;
  3009. S_LQ:
  3010. begin
  3011. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3012. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3013. taicpu(p).opsize := S_Q;
  3014. end;
  3015. {$endif x86_64}
  3016. else
  3017. { If hp1 was a MOV instruction, it should have been
  3018. optimised already }
  3019. InternalError(2020021001);
  3020. end;
  3021. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3022. RemoveInstruction(hp1);
  3023. Result := True;
  3024. Exit;
  3025. end;
  3026. top_ref:
  3027. begin
  3028. { We have something like:
  3029. movb mem, %regb
  3030. movzbl %regb,%regd
  3031. Change to:
  3032. movzbl mem, %regd
  3033. }
  3034. ThisRef := taicpu(p).oper[0]^.ref^;
  3035. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3036. begin
  3037. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3038. taicpu(hp1).loadref(0, ThisRef);
  3039. { Make sure any registers in the references are properly tracked }
  3040. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  3041. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  3042. if (ThisRef.index <> NR_NO) then
  3043. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  3044. RemoveCurrentP(p, hp1);
  3045. Result := True;
  3046. Exit;
  3047. end;
  3048. end;
  3049. else
  3050. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3051. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3052. Exit;
  3053. end;
  3054. end
  3055. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3056. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3057. optimised }
  3058. else
  3059. begin
  3060. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3061. RemoveCurrentP(p, hp1);
  3062. Result := True;
  3063. Exit;
  3064. end;
  3065. end;
  3066. if (taicpu(hp1).opcode = A_AND) and
  3067. (taicpu(p).oper[1]^.typ = top_reg) and
  3068. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3069. begin
  3070. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3071. begin
  3072. case taicpu(p).opsize of
  3073. S_L:
  3074. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3075. begin
  3076. { Optimize out:
  3077. mov x, %reg
  3078. and ffffffffh, %reg
  3079. }
  3080. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3081. RemoveInstruction(hp1);
  3082. Result:=true;
  3083. exit;
  3084. end;
  3085. S_Q: { TODO: Confirm if this is even possible }
  3086. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3087. begin
  3088. { Optimize out:
  3089. mov x, %reg
  3090. and ffffffffffffffffh, %reg
  3091. }
  3092. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3093. RemoveInstruction(hp1);
  3094. Result:=true;
  3095. exit;
  3096. end;
  3097. else
  3098. ;
  3099. end;
  3100. if (
  3101. (taicpu(p).oper[0]^.typ=top_reg) or
  3102. (
  3103. (taicpu(p).oper[0]^.typ=top_ref) and
  3104. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3105. )
  3106. ) and
  3107. GetNextInstruction(hp1,hp2) and
  3108. MatchInstruction(hp2,A_TEST,[]) and
  3109. (
  3110. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3111. (
  3112. { If the register being tested is smaller than the one
  3113. that received a bitwise AND, permit it if the constant
  3114. fits into the smaller size }
  3115. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3116. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3117. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3118. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3119. (
  3120. (
  3121. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3122. (taicpu(hp1).oper[0]^.val <= $FF)
  3123. ) or
  3124. (
  3125. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3126. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3127. {$ifdef x86_64}
  3128. ) or
  3129. (
  3130. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3131. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3132. {$endif x86_64}
  3133. )
  3134. )
  3135. )
  3136. ) and
  3137. (
  3138. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3139. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3140. ) and
  3141. GetNextInstruction(hp2,hp3) and
  3142. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3143. (taicpu(hp3).condition in [C_E,C_NE]) then
  3144. begin
  3145. TransferUsedRegs(TmpUsedRegs);
  3146. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3147. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3148. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3149. begin
  3150. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3151. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3152. taicpu(hp1).opcode:=A_TEST;
  3153. { Shrink the TEST instruction down to the smallest possible size }
  3154. case taicpu(hp1).oper[0]^.val of
  3155. 0..255:
  3156. if (taicpu(hp1).opsize <> S_B)
  3157. {$ifndef x86_64}
  3158. and (
  3159. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3160. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3161. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3162. )
  3163. {$endif x86_64}
  3164. then
  3165. begin
  3166. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3167. { Only print debug message if the TEST instruction
  3168. is a different size before and after }
  3169. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3170. taicpu(hp1).opsize := S_B;
  3171. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3172. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3173. end;
  3174. 256..65535:
  3175. if (taicpu(hp1).opsize <> S_W) then
  3176. begin
  3177. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3178. { Only print debug message if the TEST instruction
  3179. is a different size before and after }
  3180. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3181. taicpu(hp1).opsize := S_W;
  3182. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3183. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3184. end;
  3185. {$ifdef x86_64}
  3186. 65536..$7FFFFFFF:
  3187. if (taicpu(hp1).opsize <> S_L) then
  3188. begin
  3189. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3190. { Only print debug message if the TEST instruction
  3191. is a different size before and after }
  3192. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3193. taicpu(hp1).opsize := S_L;
  3194. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3195. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3196. end;
  3197. {$endif x86_64}
  3198. else
  3199. ;
  3200. end;
  3201. RemoveInstruction(hp2);
  3202. RemoveCurrentP(p, hp1);
  3203. Result:=true;
  3204. exit;
  3205. end;
  3206. end;
  3207. end
  3208. else if IsMOVZXAcceptable and
  3209. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3210. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3211. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3212. then
  3213. begin
  3214. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3215. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3216. case taicpu(p).opsize of
  3217. S_B:
  3218. if (taicpu(hp1).oper[0]^.val = $ff) then
  3219. begin
  3220. { Convert:
  3221. movb x, %regl movb x, %regl
  3222. andw ffh, %regw andl ffh, %regd
  3223. To:
  3224. movzbw x, %regd movzbl x, %regd
  3225. (Identical registers, just different sizes)
  3226. }
  3227. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3228. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3229. case taicpu(hp1).opsize of
  3230. S_W: NewSize := S_BW;
  3231. S_L: NewSize := S_BL;
  3232. {$ifdef x86_64}
  3233. S_Q: NewSize := S_BQ;
  3234. {$endif x86_64}
  3235. else
  3236. InternalError(2018011510);
  3237. end;
  3238. end
  3239. else
  3240. NewSize := S_NO;
  3241. S_W:
  3242. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3243. begin
  3244. { Convert:
  3245. movw x, %regw
  3246. andl ffffh, %regd
  3247. To:
  3248. movzwl x, %regd
  3249. (Identical registers, just different sizes)
  3250. }
  3251. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3252. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3253. case taicpu(hp1).opsize of
  3254. S_L: NewSize := S_WL;
  3255. {$ifdef x86_64}
  3256. S_Q: NewSize := S_WQ;
  3257. {$endif x86_64}
  3258. else
  3259. InternalError(2018011511);
  3260. end;
  3261. end
  3262. else
  3263. NewSize := S_NO;
  3264. else
  3265. NewSize := S_NO;
  3266. end;
  3267. if NewSize <> S_NO then
  3268. begin
  3269. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3270. { The actual optimization }
  3271. taicpu(p).opcode := A_MOVZX;
  3272. taicpu(p).changeopsize(NewSize);
  3273. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3274. { Safeguard if "and" is followed by a conditional command }
  3275. TransferUsedRegs(TmpUsedRegs);
  3276. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3277. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3278. begin
  3279. { At this point, the "and" command is effectively equivalent to
  3280. "test %reg,%reg". This will be handled separately by the
  3281. Peephole Optimizer. [Kit] }
  3282. DebugMsg(SPeepholeOptimization + PreMessage +
  3283. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3284. end
  3285. else
  3286. begin
  3287. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3288. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3289. RemoveInstruction(hp1);
  3290. end;
  3291. Result := True;
  3292. Exit;
  3293. end;
  3294. end;
  3295. end;
  3296. if (taicpu(hp1).opcode = A_OR) and
  3297. (taicpu(p).oper[1]^.typ = top_reg) and
  3298. MatchOperand(taicpu(p).oper[0]^, 0) and
  3299. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3300. begin
  3301. { mov 0, %reg
  3302. or ###,%reg
  3303. Change to (only if the flags are not used):
  3304. mov ###,%reg
  3305. }
  3306. TransferUsedRegs(TmpUsedRegs);
  3307. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3308. DoOptimisation := True;
  3309. { Even if the flags are used, we might be able to do the optimisation
  3310. if the conditions are predictable }
  3311. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3312. begin
  3313. { Only perform if ### = %reg (the same register) or equal to 0,
  3314. so %reg is guaranteed to still have a value of zero }
  3315. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3316. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3317. begin
  3318. hp2 := hp1;
  3319. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3320. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3321. GetNextInstruction(hp2, hp3) do
  3322. begin
  3323. { Don't continue modifying if the flags state is getting changed }
  3324. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3325. Break;
  3326. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3327. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3328. begin
  3329. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3330. begin
  3331. { Condition is always true }
  3332. case taicpu(hp3).opcode of
  3333. A_Jcc:
  3334. begin
  3335. { Check for jump shortcuts before we destroy the condition }
  3336. hp4 := hp3;
  3337. DoJumpOptimizations(hp3, TempBool);
  3338. { Make sure hp3 hasn't changed }
  3339. if (hp4 = hp3) then
  3340. begin
  3341. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3342. MakeUnconditional(taicpu(hp3));
  3343. end;
  3344. Result := True;
  3345. end;
  3346. A_CMOVcc:
  3347. begin
  3348. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3349. taicpu(hp3).opcode := A_MOV;
  3350. taicpu(hp3).condition := C_None;
  3351. Result := True;
  3352. end;
  3353. A_SETcc:
  3354. begin
  3355. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3356. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3357. taicpu(hp3).opcode := A_MOV;
  3358. taicpu(hp3).ops := 2;
  3359. taicpu(hp3).condition := C_None;
  3360. taicpu(hp3).opsize := S_B;
  3361. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3362. taicpu(hp3).loadconst(0, 1);
  3363. Result := True;
  3364. end;
  3365. else
  3366. InternalError(2021090701);
  3367. end;
  3368. end
  3369. 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
  3370. begin
  3371. { Condition is always false }
  3372. case taicpu(hp3).opcode of
  3373. A_Jcc:
  3374. begin
  3375. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3376. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3377. RemoveInstruction(hp3);
  3378. Result := True;
  3379. { Since hp3 was deleted, hp2 must not be updated }
  3380. Continue;
  3381. end;
  3382. A_CMOVcc:
  3383. begin
  3384. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3385. RemoveInstruction(hp3);
  3386. Result := True;
  3387. { Since hp3 was deleted, hp2 must not be updated }
  3388. Continue;
  3389. end;
  3390. A_SETcc:
  3391. begin
  3392. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3393. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3394. taicpu(hp3).opcode := A_MOV;
  3395. taicpu(hp3).ops := 2;
  3396. taicpu(hp3).condition := C_None;
  3397. taicpu(hp3).opsize := S_B;
  3398. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3399. taicpu(hp3).loadconst(0, 0);
  3400. Result := True;
  3401. end;
  3402. else
  3403. InternalError(2021090702);
  3404. end;
  3405. end
  3406. else
  3407. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3408. DoOptimisation := False;
  3409. end;
  3410. hp2 := hp3;
  3411. end;
  3412. { Flags are still in use - don't optimise }
  3413. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3414. DoOptimisation := False;
  3415. end
  3416. else
  3417. DoOptimisation := False;
  3418. end;
  3419. if DoOptimisation then
  3420. begin
  3421. {$ifdef x86_64}
  3422. { OR only supports 32-bit sign-extended constants for 64-bit
  3423. instructions, so compensate for this if the constant is
  3424. encoded as a value greater than or equal to 2^31 }
  3425. if (taicpu(hp1).opsize = S_Q) and
  3426. (taicpu(hp1).oper[0]^.typ = top_const) and
  3427. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3428. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3429. {$endif x86_64}
  3430. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3431. taicpu(hp1).opcode := A_MOV;
  3432. RemoveCurrentP(p, hp1);
  3433. Result := True;
  3434. Exit;
  3435. end;
  3436. end;
  3437. { Next instruction is also a MOV ? }
  3438. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3439. begin
  3440. if MatchOpType(taicpu(p), top_const, top_ref) and
  3441. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3442. TryConstMerge(p, hp1) then
  3443. begin
  3444. Result := True;
  3445. { In case we have four byte writes in a row, check for 2 more
  3446. right now so we don't have to wait for another iteration of
  3447. pass 1
  3448. }
  3449. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3450. case taicpu(p).opsize of
  3451. S_W:
  3452. begin
  3453. if GetNextInstruction(p, hp1) and
  3454. MatchInstruction(hp1, A_MOV, [S_B]) and
  3455. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3456. GetNextInstruction(hp1, hp2) and
  3457. MatchInstruction(hp2, A_MOV, [S_B]) and
  3458. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3459. { Try to merge the two bytes }
  3460. TryConstMerge(hp1, hp2) then
  3461. { Now try to merge the two words (hp2 will get deleted) }
  3462. TryConstMerge(p, hp1);
  3463. end;
  3464. S_L:
  3465. begin
  3466. { Though this only really benefits x86_64 and not i386, it
  3467. gets a potential optimisation done faster and hence
  3468. reduces the number of times OptPass1MOV is entered }
  3469. if GetNextInstruction(p, hp1) and
  3470. MatchInstruction(hp1, A_MOV, [S_W]) and
  3471. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3472. GetNextInstruction(hp1, hp2) and
  3473. MatchInstruction(hp2, A_MOV, [S_W]) and
  3474. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3475. { Try to merge the two words }
  3476. TryConstMerge(hp1, hp2) then
  3477. { This will always fail on i386, so don't bother
  3478. calling it unless we're doing x86_64 }
  3479. {$ifdef x86_64}
  3480. { Now try to merge the two longwords (hp2 will get deleted) }
  3481. TryConstMerge(p, hp1)
  3482. {$endif x86_64}
  3483. ;
  3484. end;
  3485. else
  3486. ;
  3487. end;
  3488. Exit;
  3489. end;
  3490. if (taicpu(p).oper[1]^.typ = top_reg) and
  3491. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3492. begin
  3493. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3494. TransferUsedRegs(TmpUsedRegs);
  3495. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3496. { we have
  3497. mov x, %treg
  3498. mov %treg, y
  3499. }
  3500. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3501. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3502. { we've got
  3503. mov x, %treg
  3504. mov %treg, y
  3505. with %treg is not used after }
  3506. case taicpu(p).oper[0]^.typ Of
  3507. { top_reg is covered by DeepMOVOpt }
  3508. top_const:
  3509. begin
  3510. { change
  3511. mov const, %treg
  3512. mov %treg, y
  3513. to
  3514. mov const, y
  3515. }
  3516. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3517. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3518. begin
  3519. if taicpu(hp1).oper[1]^.typ=top_reg then
  3520. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3521. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3522. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3523. RemoveInstruction(hp1);
  3524. Result:=true;
  3525. Exit;
  3526. end;
  3527. end;
  3528. top_ref:
  3529. case taicpu(hp1).oper[1]^.typ of
  3530. top_reg:
  3531. begin
  3532. { change
  3533. mov mem, %treg
  3534. mov %treg, %reg
  3535. to
  3536. mov mem, %reg"
  3537. }
  3538. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3539. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3540. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3541. RemoveInstruction(hp1);
  3542. Result:=true;
  3543. Exit;
  3544. end;
  3545. top_ref:
  3546. begin
  3547. {$ifdef x86_64}
  3548. { Look for the following to simplify:
  3549. mov x(mem1), %reg
  3550. mov %reg, y(mem2)
  3551. mov x+8(mem1), %reg
  3552. mov %reg, y+8(mem2)
  3553. Change to:
  3554. movdqu x(mem1), %xmmreg
  3555. movdqu %xmmreg, y(mem2)
  3556. ...but only as long as the memory blocks don't overlap
  3557. }
  3558. SourceRef := taicpu(p).oper[0]^.ref^;
  3559. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3560. if (taicpu(p).opsize = S_Q) and
  3561. GetNextInstruction(hp1, hp2) and
  3562. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3563. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3564. begin
  3565. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3566. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3567. Inc(SourceRef.offset, 8);
  3568. if UseAVX then
  3569. begin
  3570. MovAligned := A_VMOVDQA;
  3571. MovUnaligned := A_VMOVDQU;
  3572. end
  3573. else
  3574. begin
  3575. MovAligned := A_MOVDQA;
  3576. MovUnaligned := A_MOVDQU;
  3577. end;
  3578. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3579. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3580. begin
  3581. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3582. Inc(TargetRef.offset, 8);
  3583. if GetNextInstruction(hp2, hp3) and
  3584. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3585. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3586. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3587. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3588. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3589. begin
  3590. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3591. if NewMMReg <> NR_NO then
  3592. begin
  3593. { Remember that the offsets are 8 ahead }
  3594. if ((SourceRef.offset mod 16) = 8) and
  3595. (
  3596. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3597. (SourceRef.base = current_procinfo.framepointer) or
  3598. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3599. ) then
  3600. taicpu(p).opcode := MovAligned
  3601. else
  3602. taicpu(p).opcode := MovUnaligned;
  3603. taicpu(p).opsize := S_XMM;
  3604. taicpu(p).oper[1]^.reg := NewMMReg;
  3605. if ((TargetRef.offset mod 16) = 8) and
  3606. (
  3607. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3608. (TargetRef.base = current_procinfo.framepointer) or
  3609. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3610. ) then
  3611. taicpu(hp1).opcode := MovAligned
  3612. else
  3613. taicpu(hp1).opcode := MovUnaligned;
  3614. taicpu(hp1).opsize := S_XMM;
  3615. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3616. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3617. RemoveInstruction(hp2);
  3618. RemoveInstruction(hp3);
  3619. Result := True;
  3620. Exit;
  3621. end;
  3622. end;
  3623. end
  3624. else
  3625. begin
  3626. { See if the next references are 8 less rather than 8 greater }
  3627. Dec(SourceRef.offset, 16); { -8 the other way }
  3628. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3629. begin
  3630. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3631. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3632. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3633. GetNextInstruction(hp2, hp3) and
  3634. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3635. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3636. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3637. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3638. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3639. begin
  3640. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3641. if NewMMReg <> NR_NO then
  3642. begin
  3643. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3644. if ((SourceRef.offset mod 16) = 0) and
  3645. (
  3646. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3647. (SourceRef.base = current_procinfo.framepointer) or
  3648. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3649. ) then
  3650. taicpu(hp2).opcode := MovAligned
  3651. else
  3652. taicpu(hp2).opcode := MovUnaligned;
  3653. taicpu(hp2).opsize := S_XMM;
  3654. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3655. if ((TargetRef.offset mod 16) = 0) and
  3656. (
  3657. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3658. (TargetRef.base = current_procinfo.framepointer) or
  3659. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3660. ) then
  3661. taicpu(hp3).opcode := MovAligned
  3662. else
  3663. taicpu(hp3).opcode := MovUnaligned;
  3664. taicpu(hp3).opsize := S_XMM;
  3665. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3666. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3667. RemoveInstruction(hp1);
  3668. RemoveCurrentP(p, hp2);
  3669. Result := True;
  3670. Exit;
  3671. end;
  3672. end;
  3673. end;
  3674. end;
  3675. end;
  3676. {$endif x86_64}
  3677. end;
  3678. else
  3679. { The write target should be a reg or a ref }
  3680. InternalError(2021091601);
  3681. end;
  3682. else
  3683. ;
  3684. end
  3685. else
  3686. { %treg is used afterwards, but all eventualities
  3687. other than the first MOV instruction being a constant
  3688. are covered by DeepMOVOpt, so only check for that }
  3689. if (taicpu(p).oper[0]^.typ = top_const) and
  3690. (
  3691. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3692. not (cs_opt_size in current_settings.optimizerswitches) or
  3693. (taicpu(hp1).opsize = S_B)
  3694. ) and
  3695. (
  3696. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3697. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3698. ) then
  3699. begin
  3700. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3701. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3702. end;
  3703. end;
  3704. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3705. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3706. { mov reg1, mem1 or mov mem1, reg1
  3707. mov mem2, reg2 mov reg2, mem2}
  3708. begin
  3709. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3710. { mov reg1, mem1 or mov mem1, reg1
  3711. mov mem2, reg1 mov reg2, mem1}
  3712. begin
  3713. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3714. { Removes the second statement from
  3715. mov reg1, mem1/reg2
  3716. mov mem1/reg2, reg1 }
  3717. begin
  3718. if taicpu(p).oper[0]^.typ=top_reg then
  3719. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3720. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3721. RemoveInstruction(hp1);
  3722. Result:=true;
  3723. exit;
  3724. end
  3725. else
  3726. begin
  3727. TransferUsedRegs(TmpUsedRegs);
  3728. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3729. if (taicpu(p).oper[1]^.typ = top_ref) and
  3730. { mov reg1, mem1
  3731. mov mem2, reg1 }
  3732. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3733. GetNextInstruction(hp1, hp2) and
  3734. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3735. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3736. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3737. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3738. { change to
  3739. mov reg1, mem1 mov reg1, mem1
  3740. mov mem2, reg1 cmp reg1, mem2
  3741. cmp mem1, reg1
  3742. }
  3743. begin
  3744. RemoveInstruction(hp2);
  3745. taicpu(hp1).opcode := A_CMP;
  3746. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3747. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3748. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3749. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3750. end;
  3751. end;
  3752. end
  3753. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3754. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3755. begin
  3756. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3757. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3758. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3759. end
  3760. else
  3761. begin
  3762. TransferUsedRegs(TmpUsedRegs);
  3763. if GetNextInstruction(hp1, hp2) and
  3764. MatchOpType(taicpu(p),top_ref,top_reg) and
  3765. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3766. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3767. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3768. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3769. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3770. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3771. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3772. { mov mem1, %reg1
  3773. mov %reg1, mem2
  3774. mov mem2, reg2
  3775. to:
  3776. mov mem1, reg2
  3777. mov reg2, mem2}
  3778. begin
  3779. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3780. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3781. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3782. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3783. RemoveInstruction(hp2);
  3784. Result := True;
  3785. end
  3786. {$ifdef i386}
  3787. { this is enabled for i386 only, as the rules to create the reg sets below
  3788. are too complicated for x86-64, so this makes this code too error prone
  3789. on x86-64
  3790. }
  3791. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3792. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3793. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3794. { mov mem1, reg1 mov mem1, reg1
  3795. mov reg1, mem2 mov reg1, mem2
  3796. mov mem2, reg2 mov mem2, reg1
  3797. to: to:
  3798. mov mem1, reg1 mov mem1, reg1
  3799. mov mem1, reg2 mov reg1, mem2
  3800. mov reg1, mem2
  3801. or (if mem1 depends on reg1
  3802. and/or if mem2 depends on reg2)
  3803. to:
  3804. mov mem1, reg1
  3805. mov reg1, mem2
  3806. mov reg1, reg2
  3807. }
  3808. begin
  3809. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3810. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3811. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3812. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3813. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3814. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3815. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3816. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3817. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3818. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3819. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3820. end
  3821. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3822. begin
  3823. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3824. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3825. end
  3826. else
  3827. begin
  3828. RemoveInstruction(hp2);
  3829. end
  3830. {$endif i386}
  3831. ;
  3832. end;
  3833. end
  3834. { movl [mem1],reg1
  3835. movl [mem1],reg2
  3836. to
  3837. movl [mem1],reg1
  3838. movl reg1,reg2
  3839. }
  3840. else if not CheckMovMov2MovMov2(p, hp1) and
  3841. { movl const1,[mem1]
  3842. movl [mem1],reg1
  3843. to
  3844. movl const1,reg1
  3845. movl reg1,[mem1]
  3846. }
  3847. MatchOpType(Taicpu(p),top_const,top_ref) and
  3848. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3849. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3850. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3851. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3852. begin
  3853. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3854. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3855. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3856. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3857. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3858. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3859. Result:=true;
  3860. exit;
  3861. end;
  3862. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3863. { Change:
  3864. movl %reg1,%reg2
  3865. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3866. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3867. To:
  3868. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3869. movl x(%reg1),%reg1
  3870. movl %reg1,%regX
  3871. }
  3872. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3873. begin
  3874. p_SourceReg := taicpu(p).oper[0]^.reg;
  3875. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3876. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3877. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3878. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3879. GetNextInstruction(hp1, hp2) and
  3880. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3881. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3882. begin
  3883. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3884. if RegInRef(p_TargetReg, SourceRef) and
  3885. { If %reg1 also appears in the second reference, then it will
  3886. not refer to the same memory block as the first reference }
  3887. not RegInRef(p_SourceReg, SourceRef) then
  3888. begin
  3889. { Check to see if the references match if %reg2 is changed to %reg1 }
  3890. if SourceRef.base = p_TargetReg then
  3891. SourceRef.base := p_SourceReg;
  3892. if SourceRef.index = p_TargetReg then
  3893. SourceRef.index := p_SourceReg;
  3894. { RefsEqual also checks to ensure both references are non-volatile }
  3895. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3896. begin
  3897. taicpu(hp2).loadreg(0, p_SourceReg);
  3898. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3899. Result := True;
  3900. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3901. begin
  3902. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3903. RemoveCurrentP(p, hp1);
  3904. Exit;
  3905. end
  3906. else
  3907. begin
  3908. { Check to see if %reg2 is no longer in use }
  3909. TransferUsedRegs(TmpUsedRegs);
  3910. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3911. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3912. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3913. begin
  3914. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3915. RemoveCurrentP(p, hp1);
  3916. Exit;
  3917. end;
  3918. end;
  3919. { If we reach this point, p and hp1 weren't actually modified,
  3920. so we can do a bit more work on this pass }
  3921. end;
  3922. end;
  3923. end;
  3924. end;
  3925. end;
  3926. {$ifdef x86_64}
  3927. { Change:
  3928. movl %reg1l,%reg2l
  3929. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3930. To:
  3931. movl %reg1l,%reg2l
  3932. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3933. If %reg1 = %reg3, convert to:
  3934. movl %reg1l,%reg2l
  3935. andl %reg1l,%reg1l
  3936. }
  3937. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3938. MatchOpType(taicpu(p), top_reg, top_reg) and
  3939. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3940. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3941. begin
  3942. TransferUsedRegs(TmpUsedRegs);
  3943. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3944. taicpu(hp1).opsize := S_L;
  3945. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3946. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3947. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3948. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3949. begin
  3950. { %reg1 = %reg3 }
  3951. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3952. taicpu(hp1).opcode := A_AND;
  3953. end
  3954. else
  3955. begin
  3956. { %reg1 <> %reg3 }
  3957. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3958. end;
  3959. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3960. begin
  3961. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3962. RemoveCurrentP(p, hp1);
  3963. Result := True;
  3964. Exit;
  3965. end
  3966. else
  3967. begin
  3968. { Initial instruction wasn't actually changed }
  3969. Include(OptsToCheck, aoc_ForceNewIteration);
  3970. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3971. appears below since %reg1 has technically changed }
  3972. if taicpu(hp1).opcode = A_AND then
  3973. Exit;
  3974. end;
  3975. end;
  3976. {$endif x86_64}
  3977. { search further than the next instruction for a mov (as long as it's not a jump) }
  3978. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3979. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3980. (taicpu(p).oper[1]^.typ = top_reg) and
  3981. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3982. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3983. begin
  3984. { we work with hp2 here, so hp1 can be still used later on when
  3985. checking for GetNextInstruction_p }
  3986. hp3 := hp1;
  3987. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3988. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3989. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3990. TransferUsedRegs(TmpUsedRegs);
  3991. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3992. if NotFirstIteration then
  3993. JumpTracking := TLinkedList.Create
  3994. else
  3995. JumpTracking := nil;
  3996. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3997. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3998. (hp2.typ=ait_instruction) do
  3999. begin
  4000. case taicpu(hp2).opcode of
  4001. A_POP:
  4002. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4003. begin
  4004. if not CrossJump and
  4005. not RegUsedBetween(p_TargetReg, p, hp2) then
  4006. begin
  4007. { We can remove the original MOV since the register
  4008. wasn't used between it and its popping from the stack }
  4009. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4010. RemoveCurrentp(p, hp1);
  4011. Result := True;
  4012. JumpTracking.Free;
  4013. Exit;
  4014. end;
  4015. { Can't go any further }
  4016. Break;
  4017. end;
  4018. A_MOV:
  4019. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4020. ((taicpu(p).oper[0]^.typ=top_const) or
  4021. ((taicpu(p).oper[0]^.typ=top_reg) and
  4022. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4023. )
  4024. ) then
  4025. begin
  4026. { we have
  4027. mov x, %treg
  4028. mov %treg, y
  4029. }
  4030. { We don't need to call UpdateUsedRegs for every instruction between
  4031. p and hp2 because the register we're concerned about will not
  4032. become deallocated (otherwise GetNextInstructionUsingReg would
  4033. have stopped at an earlier instruction). [Kit] }
  4034. TempRegUsed :=
  4035. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4036. RegReadByInstruction(p_TargetReg, hp3) or
  4037. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4038. case taicpu(p).oper[0]^.typ Of
  4039. top_reg:
  4040. begin
  4041. { change
  4042. mov %reg, %treg
  4043. mov %treg, y
  4044. to
  4045. mov %reg, y
  4046. }
  4047. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4048. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4049. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4050. begin
  4051. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4052. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4053. if TempRegUsed then
  4054. begin
  4055. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4056. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4057. { Set the start of the next GetNextInstructionUsingRegCond search
  4058. to start at the entry right before hp2 (which is about to be removed) }
  4059. hp3 := tai(hp2.Previous);
  4060. RemoveInstruction(hp2);
  4061. Include(OptsToCheck, aoc_ForceNewIteration);
  4062. { See if there's more we can optimise }
  4063. Continue;
  4064. end
  4065. else
  4066. begin
  4067. RemoveInstruction(hp2);
  4068. { We can remove the original MOV too }
  4069. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4070. RemoveCurrentP(p, hp1);
  4071. Result:=true;
  4072. JumpTracking.Free;
  4073. Exit;
  4074. end;
  4075. end
  4076. else
  4077. begin
  4078. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4079. taicpu(hp2).loadReg(0, p_SourceReg);
  4080. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4081. { Check to see if the register also appears in the reference }
  4082. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4083. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4084. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4085. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4086. begin
  4087. { Don't remove the first instruction if the temporary register is in use }
  4088. if not TempRegUsed then
  4089. begin
  4090. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4091. RemoveCurrentP(p, hp1);
  4092. Result:=true;
  4093. JumpTracking.Free;
  4094. Exit;
  4095. end;
  4096. { No need to set Result to True here. If there's another instruction later
  4097. on that can be optimised, it will be detected when the main Pass 1 loop
  4098. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4099. hp3 := hp2;
  4100. Continue;
  4101. end;
  4102. end;
  4103. end;
  4104. top_const:
  4105. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4106. begin
  4107. { change
  4108. mov const, %treg
  4109. mov %treg, y
  4110. to
  4111. mov const, y
  4112. }
  4113. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4114. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4115. begin
  4116. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4117. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4118. if TempRegUsed then
  4119. begin
  4120. { Don't remove the first instruction if the temporary register is in use }
  4121. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4122. { No need to set Result to True. If there's another instruction later on
  4123. that can be optimised, it will be detected when the main Pass 1 loop
  4124. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4125. end
  4126. else
  4127. begin
  4128. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4129. RemoveCurrentP(p, hp1);
  4130. Result:=true;
  4131. Exit;
  4132. end;
  4133. end;
  4134. end;
  4135. else
  4136. Internalerror(2019103001);
  4137. end;
  4138. end
  4139. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4140. begin
  4141. if not CrossJump and
  4142. not RegUsedBetween(p_TargetReg, p, hp2) and
  4143. not RegReadByInstruction(p_TargetReg, hp2) then
  4144. begin
  4145. { Register is not used before it is overwritten }
  4146. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4147. RemoveCurrentp(p, hp1);
  4148. Result := True;
  4149. Exit;
  4150. end;
  4151. if (taicpu(p).oper[0]^.typ = top_const) and
  4152. (taicpu(hp2).oper[0]^.typ = top_const) then
  4153. begin
  4154. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4155. begin
  4156. { Same value - register hasn't changed }
  4157. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4158. RemoveInstruction(hp2);
  4159. Include(OptsToCheck, aoc_ForceNewIteration);
  4160. { See if there's more we can optimise }
  4161. Continue;
  4162. end;
  4163. end;
  4164. {$ifdef x86_64}
  4165. end
  4166. { Change:
  4167. movl %reg1l,%reg2l
  4168. ...
  4169. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4170. To:
  4171. movl %reg1l,%reg2l
  4172. ...
  4173. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4174. If %reg1 = %reg3, convert to:
  4175. movl %reg1l,%reg2l
  4176. ...
  4177. andl %reg1l,%reg1l
  4178. }
  4179. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4180. (taicpu(p).oper[0]^.typ = top_reg) and
  4181. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4182. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4183. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4184. begin
  4185. TempRegUsed :=
  4186. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4187. RegReadByInstruction(p_TargetReg, hp3) or
  4188. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4189. taicpu(hp2).opsize := S_L;
  4190. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4191. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4192. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4193. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4194. begin
  4195. { %reg1 = %reg3 }
  4196. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4197. taicpu(hp2).opcode := A_AND;
  4198. end
  4199. else
  4200. begin
  4201. { %reg1 <> %reg3 }
  4202. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4203. end;
  4204. if not TempRegUsed then
  4205. begin
  4206. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4207. RemoveCurrentP(p, hp1);
  4208. Result := True;
  4209. Exit;
  4210. end
  4211. else
  4212. begin
  4213. { Initial instruction wasn't actually changed }
  4214. Include(OptsToCheck, aoc_ForceNewIteration);
  4215. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4216. appears below since %reg1 has technically changed }
  4217. if taicpu(hp2).opcode = A_AND then
  4218. Break;
  4219. end;
  4220. {$endif x86_64}
  4221. end
  4222. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4223. GetNextInstruction(hp2, hp4) and
  4224. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4225. { Optimise the following first:
  4226. movl [mem1],reg1
  4227. movl [mem1],reg2
  4228. to
  4229. movl [mem1],reg1
  4230. movl reg1,reg2
  4231. If [mem1] contains the target register and reg1 is the
  4232. the source register, this optimisation will get missed
  4233. and produce less efficient code later on.
  4234. }
  4235. if CheckMovMov2MovMov2(hp2, hp4) then
  4236. { Initial instruction wasn't actually changed }
  4237. Include(OptsToCheck, aoc_ForceNewIteration);
  4238. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4239. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4240. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4241. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4242. begin
  4243. {
  4244. Change from:
  4245. mov ###, %reg
  4246. ...
  4247. movs/z %reg,%reg (Same register, just different sizes)
  4248. To:
  4249. movs/z ###, %reg (Longer version)
  4250. ...
  4251. (remove)
  4252. }
  4253. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4254. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4255. { Keep the first instruction as mov if ### is a constant }
  4256. if taicpu(p).oper[0]^.typ = top_const then
  4257. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4258. else
  4259. begin
  4260. taicpu(p).opcode := taicpu(hp2).opcode;
  4261. taicpu(p).opsize := taicpu(hp2).opsize;
  4262. end;
  4263. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4264. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4265. RemoveInstruction(hp2);
  4266. Result := True;
  4267. JumpTracking.Free;
  4268. Exit;
  4269. end;
  4270. else
  4271. { Move down to the if-block below };
  4272. end;
  4273. { Also catches MOV/S/Z instructions that aren't modified }
  4274. if taicpu(p).oper[0]^.typ = top_reg then
  4275. begin
  4276. p_SourceReg := taicpu(p).oper[0]^.reg;
  4277. if
  4278. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4279. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4280. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4281. begin
  4282. Result := True;
  4283. { Just in case something didn't get modified (e.g. an
  4284. implicit register). Also, if it does read from this
  4285. register, then there's no longer an advantage to
  4286. changing the register on subsequent instructions.}
  4287. if not RegReadByInstruction(p_TargetReg, hp2) then
  4288. begin
  4289. { If a conditional jump was crossed, do not delete
  4290. the original MOV no matter what }
  4291. if not CrossJump and
  4292. { RegEndOfLife returns True if the register is
  4293. deallocated before the next instruction or has
  4294. been loaded with a new value }
  4295. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4296. begin
  4297. { We can remove the original MOV }
  4298. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4299. RemoveCurrentp(p, hp1);
  4300. JumpTracking.Free;
  4301. Result := True;
  4302. Exit;
  4303. end;
  4304. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4305. begin
  4306. { See if there's more we can optimise }
  4307. hp3 := hp2;
  4308. Continue;
  4309. end;
  4310. end;
  4311. end;
  4312. end;
  4313. { Break out of the while loop under normal circumstances }
  4314. Break;
  4315. end;
  4316. JumpTracking.Free;
  4317. end;
  4318. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4319. (taicpu(p).oper[1]^.typ = top_reg) and
  4320. (taicpu(p).opsize = S_L) and
  4321. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4322. (hp2.typ = ait_instruction) and
  4323. (taicpu(hp2).opcode = A_AND) and
  4324. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4325. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4326. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4327. ) then
  4328. begin
  4329. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4330. begin
  4331. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4332. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4333. begin
  4334. { Optimize out:
  4335. mov x, %reg
  4336. and ffffffffh, %reg
  4337. }
  4338. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4339. RemoveInstruction(hp2);
  4340. Result:=true;
  4341. exit;
  4342. end;
  4343. end;
  4344. end;
  4345. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4346. x >= RetOffset) as it doesn't do anything (it writes either to a
  4347. parameter or to the temporary storage room for the function
  4348. result)
  4349. }
  4350. if IsExitCode(hp1) and
  4351. (taicpu(p).oper[1]^.typ = top_ref) and
  4352. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4353. (
  4354. (
  4355. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4356. not (
  4357. assigned(current_procinfo.procdef.funcretsym) and
  4358. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4359. )
  4360. ) or
  4361. { Also discard writes to the stack that are below the base pointer,
  4362. as this is temporary storage rather than a function result on the
  4363. stack, say. }
  4364. (
  4365. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4366. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4367. )
  4368. ) then
  4369. begin
  4370. RemoveCurrentp(p, hp1);
  4371. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4372. RemoveLastDeallocForFuncRes(p);
  4373. Result:=true;
  4374. exit;
  4375. end;
  4376. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4377. begin
  4378. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4379. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4380. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4381. begin
  4382. { change
  4383. mov reg1, mem1
  4384. test/cmp x, mem1
  4385. to
  4386. mov reg1, mem1
  4387. test/cmp x, reg1
  4388. }
  4389. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4390. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4391. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4392. Result := True;
  4393. Exit;
  4394. end;
  4395. if DoMovCmpMemOpt(p, hp1) then
  4396. begin
  4397. Result := True;
  4398. Exit;
  4399. end;
  4400. end;
  4401. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4402. { If the flags register is in use, don't change the instruction to an
  4403. ADD otherwise this will scramble the flags. [Kit] }
  4404. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4405. begin
  4406. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4407. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4408. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4409. ) or
  4410. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4411. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4412. )
  4413. ) then
  4414. { mov reg1,ref
  4415. lea reg2,[reg1,reg2]
  4416. to
  4417. add reg2,ref}
  4418. begin
  4419. TransferUsedRegs(TmpUsedRegs);
  4420. { reg1 may not be used afterwards }
  4421. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4422. begin
  4423. Taicpu(hp1).opcode:=A_ADD;
  4424. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4425. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4426. RemoveCurrentp(p, hp1);
  4427. result:=true;
  4428. exit;
  4429. end;
  4430. end;
  4431. { If the LEA instruction can be converted into an arithmetic instruction,
  4432. it may be possible to then fold it in the next optimisation, otherwise
  4433. there's nothing more that can be optimised here. }
  4434. if not ConvertLEA(taicpu(hp1)) then
  4435. Exit;
  4436. end;
  4437. if (taicpu(p).oper[1]^.typ = top_reg) and
  4438. (hp1.typ = ait_instruction) and
  4439. GetNextInstruction(hp1, hp2) and
  4440. MatchInstruction(hp2,A_MOV,[]) and
  4441. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4442. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4443. (
  4444. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4445. {$ifdef x86_64}
  4446. or
  4447. (
  4448. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4449. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4450. )
  4451. {$endif x86_64}
  4452. ) then
  4453. begin
  4454. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4455. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4456. { change movsX/movzX reg/ref, reg2
  4457. add/sub/or/... reg3/$const, reg2
  4458. mov reg2 reg/ref
  4459. dealloc reg2
  4460. to
  4461. add/sub/or/... reg3/$const, reg/ref }
  4462. begin
  4463. TransferUsedRegs(TmpUsedRegs);
  4464. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4465. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4466. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4467. begin
  4468. { by example:
  4469. movswl %si,%eax movswl %si,%eax p
  4470. decl %eax addl %edx,%eax hp1
  4471. movw %ax,%si movw %ax,%si hp2
  4472. ->
  4473. movswl %si,%eax movswl %si,%eax p
  4474. decw %eax addw %edx,%eax hp1
  4475. movw %ax,%si movw %ax,%si hp2
  4476. }
  4477. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4478. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4479. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4480. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4481. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4482. {
  4483. ->
  4484. movswl %si,%eax movswl %si,%eax p
  4485. decw %si addw %dx,%si hp1
  4486. movw %ax,%si movw %ax,%si hp2
  4487. }
  4488. case taicpu(hp1).ops of
  4489. 1:
  4490. begin
  4491. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4492. if taicpu(hp1).oper[0]^.typ=top_reg then
  4493. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4494. end;
  4495. 2:
  4496. begin
  4497. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4498. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4499. (taicpu(hp1).opcode<>A_SHL) and
  4500. (taicpu(hp1).opcode<>A_SHR) and
  4501. (taicpu(hp1).opcode<>A_SAR) then
  4502. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4503. end;
  4504. else
  4505. internalerror(2008042701);
  4506. end;
  4507. {
  4508. ->
  4509. decw %si addw %dx,%si p
  4510. }
  4511. RemoveInstruction(hp2);
  4512. RemoveCurrentP(p, hp1);
  4513. Result:=True;
  4514. Exit;
  4515. end;
  4516. end;
  4517. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4518. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4519. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4520. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4521. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4522. )
  4523. {$ifdef i386}
  4524. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4525. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4526. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4527. {$endif i386}
  4528. then
  4529. { change movsX/movzX reg/ref, reg2
  4530. add/sub/or/... regX/$const, reg2
  4531. mov reg2, reg3
  4532. dealloc reg2
  4533. to
  4534. movsX/movzX reg/ref, reg3
  4535. add/sub/or/... reg3/$const, reg3
  4536. }
  4537. begin
  4538. TransferUsedRegs(TmpUsedRegs);
  4539. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4540. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4541. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4542. begin
  4543. { by example:
  4544. movswl %si,%eax movswl %si,%eax p
  4545. decl %eax addl %edx,%eax hp1
  4546. movw %ax,%si movw %ax,%si hp2
  4547. ->
  4548. movswl %si,%eax movswl %si,%eax p
  4549. decw %eax addw %edx,%eax hp1
  4550. movw %ax,%si movw %ax,%si hp2
  4551. }
  4552. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4553. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4554. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4555. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4556. { limit size of constants as well to avoid assembler errors, but
  4557. check opsize to avoid overflow when left shifting the 1 }
  4558. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4559. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4560. {$ifdef x86_64}
  4561. { Be careful of, for example:
  4562. movl %reg1,%reg2
  4563. addl %reg3,%reg2
  4564. movq %reg2,%reg4
  4565. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4566. }
  4567. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4568. begin
  4569. taicpu(hp2).changeopsize(S_L);
  4570. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4571. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4572. end;
  4573. {$endif x86_64}
  4574. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4575. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4576. if taicpu(p).oper[0]^.typ=top_reg then
  4577. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4578. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4579. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4580. {
  4581. ->
  4582. movswl %si,%eax movswl %si,%eax p
  4583. decw %si addw %dx,%si hp1
  4584. movw %ax,%si movw %ax,%si hp2
  4585. }
  4586. case taicpu(hp1).ops of
  4587. 1:
  4588. begin
  4589. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4590. if taicpu(hp1).oper[0]^.typ=top_reg then
  4591. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4592. end;
  4593. 2:
  4594. begin
  4595. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4596. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4597. (taicpu(hp1).opcode<>A_SHL) and
  4598. (taicpu(hp1).opcode<>A_SHR) and
  4599. (taicpu(hp1).opcode<>A_SAR) then
  4600. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4601. end;
  4602. else
  4603. internalerror(2018111801);
  4604. end;
  4605. {
  4606. ->
  4607. decw %si addw %dx,%si p
  4608. }
  4609. RemoveInstruction(hp2);
  4610. end;
  4611. end;
  4612. end;
  4613. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4614. GetNextInstruction(hp1, hp2) and
  4615. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4616. MatchOperand(Taicpu(p).oper[0]^,0) and
  4617. (Taicpu(p).oper[1]^.typ = top_reg) and
  4618. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4619. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4620. { mov reg1,0
  4621. bts reg1,operand1 --> mov reg1,operand2
  4622. or reg1,operand2 bts reg1,operand1}
  4623. begin
  4624. Taicpu(hp2).opcode:=A_MOV;
  4625. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4626. asml.remove(hp1);
  4627. insertllitem(hp2,hp2.next,hp1);
  4628. RemoveCurrentp(p, hp1);
  4629. Result:=true;
  4630. exit;
  4631. end;
  4632. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4633. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4634. GetNextInstruction(hp1, hp2) and
  4635. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4636. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4637. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4638. { change
  4639. mov reg1,reg2
  4640. sub reg3,reg2
  4641. cmp reg3,reg1
  4642. into
  4643. mov reg1,reg2
  4644. sub reg3,reg2
  4645. }
  4646. begin
  4647. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4648. RemoveInstruction(hp2);
  4649. Result:=true;
  4650. exit;
  4651. end;
  4652. {
  4653. mov ref,reg0
  4654. <op> reg0,reg1
  4655. dealloc reg0
  4656. to
  4657. <op> ref,reg1
  4658. }
  4659. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4660. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4661. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4662. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4663. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4664. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4665. begin
  4666. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4667. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4668. RemoveCurrentp(p, hp1);
  4669. Result:=true;
  4670. exit;
  4671. end;
  4672. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4673. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4674. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4675. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4676. begin
  4677. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4678. {$ifdef x86_64}
  4679. { Convert:
  4680. movq x(ref),%reg64
  4681. shrq y,%reg64
  4682. To:
  4683. movl x+4(ref),%reg32
  4684. shrl y-32,%reg32 (Remove if y = 32)
  4685. }
  4686. if (taicpu(p).opsize = S_Q) and
  4687. (taicpu(hp1).opcode = A_SHR) and
  4688. (taicpu(hp1).oper[0]^.val >= 32) then
  4689. begin
  4690. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4691. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4692. { Convert to 32-bit }
  4693. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4694. taicpu(p).opsize := S_L;
  4695. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4696. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4697. if (taicpu(hp1).oper[0]^.val = 32) then
  4698. begin
  4699. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4700. RemoveInstruction(hp1);
  4701. end
  4702. else
  4703. begin
  4704. { This will potentially open up more arithmetic operations since
  4705. the peephole optimizer now has a big hint that only the lower
  4706. 32 bits are currently in use (and opcodes are smaller in size) }
  4707. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4708. taicpu(hp1).opsize := S_L;
  4709. Dec(taicpu(hp1).oper[0]^.val, 32);
  4710. DebugMsg(SPeepholeOptimization + PreMessage +
  4711. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4712. end;
  4713. Result := True;
  4714. Exit;
  4715. end;
  4716. {$endif x86_64}
  4717. { Convert:
  4718. movl x(ref),%reg
  4719. shrl $24,%reg
  4720. To:
  4721. movzbl x+3(ref),%reg
  4722. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4723. Also accept sar instead of shr, but convert to movsx instead of movzx
  4724. }
  4725. if taicpu(hp1).opcode = A_SHR then
  4726. MovUnaligned := A_MOVZX
  4727. else
  4728. MovUnaligned := A_MOVSX;
  4729. NewSize := S_NO;
  4730. NewOffset := 0;
  4731. case taicpu(p).opsize of
  4732. S_B:
  4733. { No valid combinations };
  4734. S_W:
  4735. if (taicpu(hp1).oper[0]^.val = 8) then
  4736. begin
  4737. NewSize := S_BW;
  4738. NewOffset := 1;
  4739. end;
  4740. S_L:
  4741. case taicpu(hp1).oper[0]^.val of
  4742. 16:
  4743. begin
  4744. NewSize := S_WL;
  4745. NewOffset := 2;
  4746. end;
  4747. 24:
  4748. begin
  4749. NewSize := S_BL;
  4750. NewOffset := 3;
  4751. end;
  4752. else
  4753. ;
  4754. end;
  4755. {$ifdef x86_64}
  4756. S_Q:
  4757. case taicpu(hp1).oper[0]^.val of
  4758. 32:
  4759. begin
  4760. if taicpu(hp1).opcode = A_SAR then
  4761. begin
  4762. { 32-bit to 64-bit is a distinct instruction }
  4763. MovUnaligned := A_MOVSXD;
  4764. NewSize := S_LQ;
  4765. NewOffset := 4;
  4766. end
  4767. else
  4768. { Should have been handled by MovShr2Mov above }
  4769. InternalError(2022081811);
  4770. end;
  4771. 48:
  4772. begin
  4773. NewSize := S_WQ;
  4774. NewOffset := 6;
  4775. end;
  4776. 56:
  4777. begin
  4778. NewSize := S_BQ;
  4779. NewOffset := 7;
  4780. end;
  4781. else
  4782. ;
  4783. end;
  4784. {$endif x86_64}
  4785. else
  4786. InternalError(2022081810);
  4787. end;
  4788. if (NewSize <> S_NO) and
  4789. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4790. begin
  4791. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4792. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4793. debug_op2str(MovUnaligned);
  4794. {$ifdef x86_64}
  4795. if MovUnaligned <> A_MOVSXD then
  4796. { Don't add size suffix for MOVSXD }
  4797. {$endif x86_64}
  4798. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4799. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4800. taicpu(p).opcode := MovUnaligned;
  4801. taicpu(p).opsize := NewSize;
  4802. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4803. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4804. RemoveInstruction(hp1);
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. end;
  4809. { Backward optimisation shared with OptPass2MOV }
  4810. if FuncMov2Func(p, hp1) then
  4811. begin
  4812. Result := True;
  4813. Exit;
  4814. end;
  4815. end;
  4816. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4817. var
  4818. hp1 : tai;
  4819. begin
  4820. Result:=false;
  4821. if taicpu(p).ops <> 2 then
  4822. exit;
  4823. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4824. GetNextInstruction(p,hp1) then
  4825. begin
  4826. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4827. (taicpu(hp1).ops = 2) then
  4828. begin
  4829. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4830. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4831. { movXX reg1, mem1 or movXX mem1, reg1
  4832. movXX mem2, reg2 movXX reg2, mem2}
  4833. begin
  4834. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4835. { movXX reg1, mem1 or movXX mem1, reg1
  4836. movXX mem2, reg1 movXX reg2, mem1}
  4837. begin
  4838. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4839. begin
  4840. { Removes the second statement from
  4841. movXX reg1, mem1/reg2
  4842. movXX mem1/reg2, reg1
  4843. }
  4844. if taicpu(p).oper[0]^.typ=top_reg then
  4845. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4846. { Removes the second statement from
  4847. movXX mem1/reg1, reg2
  4848. movXX reg2, mem1/reg1
  4849. }
  4850. if (taicpu(p).oper[1]^.typ=top_reg) and
  4851. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4852. begin
  4853. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4854. RemoveInstruction(hp1);
  4855. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4856. Result:=true;
  4857. exit;
  4858. end
  4859. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4860. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4861. begin
  4862. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4863. RemoveInstruction(hp1);
  4864. Result:=true;
  4865. exit;
  4866. end;
  4867. end
  4868. end;
  4869. end;
  4870. end;
  4871. end;
  4872. end;
  4873. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4874. var
  4875. hp1 : tai;
  4876. begin
  4877. result:=false;
  4878. { replace
  4879. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4880. MovX %mreg2,%mreg1
  4881. dealloc %mreg2
  4882. by
  4883. <Op>X %mreg2,%mreg1
  4884. ?
  4885. }
  4886. if GetNextInstruction(p,hp1) and
  4887. { we mix single and double opperations here because we assume that the compiler
  4888. generates vmovapd only after double operations and vmovaps only after single operations }
  4889. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4890. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4891. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4892. (taicpu(p).oper[0]^.typ=top_reg) then
  4893. begin
  4894. TransferUsedRegs(TmpUsedRegs);
  4895. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4896. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4897. begin
  4898. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4899. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4900. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4901. RemoveInstruction(hp1);
  4902. result:=true;
  4903. end;
  4904. end;
  4905. end;
  4906. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4907. var
  4908. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4909. JumpLabel, JumpLabel_dist: TAsmLabel;
  4910. FirstValue, SecondValue: TCGInt;
  4911. function OptimizeJump(var InputP: tai): Boolean;
  4912. var
  4913. TempBool: Boolean;
  4914. begin
  4915. Result := False;
  4916. TempBool := True;
  4917. if DoJumpOptimizations(InputP, TempBool) or
  4918. not TempBool then
  4919. begin
  4920. Result := True;
  4921. if Assigned(InputP) then
  4922. begin
  4923. { CollapseZeroDistJump will be set to the label or an align
  4924. before it after the jump if it optimises, whether or not
  4925. the label is live or dead }
  4926. if (InputP.typ = ait_align) or
  4927. (
  4928. (InputP.typ = ait_label) and
  4929. not (tai_label(InputP).labsym.is_used)
  4930. ) then
  4931. GetNextInstruction(InputP, InputP);
  4932. end;
  4933. Exit;
  4934. end;
  4935. end;
  4936. begin
  4937. Result := False;
  4938. if (taicpu(p).oper[0]^.typ = top_const) and
  4939. (taicpu(p).oper[0]^.val <> -1) then
  4940. begin
  4941. { Convert unsigned maximum constants to -1 to aid optimisation }
  4942. case taicpu(p).opsize of
  4943. S_B:
  4944. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4945. begin
  4946. taicpu(p).oper[0]^.val := -1;
  4947. Result := True;
  4948. Exit;
  4949. end;
  4950. S_W:
  4951. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4952. begin
  4953. taicpu(p).oper[0]^.val := -1;
  4954. Result := True;
  4955. Exit;
  4956. end;
  4957. S_L:
  4958. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4959. begin
  4960. taicpu(p).oper[0]^.val := -1;
  4961. Result := True;
  4962. Exit;
  4963. end;
  4964. {$ifdef x86_64}
  4965. S_Q:
  4966. { Storing anything greater than $7FFFFFFF is not possible so do
  4967. nothing };
  4968. {$endif x86_64}
  4969. else
  4970. InternalError(2021121001);
  4971. end;
  4972. end;
  4973. if GetNextInstruction(p, hp1) and
  4974. TrySwapMovCmp(p, hp1) then
  4975. begin
  4976. Result := True;
  4977. Exit;
  4978. end;
  4979. p_label := nil;
  4980. JumpLabel := nil;
  4981. if MatchInstruction(hp1, A_Jcc, []) then
  4982. begin
  4983. if OptimizeJump(hp1) then
  4984. begin
  4985. Result := True;
  4986. if Assigned(hp1) then
  4987. begin
  4988. { CollapseZeroDistJump will be set to the label or an align
  4989. before it after the jump if it optimises, whether or not
  4990. the label is live or dead }
  4991. if (hp1.typ = ait_align) or
  4992. (
  4993. (hp1.typ = ait_label) and
  4994. not (tai_label(hp1).labsym.is_used)
  4995. ) then
  4996. GetNextInstruction(hp1, hp1);
  4997. end;
  4998. TransferUsedRegs(TmpUsedRegs);
  4999. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5000. if not Assigned(hp1) or
  5001. (
  5002. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5003. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5004. ) then
  5005. begin
  5006. { No more conditional jumps; conditional statement is no longer required }
  5007. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5008. RemoveCurrentP(p);
  5009. end;
  5010. Exit;
  5011. end;
  5012. if IsJumpToLabel(taicpu(hp1)) then
  5013. begin
  5014. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5015. if Assigned(JumpLabel) then
  5016. p_label := getlabelwithsym(JumpLabel);
  5017. end;
  5018. end;
  5019. { Search for:
  5020. test $x,(reg/ref)
  5021. jne @lbl1
  5022. test $y,(reg/ref) (same register or reference)
  5023. jne @lbl1
  5024. Change to:
  5025. test $(x or y),(reg/ref)
  5026. jne @lbl1
  5027. (Note, this doesn't work with je instead of jne)
  5028. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5029. Also search for:
  5030. test $x,(reg/ref)
  5031. je @lbl1
  5032. ...
  5033. test $y,(reg/ref)
  5034. je/jne @lbl2
  5035. If (x or y) = x, then the second jump is deterministic
  5036. }
  5037. if (
  5038. (
  5039. (taicpu(p).oper[0]^.typ = top_const) or
  5040. (
  5041. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5042. (taicpu(p).oper[0]^.typ = top_reg) and
  5043. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5044. )
  5045. ) and
  5046. MatchInstruction(hp1, A_JCC, [])
  5047. ) then
  5048. begin
  5049. if (taicpu(p).oper[0]^.typ = top_reg) and
  5050. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5051. FirstValue := -1
  5052. else
  5053. FirstValue := taicpu(p).oper[0]^.val;
  5054. { If we have several test/jne's in a row, it might be the case that
  5055. the second label doesn't go to the same location, but the one
  5056. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5057. so accommodate for this with a while loop.
  5058. }
  5059. hp1_last := hp1;
  5060. while (
  5061. (
  5062. (taicpu(p).oper[1]^.typ = top_reg) and
  5063. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5064. ) or GetNextInstruction(hp1_last, p_dist)
  5065. ) and (p_dist.typ = ait_instruction) do
  5066. begin
  5067. if (
  5068. (
  5069. (taicpu(p_dist).opcode = A_TEST) and
  5070. (
  5071. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5072. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5073. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5074. )
  5075. ) or
  5076. (
  5077. { cmp 0,%reg = test %reg,%reg }
  5078. (taicpu(p_dist).opcode = A_CMP) and
  5079. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5080. )
  5081. ) and
  5082. { Make sure the destination operands are actually the same }
  5083. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5084. GetNextInstruction(p_dist, hp1_dist) and
  5085. MatchInstruction(hp1_dist, A_JCC, []) then
  5086. begin
  5087. if OptimizeJump(hp1_dist) then
  5088. begin
  5089. Result := True;
  5090. Exit;
  5091. end;
  5092. if
  5093. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5094. (
  5095. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5096. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5097. ) then
  5098. SecondValue := -1
  5099. else
  5100. SecondValue := taicpu(p_dist).oper[0]^.val;
  5101. { If both of the TEST constants are identical, delete the
  5102. second TEST that is unnecessary (be careful though, just
  5103. in case the flags are modified in between) }
  5104. if (FirstValue = SecondValue) then
  5105. begin
  5106. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5107. begin
  5108. { Since the second jump's condition is a subset of the first, we
  5109. know it will never branch because the first jump dominates it.
  5110. Get it out of the way now rather than wait for the jump
  5111. optimisations for a speed boost. }
  5112. if IsJumpToLabel(taicpu(hp1_dist)) then
  5113. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5114. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5115. RemoveInstruction(hp1_dist);
  5116. Result := True;
  5117. end
  5118. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5119. begin
  5120. { If the inverse of the first condition is a subset of the second,
  5121. the second one will definitely branch if the first one doesn't }
  5122. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5123. { We can remove the TEST instruction too }
  5124. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5125. RemoveInstruction(p_dist);
  5126. MakeUnconditional(taicpu(hp1_dist));
  5127. RemoveDeadCodeAfterJump(hp1_dist);
  5128. { Since the jump is now unconditional, we can't
  5129. continue any further with this particular
  5130. optimisation. The original TEST is still intact
  5131. though, so there might be something else we can
  5132. do }
  5133. Include(OptsToCheck, aoc_ForceNewIteration);
  5134. Break;
  5135. end;
  5136. if Result or
  5137. { If a jump wasn't removed or made unconditional, only
  5138. remove the identical TEST instruction if the flags
  5139. weren't modified }
  5140. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5141. begin
  5142. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5143. RemoveInstruction(p_dist);
  5144. { If the jump was removed or made unconditional, we
  5145. don't need to allocate NR_DEFAULTFLAGS over the
  5146. entire range }
  5147. if not Result then
  5148. begin
  5149. { Mark the flags as 'in use' over the entire range }
  5150. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5151. { Speed gain - continue search from the Jcc instruction }
  5152. hp1_last := hp1_dist;
  5153. { Only the TEST instruction was removed, and the
  5154. original was unchanged, so we can safely do
  5155. another iteration of the while loop }
  5156. Include(OptsToCheck, aoc_ForceNewIteration);
  5157. Continue;
  5158. end;
  5159. Exit;
  5160. end;
  5161. end;
  5162. hp1_last := nil;
  5163. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5164. (
  5165. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5166. { Always adjacent under -O2 and under }
  5167. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5168. (
  5169. GetNextInstruction(hp1, hp1_last) and
  5170. (hp1_last = p_dist)
  5171. )
  5172. ) and
  5173. (
  5174. (
  5175. { Test the following variant:
  5176. test $x,(reg/ref)
  5177. jne @lbl1
  5178. test $y,(reg/ref)
  5179. je @lbl2
  5180. @lbl1:
  5181. Becomes:
  5182. test $(x or y),(reg/ref)
  5183. je @lbl2
  5184. @lbl1: (may become a dead label)
  5185. }
  5186. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5187. GetNextInstruction(hp1_dist, hp1_last) and
  5188. (hp1_last = p_label)
  5189. ) or
  5190. (
  5191. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5192. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5193. then the second jump will never branch, so it can also be
  5194. removed regardless of where it goes }
  5195. (
  5196. (FirstValue = -1) or
  5197. (SecondValue = -1) or
  5198. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5199. )
  5200. )
  5201. ) then
  5202. begin
  5203. { Same jump location... can be a register since nothing's changed }
  5204. { If any of the entries are equivalent to test %reg,%reg, then the
  5205. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5206. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5207. if (hp1_last = p_label) then
  5208. begin
  5209. { Variant }
  5210. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5211. RemoveInstruction(p_dist);
  5212. if Assigned(JumpLabel) then
  5213. JumpLabel.decrefs;
  5214. RemoveInstruction(hp1);
  5215. end
  5216. else
  5217. begin
  5218. { Only remove the second test if no jumps or other conditional instructions follow }
  5219. TransferUsedRegs(TmpUsedRegs);
  5220. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5221. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5222. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5223. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5224. begin
  5225. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5226. RemoveInstruction(p_dist);
  5227. { Remove the first jump, not the second, to keep
  5228. any register deallocations between the second
  5229. TEST/JNE pair in the same place. Aids future
  5230. optimisation. }
  5231. if Assigned(JumpLabel) then
  5232. JumpLabel.decrefs;
  5233. RemoveInstruction(hp1);
  5234. end
  5235. else
  5236. begin
  5237. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5238. if IsJumpToLabel(taicpu(hp1_dist)) then
  5239. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5240. { Remove second jump in this instance }
  5241. RemoveInstruction(hp1_dist);
  5242. end;
  5243. end;
  5244. Result := True;
  5245. Exit;
  5246. end;
  5247. end;
  5248. if { If -O2 and under, it may stop on any old instruction }
  5249. (cs_opt_level3 in current_settings.optimizerswitches) and
  5250. (taicpu(p).oper[1]^.typ = top_reg) and
  5251. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5252. begin
  5253. hp1_last := p_dist;
  5254. Continue;
  5255. end;
  5256. Break;
  5257. end;
  5258. end;
  5259. { Search for:
  5260. test %reg,%reg
  5261. j(c1) @lbl1
  5262. ...
  5263. @lbl:
  5264. test %reg,%reg (same register)
  5265. j(c2) @lbl2
  5266. If c2 is a subset of c1, change to:
  5267. test %reg,%reg
  5268. j(c1) @lbl2
  5269. (@lbl1 may become a dead label as a result)
  5270. }
  5271. if (taicpu(p).oper[1]^.typ = top_reg) and
  5272. (taicpu(p).oper[0]^.typ = top_reg) and
  5273. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5274. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5275. Assigned(p_label) and
  5276. GetNextInstruction(p_label, p_dist) and
  5277. MatchInstruction(p_dist, A_TEST, []) and
  5278. { It's fine if the second test uses smaller sub-registers }
  5279. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5280. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5281. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5282. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5283. GetNextInstruction(p_dist, hp1_dist) and
  5284. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5285. begin
  5286. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5287. if JumpLabel = JumpLabel_dist then
  5288. { This is an infinite loop }
  5289. Exit;
  5290. { Best optimisation when the first condition is a subset (or equal) of the second }
  5291. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5292. begin
  5293. { Any registers used here will already be allocated }
  5294. if Assigned(JumpLabel) then
  5295. JumpLabel.DecRefs;
  5296. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5297. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5298. Result := True;
  5299. Exit;
  5300. end;
  5301. end;
  5302. end;
  5303. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5304. var
  5305. hp1, hp2: tai;
  5306. ActiveReg: TRegister;
  5307. OldOffset: asizeint;
  5308. ThisConst: TCGInt;
  5309. function RegDeallocated: Boolean;
  5310. begin
  5311. TransferUsedRegs(TmpUsedRegs);
  5312. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5313. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5314. end;
  5315. begin
  5316. result:=false;
  5317. hp1 := nil;
  5318. { replace
  5319. addX const,%reg1
  5320. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5321. dealloc %reg1
  5322. by
  5323. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5324. }
  5325. if MatchOpType(taicpu(p),top_const,top_reg) then
  5326. begin
  5327. ActiveReg := taicpu(p).oper[1]^.reg;
  5328. { Ensures the entire register was updated }
  5329. if (taicpu(p).opsize >= S_L) and
  5330. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5331. MatchInstruction(hp1,A_LEA,[]) and
  5332. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5333. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5334. (
  5335. { Cover the case where the register in the reference is also the destination register }
  5336. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5337. (
  5338. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5339. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5340. RegDeallocated
  5341. )
  5342. ) then
  5343. begin
  5344. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5345. {$push}
  5346. {$R-}{$Q-}
  5347. { Explicitly disable overflow checking for these offset calculation
  5348. as those do not matter for the final result }
  5349. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5350. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5351. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5352. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5353. {$pop}
  5354. {$ifdef x86_64}
  5355. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5356. begin
  5357. { Overflow; abort }
  5358. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5359. end
  5360. else
  5361. {$endif x86_64}
  5362. begin
  5363. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5364. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5365. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5366. RemoveCurrentP(p, hp1)
  5367. else
  5368. RemoveCurrentP(p);
  5369. result:=true;
  5370. Exit;
  5371. end;
  5372. end;
  5373. if (
  5374. { Save calling GetNextInstructionUsingReg again }
  5375. Assigned(hp1) or
  5376. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5377. ) and
  5378. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5379. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5380. begin
  5381. if taicpu(hp1).oper[0]^.typ = top_const then
  5382. begin
  5383. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5384. if taicpu(hp1).opcode = A_ADD then
  5385. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5386. else
  5387. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5388. Result := True;
  5389. { Handle any overflows }
  5390. case taicpu(p).opsize of
  5391. S_B:
  5392. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5393. S_W:
  5394. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5395. S_L:
  5396. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5397. {$ifdef x86_64}
  5398. S_Q:
  5399. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5400. { Overflow; abort }
  5401. Result := False
  5402. else
  5403. taicpu(p).oper[0]^.val := ThisConst;
  5404. {$endif x86_64}
  5405. else
  5406. InternalError(2021102610);
  5407. end;
  5408. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5409. if Result then
  5410. begin
  5411. if (taicpu(p).oper[0]^.val < 0) and
  5412. (
  5413. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5414. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5415. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5416. ) then
  5417. begin
  5418. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5419. taicpu(p).opcode := A_SUB;
  5420. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5421. end
  5422. else
  5423. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5424. RemoveInstruction(hp1);
  5425. end;
  5426. end
  5427. else
  5428. begin
  5429. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5430. TransferUsedRegs(TmpUsedRegs);
  5431. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5432. hp2 := p;
  5433. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5434. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5435. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5436. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5437. begin
  5438. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5439. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5440. Asml.Remove(p);
  5441. Asml.InsertAfter(p, hp1);
  5442. p := hp1;
  5443. Result := True;
  5444. Exit;
  5445. end;
  5446. end;
  5447. end;
  5448. if DoArithCombineOpt(p) then
  5449. Result:=true;
  5450. end;
  5451. end;
  5452. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5453. var
  5454. hp1, hp2: tai;
  5455. ref: Integer;
  5456. saveref: treference;
  5457. offsetcalc: Int64;
  5458. TempReg: TRegister;
  5459. Multiple: TCGInt;
  5460. Adjacent, IntermediateRegDiscarded: Boolean;
  5461. begin
  5462. Result:=false;
  5463. { play save and throw an error if LEA uses a seg register prefix,
  5464. this is most likely an error somewhere else }
  5465. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5466. internalerror(2022022001);
  5467. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5468. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5469. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5470. (
  5471. { do not mess with leas accessing the stack pointer
  5472. unless it's a null operation }
  5473. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5474. (
  5475. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5476. (taicpu(p).oper[0]^.ref^.offset = 0)
  5477. )
  5478. ) and
  5479. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5480. begin
  5481. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5482. begin
  5483. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5484. begin
  5485. taicpu(p).opcode := A_MOV;
  5486. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5487. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5488. end
  5489. else
  5490. begin
  5491. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5492. RemoveCurrentP(p);
  5493. end;
  5494. Result:=true;
  5495. exit;
  5496. end
  5497. else if (
  5498. { continue to use lea to adjust the stack pointer,
  5499. it is the recommended way, but only if not optimizing for size }
  5500. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5501. (cs_opt_size in current_settings.optimizerswitches)
  5502. ) and
  5503. { If the flags register is in use, don't change the instruction
  5504. to an ADD otherwise this will scramble the flags. [Kit] }
  5505. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5506. ConvertLEA(taicpu(p)) then
  5507. begin
  5508. Result:=true;
  5509. exit;
  5510. end;
  5511. end;
  5512. { Don't optimise if the stack or frame pointer is the destination register }
  5513. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5514. Exit;
  5515. if GetNextInstruction(p,hp1) and
  5516. (hp1.typ=ait_instruction) then
  5517. begin
  5518. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5519. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5520. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5521. begin
  5522. TransferUsedRegs(TmpUsedRegs);
  5523. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5524. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5525. begin
  5526. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5527. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5528. RemoveInstruction(hp1);
  5529. result:=true;
  5530. exit;
  5531. end;
  5532. end;
  5533. { changes
  5534. lea <ref1>, reg1
  5535. <op> ...,<ref. with reg1>,...
  5536. to
  5537. <op> ...,<ref1>,... }
  5538. { find a reference which uses reg1 }
  5539. 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
  5540. ref:=0
  5541. 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
  5542. ref:=1
  5543. else
  5544. ref:=-1;
  5545. if (ref<>-1) and
  5546. { reg1 must be either the base or the index }
  5547. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5548. begin
  5549. { reg1 can be removed from the reference }
  5550. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5551. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5552. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5553. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5554. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5555. else
  5556. Internalerror(2019111201);
  5557. { check if the can insert all data of the lea into the second instruction }
  5558. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5559. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5560. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5561. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5562. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5563. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5564. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5565. {$ifdef x86_64}
  5566. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5567. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5568. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5569. )
  5570. {$endif x86_64}
  5571. then
  5572. begin
  5573. { reg1 might not used by the second instruction after it is remove from the reference }
  5574. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5575. begin
  5576. TransferUsedRegs(TmpUsedRegs);
  5577. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5578. { reg1 is not updated so it might not be used afterwards }
  5579. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5580. begin
  5581. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5582. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5583. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5584. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5585. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5586. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5587. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5588. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5589. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5590. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5591. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5592. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5593. RemoveCurrentP(p, hp1);
  5594. result:=true;
  5595. exit;
  5596. end
  5597. end;
  5598. end;
  5599. { recover }
  5600. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5601. end;
  5602. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5603. if Adjacent or
  5604. { Check further ahead (up to 2 instructions ahead for -O2) }
  5605. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5606. begin
  5607. { Check common LEA/LEA conditions }
  5608. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5609. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5610. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5611. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5612. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5613. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5614. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5615. (
  5616. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5617. calling it (since it calls GetNextInstruction) }
  5618. Adjacent or
  5619. (
  5620. (
  5621. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5622. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5623. ) and (
  5624. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5625. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5626. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5627. )
  5628. )
  5629. ) then
  5630. begin
  5631. TransferUsedRegs(TmpUsedRegs);
  5632. hp2 := p;
  5633. repeat
  5634. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5635. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5636. IntermediateRegDiscarded :=
  5637. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5638. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5639. { changes
  5640. lea offset1(regX,scale), reg1
  5641. lea offset2(reg1,reg1), reg2
  5642. to
  5643. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5644. and
  5645. lea offset1(regX,scale1), reg1
  5646. lea offset2(reg1,scale2), reg2
  5647. to
  5648. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5649. and
  5650. lea offset1(regX,scale1), reg1
  5651. lea offset2(reg3,reg1,scale2), reg2
  5652. to
  5653. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5654. ... so long as the final scale does not exceed 8
  5655. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5656. }
  5657. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5658. (
  5659. { Don't optimise if size is a concern and the intermediate register remains in use }
  5660. IntermediateRegDiscarded or
  5661. not (cs_opt_size in current_settings.optimizerswitches)
  5662. ) and
  5663. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5664. (
  5665. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5666. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5667. ) and (
  5668. (
  5669. { lea (reg1,scale2), reg2 variant }
  5670. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5671. (
  5672. Adjacent or
  5673. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5674. ) and
  5675. (
  5676. (
  5677. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5678. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5679. ) or (
  5680. { lea (regX,regX), reg1 variant }
  5681. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5682. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5683. )
  5684. )
  5685. ) or (
  5686. { lea (reg1,reg1), reg1 variant }
  5687. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5688. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5689. )
  5690. ) then
  5691. begin
  5692. { Make everything homogeneous to make calculations easier }
  5693. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5694. begin
  5695. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5696. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5697. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5698. else
  5699. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5700. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5701. end;
  5702. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5703. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5704. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5705. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5706. begin
  5707. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5708. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5709. begin
  5710. { Put the register to change in the index register }
  5711. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5712. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5713. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5714. end;
  5715. { Change lea (reg,reg) to lea(,reg,2) }
  5716. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5717. begin
  5718. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5719. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5720. end;
  5721. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5722. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5723. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5724. { Just to prevent miscalculations }
  5725. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5726. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5727. else
  5728. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5729. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5730. if IntermediateRegDiscarded then
  5731. begin
  5732. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5733. RemoveCurrentP(p);
  5734. end
  5735. else
  5736. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5737. result:=true;
  5738. exit;
  5739. end;
  5740. end;
  5741. { changes
  5742. lea offset1(regX), reg1
  5743. lea offset2(reg1), reg2
  5744. to
  5745. lea offset1+offset2(regX), reg2 }
  5746. if (
  5747. { Don't optimise if size is a concern and the intermediate register remains in use }
  5748. IntermediateRegDiscarded or
  5749. not (cs_opt_size in current_settings.optimizerswitches)
  5750. ) and
  5751. (
  5752. (
  5753. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5754. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5755. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5756. ) or (
  5757. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5758. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5759. (
  5760. (
  5761. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5762. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5763. ) or (
  5764. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5765. (
  5766. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5767. (
  5768. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5769. (
  5770. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5771. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5772. )
  5773. )
  5774. )
  5775. )
  5776. )
  5777. )
  5778. ) then
  5779. begin
  5780. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5781. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5782. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5783. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5784. begin
  5785. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5786. begin
  5787. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5788. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5789. { if the register is used as index and base, we have to increase for base as well
  5790. and adapt base }
  5791. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5792. begin
  5793. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5794. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5795. end;
  5796. end
  5797. else
  5798. begin
  5799. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5800. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5801. end;
  5802. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5803. begin
  5804. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5805. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5806. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5807. { Catch the situation where the base = index
  5808. and treat this as *2. The scalefactor of
  5809. p will be 0 or 1 due to the conditional
  5810. checks above. Fixes i40647 }
  5811. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5812. else
  5813. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5814. end;
  5815. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5816. if IntermediateRegDiscarded then
  5817. begin
  5818. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5819. RemoveCurrentP(p);
  5820. end
  5821. else
  5822. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5823. result:=true;
  5824. exit;
  5825. end;
  5826. end;
  5827. end;
  5828. { Change:
  5829. leal/q $x(%reg1),%reg2
  5830. ...
  5831. shll/q $y,%reg2
  5832. To:
  5833. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5834. }
  5835. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5836. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5837. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5838. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5839. (taicpu(hp1).oper[0]^.val <= 3) then
  5840. begin
  5841. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5842. TransferUsedRegs(TmpUsedRegs);
  5843. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5844. if
  5845. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5846. (this works even if scalefactor is zero) }
  5847. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5848. { Ensure offset doesn't go out of bounds }
  5849. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5850. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5851. (
  5852. (
  5853. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5854. (
  5855. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5856. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5857. (
  5858. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5859. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5860. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5861. )
  5862. )
  5863. ) or (
  5864. (
  5865. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5866. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5867. ) and
  5868. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5869. )
  5870. ) then
  5871. begin
  5872. repeat
  5873. with taicpu(p).oper[0]^.ref^ do
  5874. begin
  5875. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5876. if index = base then
  5877. begin
  5878. if Multiple > 4 then
  5879. { Optimisation will no longer work because resultant
  5880. scale factor will exceed 8 }
  5881. Break;
  5882. base := NR_NO;
  5883. scalefactor := 2;
  5884. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5885. end
  5886. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5887. begin
  5888. { Scale factor only works on the index register }
  5889. index := base;
  5890. base := NR_NO;
  5891. end;
  5892. { For safety }
  5893. if scalefactor <= 1 then
  5894. begin
  5895. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5896. scalefactor := Multiple;
  5897. end
  5898. else
  5899. begin
  5900. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5901. scalefactor := scalefactor * Multiple;
  5902. end;
  5903. offset := offset * Multiple;
  5904. end;
  5905. RemoveInstruction(hp1);
  5906. Result := True;
  5907. Exit;
  5908. { This repeat..until loop exists for the benefit of Break }
  5909. until True;
  5910. end;
  5911. end;
  5912. end;
  5913. end;
  5914. end;
  5915. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5916. var
  5917. hp1 : tai;
  5918. SubInstr: Boolean;
  5919. ThisConst: TCGInt;
  5920. const
  5921. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5922. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5923. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5924. begin
  5925. Result := False;
  5926. if taicpu(p).oper[0]^.typ <> top_const then
  5927. { Should have been confirmed before calling }
  5928. InternalError(2021102601);
  5929. SubInstr := (taicpu(p).opcode = A_SUB);
  5930. if GetLastInstruction(p, hp1) and
  5931. (hp1.typ = ait_instruction) and
  5932. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5933. begin
  5934. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5935. { Bad size }
  5936. InternalError(2022042001);
  5937. case taicpu(hp1).opcode Of
  5938. A_INC:
  5939. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5940. begin
  5941. if SubInstr then
  5942. ThisConst := taicpu(p).oper[0]^.val - 1
  5943. else
  5944. ThisConst := taicpu(p).oper[0]^.val + 1;
  5945. end
  5946. else
  5947. Exit;
  5948. A_DEC:
  5949. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5950. begin
  5951. if SubInstr then
  5952. ThisConst := taicpu(p).oper[0]^.val + 1
  5953. else
  5954. ThisConst := taicpu(p).oper[0]^.val - 1;
  5955. end
  5956. else
  5957. Exit;
  5958. A_SUB:
  5959. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5960. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5961. begin
  5962. if SubInstr then
  5963. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5964. else
  5965. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5966. end
  5967. else
  5968. Exit;
  5969. A_ADD:
  5970. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5971. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5972. begin
  5973. if SubInstr then
  5974. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5975. else
  5976. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5977. end
  5978. else
  5979. Exit;
  5980. else
  5981. Exit;
  5982. end;
  5983. { Check that the values are in range }
  5984. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5985. { Overflow; abort }
  5986. Exit;
  5987. if (ThisConst = 0) then
  5988. begin
  5989. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5990. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5991. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5992. RemoveInstruction(hp1);
  5993. hp1 := tai(p.next);
  5994. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5995. if not GetLastInstruction(hp1, p) then
  5996. p := hp1;
  5997. end
  5998. else
  5999. begin
  6000. if taicpu(hp1).opercnt=1 then
  6001. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6002. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6003. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6004. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6005. else
  6006. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6007. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6008. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6009. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6010. RemoveInstruction(hp1);
  6011. taicpu(p).loadconst(0, ThisConst);
  6012. end;
  6013. Result := True;
  6014. end;
  6015. end;
  6016. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6017. begin
  6018. Result := False;
  6019. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6020. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6021. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6022. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6023. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6024. (
  6025. (
  6026. (taicpu(hp1).opcode = A_TEST)
  6027. ) or (
  6028. (taicpu(hp1).opcode = A_CMP) and
  6029. { A sanity check more than anything }
  6030. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6031. )
  6032. ) then
  6033. begin
  6034. { change
  6035. mov mem, %reg
  6036. ...
  6037. cmp/test x, %reg / test %reg,%reg
  6038. (reg deallocated)
  6039. to
  6040. cmp/test x, mem / cmp 0, mem
  6041. }
  6042. TransferUsedRegs(TmpUsedRegs);
  6043. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6044. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6045. begin
  6046. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6047. if (taicpu(hp1).opcode = A_TEST) and
  6048. (
  6049. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6050. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6051. ) then
  6052. begin
  6053. taicpu(hp1).opcode := A_CMP;
  6054. taicpu(hp1).loadconst(0, 0);
  6055. end;
  6056. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6057. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6058. RemoveCurrentP(p);
  6059. if (p <> hp1) then
  6060. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6061. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6062. { Make sure the flags are allocated across the CMP instruction }
  6063. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6064. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6065. Result := True;
  6066. Exit;
  6067. end;
  6068. end;
  6069. end;
  6070. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6071. var
  6072. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6073. ThisReg, SecondReg: TRegister;
  6074. JumpLoc: TAsmLabel;
  6075. NewSize: TOpSize;
  6076. begin
  6077. Result := False;
  6078. {
  6079. Convert:
  6080. j<c> .L1
  6081. .L2:
  6082. mov 1,reg
  6083. jmp .L3 (or ret, although it might not be a RET yet)
  6084. .L1:
  6085. mov 0,reg
  6086. jmp .L3 (or ret)
  6087. ( As long as .L3 <> .L1 or .L2)
  6088. To:
  6089. mov 0,reg
  6090. set<not(c)> reg
  6091. jmp .L3 (or ret)
  6092. .L2:
  6093. mov 1,reg
  6094. jmp .L3 (or ret)
  6095. .L1:
  6096. mov 0,reg
  6097. jmp .L3 (or ret)
  6098. }
  6099. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6100. Exit;
  6101. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6102. if GetNextInstruction(hp_label, hp2) and
  6103. MatchInstruction(hp2,A_MOV,[]) and
  6104. (taicpu(hp2).oper[0]^.typ = top_const) and
  6105. (
  6106. (
  6107. (taicpu(hp2).oper[1]^.typ = top_reg)
  6108. {$ifdef i386}
  6109. { Under i386, ESI, EDI, EBP and ESP
  6110. don't have an 8-bit representation }
  6111. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6112. {$endif i386}
  6113. ) or (
  6114. {$ifdef i386}
  6115. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6116. {$endif i386}
  6117. (taicpu(hp2).opsize = S_B)
  6118. )
  6119. ) and
  6120. GetNextInstruction(hp2, hp3) and
  6121. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6122. (
  6123. (taicpu(hp3).opcode=A_RET) or
  6124. (
  6125. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6126. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6127. )
  6128. ) and
  6129. GetNextInstruction(hp3, hp4) and
  6130. (hp4.typ=ait_label) and
  6131. (tai_label(hp4).labsym=JumpLoc) and
  6132. (
  6133. not (cs_opt_size in current_settings.optimizerswitches) or
  6134. { If the initial jump is the label's only reference, then it will
  6135. become a dead label if the other conditions are met and hence
  6136. remove at least 2 instructions, including a jump }
  6137. (JumpLoc.getrefs = 1)
  6138. ) and
  6139. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6140. that will be optimised out }
  6141. GetNextInstruction(hp4, hp5) and
  6142. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6143. (taicpu(hp5).oper[0]^.typ = top_const) and
  6144. (
  6145. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6146. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6147. ) and
  6148. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6149. GetNextInstruction(hp5,hp6) and
  6150. (
  6151. (hp6.typ<>ait_label) or
  6152. SkipLabels(hp6, hp6)
  6153. ) and
  6154. (hp6.typ=ait_instruction) then
  6155. begin
  6156. { First, let's look at the two jumps that are hp3 and hp6 }
  6157. if not
  6158. (
  6159. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6160. (
  6161. (taicpu(hp6).opcode=A_RET) or
  6162. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6163. )
  6164. ) then
  6165. { If condition is False, then the JMP/RET instructions matched conventionally }
  6166. begin
  6167. { See if one of the jumps can be instantly converted into a RET }
  6168. if (taicpu(hp3).opcode=A_JMP) then
  6169. begin
  6170. { Reuse hp5 }
  6171. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6172. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6173. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6174. Exit;
  6175. if MatchInstruction(hp5, A_RET, []) then
  6176. begin
  6177. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6178. ConvertJumpToRET(hp3, hp5);
  6179. Result := True;
  6180. end
  6181. else
  6182. Exit;
  6183. end;
  6184. if (taicpu(hp6).opcode=A_JMP) then
  6185. begin
  6186. { Reuse hp5 }
  6187. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6188. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6189. Exit;
  6190. if MatchInstruction(hp5, A_RET, []) then
  6191. begin
  6192. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6193. ConvertJumpToRET(hp6, hp5);
  6194. Result := True;
  6195. end
  6196. else
  6197. Exit;
  6198. end;
  6199. if not
  6200. (
  6201. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6202. (
  6203. (taicpu(hp6).opcode=A_RET) or
  6204. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6205. )
  6206. ) then
  6207. { Still doesn't match }
  6208. Exit;
  6209. end;
  6210. if (taicpu(hp2).oper[0]^.val = 1) then
  6211. begin
  6212. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6213. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6214. end
  6215. else
  6216. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6217. if taicpu(hp2).opsize=S_B then
  6218. begin
  6219. if taicpu(hp2).oper[1]^.typ = top_reg then
  6220. begin
  6221. SecondReg := taicpu(hp2).oper[1]^.reg;
  6222. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6223. end
  6224. else
  6225. begin
  6226. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6227. SecondReg := NR_NO;
  6228. end;
  6229. hp_pos := p;
  6230. hp_allocstart := hp4;
  6231. end
  6232. else
  6233. begin
  6234. { Will be a register because the size can't be S_B otherwise }
  6235. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6236. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6237. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6238. if (cs_opt_size in current_settings.optimizerswitches) then
  6239. begin
  6240. { Favour using MOVZX when optimising for size }
  6241. case taicpu(hp2).opsize of
  6242. S_W:
  6243. NewSize := S_BW;
  6244. S_L:
  6245. NewSize := S_BL;
  6246. {$ifdef x86_64}
  6247. S_Q:
  6248. begin
  6249. NewSize := S_BL;
  6250. { Will implicitly zero-extend to 64-bit }
  6251. setsubreg(SecondReg, R_SUBD);
  6252. end;
  6253. {$endif x86_64}
  6254. else
  6255. InternalError(2022101301);
  6256. end;
  6257. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6258. { Inserting it right before p will guarantee that the flags are also tracked }
  6259. Asml.InsertBefore(hp5, p);
  6260. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6261. hp_pos := hp5;
  6262. hp_allocstart := hp4;
  6263. end
  6264. else
  6265. begin
  6266. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6267. { Inserting it right before p will guarantee that the flags are also tracked }
  6268. Asml.InsertBefore(hp5, p);
  6269. hp_pos := p;
  6270. hp_allocstart := hp5;
  6271. end;
  6272. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6273. end;
  6274. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6275. taicpu(hp4).condition := taicpu(p).condition;
  6276. asml.InsertBefore(hp4, hp_pos);
  6277. if taicpu(hp3).is_jmp then
  6278. begin
  6279. JumpLoc.decrefs;
  6280. MakeUnconditional(taicpu(p));
  6281. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6282. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6283. end
  6284. else
  6285. ConvertJumpToRET(p, hp3);
  6286. if SecondReg <> NR_NO then
  6287. { Ensure the destination register is allocated over this region }
  6288. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6289. if (JumpLoc.getrefs = 0) then
  6290. RemoveDeadCodeAfterJump(hp3);
  6291. Result:=true;
  6292. exit;
  6293. end;
  6294. end;
  6295. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6296. var
  6297. hp1, hp2: tai;
  6298. ActiveReg: TRegister;
  6299. OldOffset: asizeint;
  6300. ThisConst: TCGInt;
  6301. function RegDeallocated: Boolean;
  6302. begin
  6303. TransferUsedRegs(TmpUsedRegs);
  6304. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6305. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6306. end;
  6307. begin
  6308. Result:=false;
  6309. hp1 := nil;
  6310. { replace
  6311. subX const,%reg1
  6312. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6313. dealloc %reg1
  6314. by
  6315. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6316. }
  6317. if MatchOpType(taicpu(p),top_const,top_reg) then
  6318. begin
  6319. ActiveReg := taicpu(p).oper[1]^.reg;
  6320. { Ensures the entire register was updated }
  6321. if (taicpu(p).opsize >= S_L) and
  6322. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6323. MatchInstruction(hp1,A_LEA,[]) and
  6324. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6325. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6326. (
  6327. { Cover the case where the register in the reference is also the destination register }
  6328. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6329. (
  6330. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6331. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6332. RegDeallocated
  6333. )
  6334. ) then
  6335. begin
  6336. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6337. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6338. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6339. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6340. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6341. {$ifdef x86_64}
  6342. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6343. begin
  6344. { Overflow; abort }
  6345. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6346. end
  6347. else
  6348. {$endif x86_64}
  6349. begin
  6350. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6351. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6352. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6353. RemoveCurrentP(p, hp1)
  6354. else
  6355. RemoveCurrentP(p);
  6356. result:=true;
  6357. Exit;
  6358. end;
  6359. end;
  6360. if (
  6361. { Save calling GetNextInstructionUsingReg again }
  6362. Assigned(hp1) or
  6363. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6364. ) and
  6365. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6366. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6367. begin
  6368. if taicpu(hp1).oper[0]^.typ = top_const then
  6369. begin
  6370. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6371. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6372. Result := True;
  6373. { Handle any overflows }
  6374. case taicpu(p).opsize of
  6375. S_B:
  6376. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6377. S_W:
  6378. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6379. S_L:
  6380. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6381. {$ifdef x86_64}
  6382. S_Q:
  6383. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6384. { Overflow; abort }
  6385. Result := False
  6386. else
  6387. taicpu(p).oper[0]^.val := ThisConst;
  6388. {$endif x86_64}
  6389. else
  6390. InternalError(2021102611);
  6391. end;
  6392. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6393. if Result then
  6394. begin
  6395. if (taicpu(p).oper[0]^.val < 0) and
  6396. (
  6397. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6398. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6399. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6400. ) then
  6401. begin
  6402. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6403. taicpu(p).opcode := A_SUB;
  6404. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6405. end
  6406. else
  6407. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6408. RemoveInstruction(hp1);
  6409. end;
  6410. end
  6411. else
  6412. begin
  6413. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6414. TransferUsedRegs(TmpUsedRegs);
  6415. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6416. hp2 := p;
  6417. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6418. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6419. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6420. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6421. begin
  6422. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6423. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6424. Asml.Remove(p);
  6425. Asml.InsertAfter(p, hp1);
  6426. p := hp1;
  6427. Result := True;
  6428. Exit;
  6429. end;
  6430. end;
  6431. end;
  6432. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6433. { * change "sub/add const1, reg" or "dec reg" followed by
  6434. "sub const2, reg" to one "sub ..., reg" }
  6435. {$ifdef i386}
  6436. if (taicpu(p).oper[0]^.val = 2) and
  6437. (ActiveReg = NR_ESP) and
  6438. { Don't do the sub/push optimization if the sub }
  6439. { comes from setting up the stack frame (JM) }
  6440. (not(GetLastInstruction(p,hp1)) or
  6441. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6442. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6443. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6444. begin
  6445. hp1 := tai(p.next);
  6446. while Assigned(hp1) and
  6447. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6448. not RegReadByInstruction(NR_ESP,hp1) and
  6449. not RegModifiedByInstruction(NR_ESP,hp1) do
  6450. hp1 := tai(hp1.next);
  6451. if Assigned(hp1) and
  6452. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6453. begin
  6454. taicpu(hp1).changeopsize(S_L);
  6455. if taicpu(hp1).oper[0]^.typ=top_reg then
  6456. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6457. hp1 := tai(p.next);
  6458. RemoveCurrentp(p, hp1);
  6459. Result:=true;
  6460. exit;
  6461. end;
  6462. end;
  6463. {$endif i386}
  6464. if DoArithCombineOpt(p) then
  6465. Result:=true;
  6466. end;
  6467. end;
  6468. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6469. var
  6470. TmpBool1,TmpBool2 : Boolean;
  6471. tmpref : treference;
  6472. hp1,hp2: tai;
  6473. mask, shiftval: tcgint;
  6474. begin
  6475. Result:=false;
  6476. { All these optimisations work on "shl/sal const,%reg" }
  6477. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6478. Exit;
  6479. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6480. (taicpu(p).oper[0]^.val <= 3) then
  6481. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6482. begin
  6483. { should we check the next instruction? }
  6484. TmpBool1 := True;
  6485. { have we found an add/sub which could be
  6486. integrated in the lea? }
  6487. TmpBool2 := False;
  6488. reference_reset(tmpref,2,[]);
  6489. TmpRef.index := taicpu(p).oper[1]^.reg;
  6490. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6491. while TmpBool1 and
  6492. GetNextInstruction(p, hp1) and
  6493. (tai(hp1).typ = ait_instruction) and
  6494. ((((taicpu(hp1).opcode = A_ADD) or
  6495. (taicpu(hp1).opcode = A_SUB)) and
  6496. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6497. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6498. (((taicpu(hp1).opcode = A_INC) or
  6499. (taicpu(hp1).opcode = A_DEC)) and
  6500. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6501. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6502. ((taicpu(hp1).opcode = A_LEA) and
  6503. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6504. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6505. (not GetNextInstruction(hp1,hp2) or
  6506. not instrReadsFlags(hp2)) Do
  6507. begin
  6508. TmpBool1 := False;
  6509. if taicpu(hp1).opcode=A_LEA then
  6510. begin
  6511. if (TmpRef.base = NR_NO) and
  6512. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6513. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6514. { Segment register isn't a concern here }
  6515. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6516. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6517. begin
  6518. TmpBool1 := True;
  6519. TmpBool2 := True;
  6520. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6521. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6522. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6523. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6524. RemoveInstruction(hp1);
  6525. end
  6526. end
  6527. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6528. begin
  6529. TmpBool1 := True;
  6530. TmpBool2 := True;
  6531. case taicpu(hp1).opcode of
  6532. A_ADD:
  6533. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6534. A_SUB:
  6535. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6536. else
  6537. internalerror(2019050536);
  6538. end;
  6539. RemoveInstruction(hp1);
  6540. end
  6541. else
  6542. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6543. (((taicpu(hp1).opcode = A_ADD) and
  6544. (TmpRef.base = NR_NO)) or
  6545. (taicpu(hp1).opcode = A_INC) or
  6546. (taicpu(hp1).opcode = A_DEC)) then
  6547. begin
  6548. TmpBool1 := True;
  6549. TmpBool2 := True;
  6550. case taicpu(hp1).opcode of
  6551. A_ADD:
  6552. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6553. A_INC:
  6554. inc(TmpRef.offset);
  6555. A_DEC:
  6556. dec(TmpRef.offset);
  6557. else
  6558. internalerror(2019050535);
  6559. end;
  6560. RemoveInstruction(hp1);
  6561. end;
  6562. end;
  6563. if TmpBool2
  6564. {$ifndef x86_64}
  6565. or
  6566. ((current_settings.optimizecputype < cpu_Pentium2) and
  6567. (taicpu(p).oper[0]^.val <= 3) and
  6568. not(cs_opt_size in current_settings.optimizerswitches))
  6569. {$endif x86_64}
  6570. then
  6571. begin
  6572. if not(TmpBool2) and
  6573. (taicpu(p).oper[0]^.val=1) then
  6574. begin
  6575. taicpu(p).opcode := A_ADD;
  6576. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6577. end
  6578. else
  6579. begin
  6580. taicpu(p).opcode := A_LEA;
  6581. taicpu(p).loadref(0, TmpRef);
  6582. end;
  6583. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6584. Result := True;
  6585. end;
  6586. end
  6587. {$ifndef x86_64}
  6588. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6589. begin
  6590. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6591. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6592. (unlike shl, which is only Tairable in the U pipe) }
  6593. if taicpu(p).oper[0]^.val=1 then
  6594. begin
  6595. taicpu(p).opcode := A_ADD;
  6596. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6597. Result := True;
  6598. end
  6599. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6600. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6601. else if (taicpu(p).opsize = S_L) and
  6602. (taicpu(p).oper[0]^.val<= 3) then
  6603. begin
  6604. reference_reset(tmpref,2,[]);
  6605. TmpRef.index := taicpu(p).oper[1]^.reg;
  6606. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6607. taicpu(p).opcode := A_LEA;
  6608. taicpu(p).loadref(0, TmpRef);
  6609. Result := True;
  6610. end;
  6611. end
  6612. {$endif x86_64}
  6613. else if
  6614. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6615. (
  6616. (
  6617. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6618. SetAndTest(hp1, hp2)
  6619. {$ifdef x86_64}
  6620. ) or
  6621. (
  6622. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6623. GetNextInstruction(hp1, hp2) and
  6624. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6625. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6626. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6627. {$endif x86_64}
  6628. )
  6629. ) and
  6630. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6631. begin
  6632. { Change:
  6633. shl x, %reg1
  6634. mov -(1<<x), %reg2
  6635. and %reg2, %reg1
  6636. Or:
  6637. shl x, %reg1
  6638. and -(1<<x), %reg1
  6639. To just:
  6640. shl x, %reg1
  6641. Since the and operation only zeroes bits that are already zero from the shl operation
  6642. }
  6643. case taicpu(p).oper[0]^.val of
  6644. 8:
  6645. mask:=$FFFFFFFFFFFFFF00;
  6646. 16:
  6647. mask:=$FFFFFFFFFFFF0000;
  6648. 32:
  6649. mask:=$FFFFFFFF00000000;
  6650. 63:
  6651. { Constant pre-calculated to prevent overflow errors with Int64 }
  6652. mask:=$8000000000000000;
  6653. else
  6654. begin
  6655. if taicpu(p).oper[0]^.val >= 64 then
  6656. { Shouldn't happen realistically, since the register
  6657. is guaranteed to be set to zero at this point }
  6658. mask := 0
  6659. else
  6660. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6661. end;
  6662. end;
  6663. if taicpu(hp1).oper[0]^.val = mask then
  6664. begin
  6665. { Everything checks out, perform the optimisation, as long as
  6666. the FLAGS register isn't being used}
  6667. TransferUsedRegs(TmpUsedRegs);
  6668. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6669. {$ifdef x86_64}
  6670. if (hp1 <> hp2) then
  6671. begin
  6672. { "shl/mov/and" version }
  6673. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6674. { Don't do the optimisation if the FLAGS register is in use }
  6675. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6676. begin
  6677. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6678. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6679. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6680. begin
  6681. RemoveInstruction(hp1);
  6682. Result := True;
  6683. end;
  6684. { Only set Result to True if the 'mov' instruction was removed }
  6685. RemoveInstruction(hp2);
  6686. end;
  6687. end
  6688. else
  6689. {$endif x86_64}
  6690. begin
  6691. { "shl/and" version }
  6692. { Don't do the optimisation if the FLAGS register is in use }
  6693. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6694. begin
  6695. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6696. RemoveInstruction(hp1);
  6697. Result := True;
  6698. end;
  6699. end;
  6700. Exit;
  6701. end
  6702. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6703. begin
  6704. { Even if the mask doesn't allow for its removal, we might be
  6705. able to optimise the mask for the "shl/and" version, which
  6706. may permit other peephole optimisations }
  6707. {$ifdef DEBUG_AOPTCPU}
  6708. mask := taicpu(hp1).oper[0]^.val and mask;
  6709. if taicpu(hp1).oper[0]^.val <> mask then
  6710. begin
  6711. DebugMsg(
  6712. SPeepholeOptimization +
  6713. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6714. ' to $' + debug_tostr(mask) +
  6715. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6716. taicpu(hp1).oper[0]^.val := mask;
  6717. end;
  6718. {$else DEBUG_AOPTCPU}
  6719. { If debugging is off, just set the operand even if it's the same }
  6720. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6721. {$endif DEBUG_AOPTCPU}
  6722. end;
  6723. end;
  6724. {
  6725. change
  6726. shl/sal const,reg
  6727. <op> ...(...,reg,1),...
  6728. into
  6729. <op> ...(...,reg,1 shl const),...
  6730. if const in 1..3
  6731. }
  6732. if MatchOpType(taicpu(p), top_const, top_reg) and
  6733. (taicpu(p).oper[0]^.val in [1..3]) and
  6734. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6735. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6736. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6737. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6738. MatchOpType(taicpu(hp1),top_ref))
  6739. ) and
  6740. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6741. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6742. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6743. begin
  6744. TransferUsedRegs(TmpUsedRegs);
  6745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6746. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6747. begin
  6748. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6749. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6750. RemoveCurrentP(p);
  6751. Result:=true;
  6752. exit;
  6753. end;
  6754. end;
  6755. if MatchOpType(taicpu(p), top_const, top_reg) and
  6756. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6757. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6758. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6759. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6760. begin
  6761. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6762. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6763. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6764. {$ifdef x86_64}
  6765. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6766. {$endif x86_64}
  6767. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6768. begin
  6769. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6770. taicpu(hp1).opcode:=A_MOV;
  6771. taicpu(hp1).oper[0]^.val:=0;
  6772. end
  6773. else
  6774. begin
  6775. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6776. taicpu(hp1).oper[0]^.val:=shiftval;
  6777. end;
  6778. RemoveCurrentP(p);
  6779. Result:=true;
  6780. exit;
  6781. end;
  6782. end;
  6783. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6784. begin
  6785. case shr_size of
  6786. S_B:
  6787. { No valid combinations }
  6788. Result := False;
  6789. S_W:
  6790. Result := (Shift >= 8) and (movz_size = S_BW);
  6791. S_L:
  6792. Result :=
  6793. (Shift >= 24) { Any opsize is valid for this shift } or
  6794. ((Shift >= 16) and (movz_size = S_WL));
  6795. {$ifdef x86_64}
  6796. S_Q:
  6797. Result :=
  6798. (Shift >= 56) { Any opsize is valid for this shift } or
  6799. ((Shift >= 48) and (movz_size = S_WL));
  6800. {$endif x86_64}
  6801. else
  6802. InternalError(2022081510);
  6803. end;
  6804. end;
  6805. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6806. var
  6807. hp1, hp2: tai;
  6808. Shift: TCGInt;
  6809. LimitSize: Topsize;
  6810. DoNotMerge: Boolean;
  6811. begin
  6812. Result := False;
  6813. { All these optimisations work on "shr const,%reg" }
  6814. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6815. Exit;
  6816. DoNotMerge := False;
  6817. Shift := taicpu(p).oper[0]^.val;
  6818. LimitSize := taicpu(p).opsize;
  6819. hp1 := p;
  6820. repeat
  6821. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6822. Exit;
  6823. case taicpu(hp1).opcode of
  6824. A_TEST, A_CMP, A_Jcc:
  6825. { Skip over conditional jumps and relevant comparisons }
  6826. Continue;
  6827. A_MOVZX:
  6828. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6829. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6830. begin
  6831. { Since the original register is being read as is, subsequent
  6832. SHRs must not be merged at this point }
  6833. DoNotMerge := True;
  6834. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6835. begin
  6836. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6837. begin
  6838. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6839. taicpu(hp1).opcode := A_MOV;
  6840. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6841. case taicpu(hp1).opsize of
  6842. S_BW:
  6843. taicpu(hp1).opsize := S_W;
  6844. S_BL, S_WL:
  6845. taicpu(hp1).opsize := S_L;
  6846. else
  6847. InternalError(2022081503);
  6848. end;
  6849. { p itself hasn't changed, so no need to set Result to True }
  6850. Include(OptsToCheck, aoc_ForceNewIteration);
  6851. { See if there's anything afterwards that can be
  6852. optimised, since the input register hasn't changed }
  6853. Continue;
  6854. end;
  6855. { NOTE: If the MOVZX instruction reads and writes the same
  6856. register, defer this to the post-peephole optimisation stage }
  6857. Exit;
  6858. end;
  6859. end;
  6860. A_SHL, A_SAL, A_SHR:
  6861. if (taicpu(hp1).opsize <= LimitSize) and
  6862. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6863. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6864. begin
  6865. { Make sure the sizes don't exceed the register size limit
  6866. (measured by the shift value falling below the limit) }
  6867. if taicpu(hp1).opsize < LimitSize then
  6868. LimitSize := taicpu(hp1).opsize;
  6869. if taicpu(hp1).opcode = A_SHR then
  6870. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6871. else
  6872. begin
  6873. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6874. DoNotMerge := True;
  6875. end;
  6876. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6877. Exit;
  6878. { Since we've established that the combined shift is within
  6879. limits, we can actually combine the adjacent SHR
  6880. instructions even if they're different sizes }
  6881. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6882. begin
  6883. hp2 := tai(hp1.Previous);
  6884. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6885. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6886. RemoveInstruction(hp1);
  6887. hp1 := hp2;
  6888. { Though p has changed, only the constant has, and its
  6889. effects can still be detected on the next iteration of
  6890. the repeat..until loop }
  6891. Include(OptsToCheck, aoc_ForceNewIteration);
  6892. end;
  6893. { Move onto the next instruction }
  6894. Continue;
  6895. end;
  6896. else
  6897. ;
  6898. end;
  6899. Break;
  6900. until False;
  6901. end;
  6902. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6903. var
  6904. CurrentRef: TReference;
  6905. FullReg: TRegister;
  6906. hp1, hp2: tai;
  6907. begin
  6908. Result := False;
  6909. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6910. Exit;
  6911. { We assume you've checked if the operand is actually a reference by
  6912. this point. If it isn't, you'll most likely get an access violation }
  6913. CurrentRef := first_mov.oper[1]^.ref^;
  6914. { Memory must be aligned }
  6915. if (CurrentRef.offset mod 4) <> 0 then
  6916. Exit;
  6917. Inc(CurrentRef.offset);
  6918. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6919. if MatchOperand(second_mov.oper[0]^, 0) and
  6920. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6921. GetNextInstruction(second_mov, hp1) and
  6922. (hp1.typ = ait_instruction) and
  6923. (taicpu(hp1).opcode = A_MOV) and
  6924. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6925. (taicpu(hp1).oper[0]^.val = 0) then
  6926. begin
  6927. Inc(CurrentRef.offset);
  6928. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6929. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6930. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6931. begin
  6932. case taicpu(hp1).opsize of
  6933. S_B:
  6934. if GetNextInstruction(hp1, hp2) and
  6935. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6936. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6937. (taicpu(hp2).oper[0]^.val = 0) then
  6938. begin
  6939. Inc(CurrentRef.offset);
  6940. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6941. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6942. (taicpu(hp2).opsize = S_B) then
  6943. begin
  6944. RemoveInstruction(hp1);
  6945. RemoveInstruction(hp2);
  6946. first_mov.opsize := S_L;
  6947. if first_mov.oper[0]^.typ = top_reg then
  6948. begin
  6949. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6950. { Reuse second_mov as a MOVZX instruction }
  6951. second_mov.opcode := A_MOVZX;
  6952. second_mov.opsize := S_BL;
  6953. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6954. second_mov.loadreg(1, FullReg);
  6955. first_mov.oper[0]^.reg := FullReg;
  6956. asml.Remove(second_mov);
  6957. asml.InsertBefore(second_mov, first_mov);
  6958. end
  6959. else
  6960. { It's a value }
  6961. begin
  6962. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6963. RemoveInstruction(second_mov);
  6964. end;
  6965. Result := True;
  6966. Exit;
  6967. end;
  6968. end;
  6969. S_W:
  6970. begin
  6971. RemoveInstruction(hp1);
  6972. first_mov.opsize := S_L;
  6973. if first_mov.oper[0]^.typ = top_reg then
  6974. begin
  6975. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6976. { Reuse second_mov as a MOVZX instruction }
  6977. second_mov.opcode := A_MOVZX;
  6978. second_mov.opsize := S_BL;
  6979. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6980. second_mov.loadreg(1, FullReg);
  6981. first_mov.oper[0]^.reg := FullReg;
  6982. asml.Remove(second_mov);
  6983. asml.InsertBefore(second_mov, first_mov);
  6984. end
  6985. else
  6986. { It's a value }
  6987. begin
  6988. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6989. RemoveInstruction(second_mov);
  6990. end;
  6991. Result := True;
  6992. Exit;
  6993. end;
  6994. else
  6995. ;
  6996. end;
  6997. end;
  6998. end;
  6999. end;
  7000. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7001. { returns true if a "continue" should be done after this optimization }
  7002. var
  7003. hp1, hp2, hp3: tai;
  7004. begin
  7005. Result := false;
  7006. hp3 := nil;
  7007. if MatchOpType(taicpu(p),top_ref) and
  7008. GetNextInstruction(p, hp1) and
  7009. (hp1.typ = ait_instruction) and
  7010. (((taicpu(hp1).opcode = A_FLD) and
  7011. (taicpu(p).opcode = A_FSTP)) or
  7012. ((taicpu(p).opcode = A_FISTP) and
  7013. (taicpu(hp1).opcode = A_FILD))) and
  7014. MatchOpType(taicpu(hp1),top_ref) and
  7015. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7016. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7017. begin
  7018. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7019. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7020. GetNextInstruction(hp1, hp2) and
  7021. (((hp2.typ = ait_instruction) and
  7022. IsExitCode(hp2) and
  7023. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7024. not(assigned(current_procinfo.procdef.funcretsym) and
  7025. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7026. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7027. { fstp <temp>
  7028. fld <temp>
  7029. <dealloc> <temp>
  7030. }
  7031. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7032. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7033. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7034. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7035. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7036. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7037. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7038. )
  7039. )
  7040. ) then
  7041. begin
  7042. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7043. RemoveInstruction(hp1);
  7044. RemoveCurrentP(p, hp2);
  7045. { first case: exit code }
  7046. if hp2.typ = ait_instruction then
  7047. RemoveLastDeallocForFuncRes(p);
  7048. Result := true;
  7049. end
  7050. else
  7051. { we can do this only in fast math mode as fstp is rounding ...
  7052. ... still disabled as it breaks the compiler and/or rtl }
  7053. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7054. { ... or if another fstp equal to the first one follows }
  7055. GetNextInstruction(hp1,hp2) and
  7056. (hp2.typ = ait_instruction) and
  7057. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7058. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7059. begin
  7060. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7061. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7062. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7063. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7064. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7065. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7066. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7067. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7068. ) then
  7069. begin
  7070. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7071. RemoveCurrentP(p,hp2);
  7072. RemoveInstruction(hp1);
  7073. Result := true;
  7074. end
  7075. else if { fst can't store an extended/comp value }
  7076. (taicpu(p).opsize <> S_FX) and
  7077. (taicpu(p).opsize <> S_IQ) then
  7078. begin
  7079. if (taicpu(p).opcode = A_FSTP) then
  7080. taicpu(p).opcode := A_FST
  7081. else
  7082. taicpu(p).opcode := A_FIST;
  7083. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7084. RemoveInstruction(hp1);
  7085. Result := true;
  7086. end;
  7087. end;
  7088. end;
  7089. end;
  7090. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7091. var
  7092. hp1, hp2, hp3: tai;
  7093. begin
  7094. result:=false;
  7095. if MatchOpType(taicpu(p),top_reg) and
  7096. GetNextInstruction(p, hp1) and
  7097. (hp1.typ = Ait_Instruction) and
  7098. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7099. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7100. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7101. { change to
  7102. fld reg fxxx reg,st
  7103. fxxxp st, st1 (hp1)
  7104. Remark: non commutative operations must be reversed!
  7105. }
  7106. begin
  7107. case taicpu(hp1).opcode Of
  7108. A_FMULP,A_FADDP,
  7109. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7110. begin
  7111. case taicpu(hp1).opcode Of
  7112. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7113. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7114. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7115. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7116. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7117. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7118. else
  7119. internalerror(2019050534);
  7120. end;
  7121. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7122. taicpu(hp1).oper[1]^.reg := NR_ST;
  7123. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7124. RemoveCurrentP(p, hp1);
  7125. Result:=true;
  7126. exit;
  7127. end;
  7128. else
  7129. ;
  7130. end;
  7131. end
  7132. else
  7133. if MatchOpType(taicpu(p),top_ref) and
  7134. GetNextInstruction(p, hp2) and
  7135. (hp2.typ = Ait_Instruction) and
  7136. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7137. (taicpu(p).opsize in [S_FS, S_FL]) and
  7138. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7139. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7140. if GetLastInstruction(p, hp1) and
  7141. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7142. MatchOpType(taicpu(hp1),top_ref) and
  7143. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7144. if ((taicpu(hp2).opcode = A_FMULP) or
  7145. (taicpu(hp2).opcode = A_FADDP)) then
  7146. { change to
  7147. fld/fst mem1 (hp1) fld/fst mem1
  7148. fld mem1 (p) fadd/
  7149. faddp/ fmul st, st
  7150. fmulp st, st1 (hp2) }
  7151. begin
  7152. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7153. RemoveCurrentP(p, hp1);
  7154. if (taicpu(hp2).opcode = A_FADDP) then
  7155. taicpu(hp2).opcode := A_FADD
  7156. else
  7157. taicpu(hp2).opcode := A_FMUL;
  7158. taicpu(hp2).oper[1]^.reg := NR_ST;
  7159. end
  7160. else
  7161. { change to
  7162. fld/fst mem1 (hp1) fld/fst mem1
  7163. fld mem1 (p) fld st
  7164. }
  7165. begin
  7166. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7167. taicpu(p).changeopsize(S_FL);
  7168. taicpu(p).loadreg(0,NR_ST);
  7169. end
  7170. else
  7171. begin
  7172. case taicpu(hp2).opcode Of
  7173. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7174. { change to
  7175. fld/fst mem1 (hp1) fld/fst mem1
  7176. fld mem2 (p) fxxx mem2
  7177. fxxxp st, st1 (hp2) }
  7178. begin
  7179. case taicpu(hp2).opcode Of
  7180. A_FADDP: taicpu(p).opcode := A_FADD;
  7181. A_FMULP: taicpu(p).opcode := A_FMUL;
  7182. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7183. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7184. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7185. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7186. else
  7187. internalerror(2019050533);
  7188. end;
  7189. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7190. RemoveInstruction(hp2);
  7191. end
  7192. else
  7193. ;
  7194. end
  7195. end
  7196. end;
  7197. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7198. begin
  7199. Result := condition_in(cond1, cond2) or
  7200. { Not strictly subsets due to the actual flags checked, but because we're
  7201. comparing integers, E is a subset of AE and GE and their aliases }
  7202. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7203. end;
  7204. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7205. var
  7206. v: TCGInt;
  7207. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7208. FirstMatch, TempBool: Boolean;
  7209. NewReg: TRegister;
  7210. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7211. begin
  7212. Result:=false;
  7213. { All these optimisations need a next instruction }
  7214. if not GetNextInstruction(p, hp1) then
  7215. Exit;
  7216. true_hp1 := hp1;
  7217. { Search for:
  7218. cmp ###,###
  7219. j(c1) @lbl1
  7220. ...
  7221. @lbl:
  7222. cmp ###,### (same comparison as above)
  7223. j(c2) @lbl2
  7224. If c1 is a subset of c2, change to:
  7225. cmp ###,###
  7226. j(c1) @lbl2
  7227. (@lbl1 may become a dead label as a result)
  7228. }
  7229. { Also handle cases where there are multiple jumps in a row }
  7230. p_jump := hp1;
  7231. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7232. begin
  7233. Prefetch(p_jump.Next);
  7234. if IsJumpToLabel(taicpu(p_jump)) then
  7235. begin
  7236. { Do jump optimisations first in case the condition becomes
  7237. unnecessary }
  7238. TempBool := True;
  7239. if DoJumpOptimizations(p_jump, TempBool) or
  7240. not TempBool then
  7241. begin
  7242. if Assigned(p_jump) then
  7243. begin
  7244. { CollapseZeroDistJump will be set to the label or an align
  7245. before it after the jump if it optimises, whether or not
  7246. the label is live or dead }
  7247. if (p_jump.typ = ait_align) or
  7248. (
  7249. (p_jump.typ = ait_label) and
  7250. not (tai_label(p_jump).labsym.is_used)
  7251. ) then
  7252. GetNextInstruction(p_jump, p_jump);
  7253. end;
  7254. TransferUsedRegs(TmpUsedRegs);
  7255. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7256. if not Assigned(p_jump) or
  7257. (
  7258. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7259. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7260. ) then
  7261. begin
  7262. { No more conditional jumps; conditional statement is no longer required }
  7263. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7264. RemoveCurrentP(p);
  7265. Result := True;
  7266. Exit;
  7267. end;
  7268. hp1 := p_jump;
  7269. Include(OptsToCheck, aoc_ForceNewIteration);
  7270. Continue;
  7271. end;
  7272. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7273. if GetNextInstruction(p_jump, hp2) and
  7274. (
  7275. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7276. not TempBool
  7277. ) then
  7278. begin
  7279. hp1 := p_jump;
  7280. Include(OptsToCheck, aoc_ForceNewIteration);
  7281. Continue;
  7282. end;
  7283. p_label := nil;
  7284. if Assigned(JumpLabel) then
  7285. p_label := getlabelwithsym(JumpLabel);
  7286. if Assigned(p_label) and
  7287. GetNextInstruction(p_label, p_dist) and
  7288. MatchInstruction(p_dist, A_CMP, []) and
  7289. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7290. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7291. GetNextInstruction(p_dist, hp1_dist) and
  7292. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7293. begin
  7294. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7295. if JumpLabel = JumpLabel_dist then
  7296. { This is an infinite loop }
  7297. Exit;
  7298. { Best optimisation when the first condition is a subset (or equal) of the second }
  7299. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7300. begin
  7301. { Any registers used here will already be allocated }
  7302. if Assigned(JumpLabel) then
  7303. JumpLabel.DecRefs;
  7304. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7305. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7306. Include(OptsToCheck, aoc_ForceNewIteration);
  7307. { Don't exit yet. Since p and p_jump haven't actually been
  7308. removed, we can check for more on this iteration }
  7309. end
  7310. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7311. GetNextInstruction(hp1_dist, hp1_label) and
  7312. (hp1_label.typ = ait_label) then
  7313. begin
  7314. JumpLabel_far := tai_label(hp1_label).labsym;
  7315. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7316. { This is an infinite loop }
  7317. Exit;
  7318. if Assigned(JumpLabel_far) then
  7319. begin
  7320. { In this situation, if the first jump branches, the second one will never,
  7321. branch so change the destination label to after the second jump }
  7322. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7323. if Assigned(JumpLabel) then
  7324. JumpLabel.DecRefs;
  7325. JumpLabel_far.IncRefs;
  7326. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7327. Result := True;
  7328. { Don't exit yet. Since p and p_jump haven't actually been
  7329. removed, we can check for more on this iteration }
  7330. Continue;
  7331. end;
  7332. end;
  7333. end;
  7334. end;
  7335. { Search for:
  7336. cmp ###,###
  7337. j(c1) @lbl1
  7338. cmp ###,### (same as first)
  7339. Remove second cmp
  7340. }
  7341. if GetNextInstruction(p_jump, hp2) and
  7342. (
  7343. (
  7344. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7345. (
  7346. (
  7347. MatchOpType(taicpu(p), top_const, top_reg) and
  7348. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7349. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7350. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7351. ) or (
  7352. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7353. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7354. )
  7355. )
  7356. ) or (
  7357. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7358. MatchOperand(taicpu(p).oper[0]^, 0) and
  7359. (taicpu(p).oper[1]^.typ = top_reg) and
  7360. MatchInstruction(hp2, A_TEST, []) and
  7361. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7362. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7363. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7364. )
  7365. ) then
  7366. begin
  7367. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7368. TransferUsedRegs(TmpUsedRegs);
  7369. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7370. RemoveInstruction(hp2);
  7371. Result := True;
  7372. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7373. end
  7374. else
  7375. begin
  7376. { hp2 is the next instruction, so save time and just set p_jump
  7377. to it instead of calling GetNextInstruction below }
  7378. p_jump := hp2;
  7379. Continue;
  7380. end;
  7381. GetNextInstruction(p_jump, p_jump);
  7382. end;
  7383. if (
  7384. { Don't call GetNextInstruction again if we already have it }
  7385. (true_hp1 = p_jump) or
  7386. GetNextInstruction(p, hp1)
  7387. ) and
  7388. MatchInstruction(hp1, A_Jcc, []) and
  7389. IsJumpToLabel(taicpu(hp1)) and
  7390. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7391. GetNextInstruction(hp1, hp2) then
  7392. begin
  7393. {
  7394. cmp x, y (or "cmp y, x")
  7395. je @lbl
  7396. mov x, y
  7397. @lbl:
  7398. (x and y can be constants, registers or references)
  7399. Change to:
  7400. mov x, y (x and y will always be equal in the end)
  7401. @lbl: (may beceome a dead label)
  7402. Also:
  7403. cmp x, y (or "cmp y, x")
  7404. jne @lbl
  7405. mov x, y
  7406. @lbl:
  7407. (x and y can be constants, registers or references)
  7408. Change to:
  7409. Absolutely nothing! (Except @lbl if it's still live)
  7410. }
  7411. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7412. (
  7413. (
  7414. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7415. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7416. ) or (
  7417. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7418. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7419. )
  7420. ) and
  7421. GetNextInstruction(hp2, hp1_label) and
  7422. (hp1_label.typ = ait_label) and
  7423. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7424. begin
  7425. tai_label(hp1_label).labsym.DecRefs;
  7426. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7427. begin
  7428. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7429. RemoveInstruction(hp2);
  7430. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7431. end
  7432. else
  7433. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7434. RemoveInstruction(hp1);
  7435. RemoveCurrentp(p, hp2);
  7436. Result := True;
  7437. Exit;
  7438. end;
  7439. {
  7440. Try to optimise the following:
  7441. cmp $x,### ($x and $y can be registers or constants)
  7442. je @lbl1 (only reference)
  7443. cmp $y,### (### are identical)
  7444. @Lbl:
  7445. sete %reg1
  7446. Change to:
  7447. cmp $x,###
  7448. sete %reg2 (allocate new %reg2)
  7449. cmp $y,###
  7450. sete %reg1
  7451. orb %reg2,%reg1
  7452. (dealloc %reg2)
  7453. This adds an instruction (so don't perform under -Os), but it removes
  7454. a conditional branch.
  7455. }
  7456. if not (cs_opt_size in current_settings.optimizerswitches) and
  7457. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7458. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7459. { The first operand of CMP instructions can only be a register or
  7460. immediate anyway, so no need to check }
  7461. GetNextInstruction(hp2, p_label) and
  7462. (p_label.typ = ait_label) and
  7463. (tai_label(p_label).labsym.getrefs = 1) and
  7464. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7465. GetNextInstruction(p_label, p_dist) and
  7466. MatchInstruction(p_dist, A_SETcc, []) and
  7467. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7468. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7469. begin
  7470. TransferUsedRegs(TmpUsedRegs);
  7471. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7472. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7473. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7474. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7475. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7476. { Get the instruction after the SETcc instruction so we can
  7477. allocate a new register over the entire range }
  7478. GetNextInstruction(p_dist, hp1_dist) then
  7479. begin
  7480. { Register can appear in p if it's not used afterwards, so only
  7481. allocate between hp1 and hp1_dist }
  7482. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7483. if NewReg <> NR_NO then
  7484. begin
  7485. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7486. { Change the jump instruction into a SETcc instruction }
  7487. taicpu(hp1).opcode := A_SETcc;
  7488. taicpu(hp1).opsize := S_B;
  7489. taicpu(hp1).loadreg(0, NewReg);
  7490. { This is now a dead label }
  7491. tai_label(p_label).labsym.decrefs;
  7492. { Prefer adding before the next instruction so the FLAGS
  7493. register is deallicated first }
  7494. AsmL.InsertBefore(
  7495. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7496. hp1_dist
  7497. );
  7498. Result := True;
  7499. { Don't exit yet, as p wasn't changed and hp1, while
  7500. modified, is still intact and might be optimised by the
  7501. SETcc optimisation below }
  7502. end;
  7503. end;
  7504. end;
  7505. end;
  7506. if (taicpu(p).oper[0]^.typ = top_const) and
  7507. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7508. begin
  7509. if (taicpu(p).oper[0]^.val = 0) and
  7510. (taicpu(p).oper[1]^.typ = top_reg) then
  7511. begin
  7512. hp2 := p;
  7513. FirstMatch := True;
  7514. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7515. anything meaningful once it's converted to "test %reg,%reg";
  7516. additionally, some jumps will always (or never) branch, so
  7517. evaluate every jump immediately following the
  7518. comparison, optimising the conditions if possible.
  7519. Similarly with SETcc... those that are always set to 0 or 1
  7520. are changed to MOV instructions }
  7521. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7522. (
  7523. GetNextInstruction(hp2, hp1) and
  7524. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7525. ) do
  7526. begin
  7527. Prefetch(hp1.Next);
  7528. FirstMatch := False;
  7529. case taicpu(hp1).condition of
  7530. C_B, C_C, C_NAE, C_O:
  7531. { For B/NAE:
  7532. Will never branch since an unsigned integer can never be below zero
  7533. For C/O:
  7534. Result cannot overflow because 0 is being subtracted
  7535. }
  7536. begin
  7537. if taicpu(hp1).opcode = A_Jcc then
  7538. begin
  7539. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7540. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7541. RemoveInstruction(hp1);
  7542. { Since hp1 was deleted, hp2 must not be updated }
  7543. Continue;
  7544. end
  7545. else
  7546. begin
  7547. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7548. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7549. taicpu(hp1).opcode := A_MOV;
  7550. taicpu(hp1).ops := 2;
  7551. taicpu(hp1).condition := C_None;
  7552. taicpu(hp1).opsize := S_B;
  7553. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7554. taicpu(hp1).loadconst(0, 0);
  7555. end;
  7556. end;
  7557. C_BE, C_NA:
  7558. begin
  7559. { Will only branch if equal to zero }
  7560. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7561. taicpu(hp1).condition := C_E;
  7562. end;
  7563. C_A, C_NBE:
  7564. begin
  7565. { Will only branch if not equal to zero }
  7566. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7567. taicpu(hp1).condition := C_NE;
  7568. end;
  7569. C_AE, C_NB, C_NC, C_NO:
  7570. begin
  7571. { Will always branch }
  7572. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7573. if taicpu(hp1).opcode = A_Jcc then
  7574. begin
  7575. MakeUnconditional(taicpu(hp1));
  7576. { Any jumps/set that follow will now be dead code }
  7577. RemoveDeadCodeAfterJump(taicpu(hp1));
  7578. Break;
  7579. end
  7580. else
  7581. begin
  7582. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7583. taicpu(hp1).opcode := A_MOV;
  7584. taicpu(hp1).ops := 2;
  7585. taicpu(hp1).condition := C_None;
  7586. taicpu(hp1).opsize := S_B;
  7587. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7588. taicpu(hp1).loadconst(0, 1);
  7589. end;
  7590. end;
  7591. C_None:
  7592. InternalError(2020012201);
  7593. C_P, C_PE, C_NP, C_PO:
  7594. { We can't handle parity checks and they should never be generated
  7595. after a general-purpose CMP (it's used in some floating-point
  7596. comparisons that don't use CMP) }
  7597. InternalError(2020012202);
  7598. else
  7599. { Zero/Equality, Sign, their complements and all of the
  7600. signed comparisons do not need to be converted };
  7601. end;
  7602. hp2 := hp1;
  7603. end;
  7604. { Convert the instruction to a TEST }
  7605. taicpu(p).opcode := A_TEST;
  7606. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7607. Result := True;
  7608. Exit;
  7609. end
  7610. else
  7611. begin
  7612. TransferUsedRegs(TmpUsedRegs);
  7613. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7614. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7615. begin
  7616. if (taicpu(p).oper[0]^.val = 1) and
  7617. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7618. begin
  7619. { Convert; To:
  7620. cmp $1,r/m cmp $0,r/m
  7621. jl @lbl jle @lbl
  7622. (Also do inverted conditions)
  7623. }
  7624. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7625. taicpu(p).oper[0]^.val := 0;
  7626. if taicpu(hp1).condition in [C_L, C_NGE] then
  7627. taicpu(hp1).condition := C_LE
  7628. else
  7629. taicpu(hp1).condition := C_NLE;
  7630. { If the instruction is now "cmp $0,%reg", convert it to a
  7631. TEST (and effectively do the work of the "cmp $0,%reg" in
  7632. the block above)
  7633. }
  7634. if (taicpu(p).oper[1]^.typ = top_reg) then
  7635. begin
  7636. taicpu(p).opcode := A_TEST;
  7637. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7638. end;
  7639. Result := True;
  7640. Exit;
  7641. end
  7642. else if (taicpu(p).oper[1]^.typ = top_reg)
  7643. {$ifdef x86_64}
  7644. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7645. {$endif x86_64}
  7646. then
  7647. begin
  7648. { cmp register,$8000 neg register
  7649. je target --> jo target
  7650. .... only if register is deallocated before jump.}
  7651. case Taicpu(p).opsize of
  7652. S_B: v:=$80;
  7653. S_W: v:=$8000;
  7654. S_L: v:=qword($80000000);
  7655. else
  7656. internalerror(2013112905);
  7657. end;
  7658. if (taicpu(p).oper[0]^.val=v) and
  7659. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7660. begin
  7661. TransferUsedRegs(TmpUsedRegs);
  7662. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7663. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7664. begin
  7665. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7666. Taicpu(p).opcode:=A_NEG;
  7667. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7668. Taicpu(p).clearop(1);
  7669. Taicpu(p).ops:=1;
  7670. if Taicpu(hp1).condition=C_E then
  7671. Taicpu(hp1).condition:=C_O
  7672. else
  7673. Taicpu(hp1).condition:=C_NO;
  7674. Result:=true;
  7675. exit;
  7676. end;
  7677. end;
  7678. end;
  7679. end;
  7680. end;
  7681. end;
  7682. if TrySwapMovCmp(p, hp1) then
  7683. begin
  7684. Result := True;
  7685. Exit;
  7686. end;
  7687. end;
  7688. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7689. var
  7690. hp1: tai;
  7691. begin
  7692. {
  7693. remove the second (v)pxor from
  7694. pxor reg,reg
  7695. ...
  7696. pxor reg,reg
  7697. }
  7698. Result:=false;
  7699. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7700. MatchOpType(taicpu(p),top_reg,top_reg) and
  7701. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7702. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7703. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7704. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7705. begin
  7706. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7707. RemoveInstruction(hp1);
  7708. Result:=true;
  7709. Exit;
  7710. end
  7711. {
  7712. replace
  7713. pxor reg1,reg1
  7714. movapd/s reg1,reg2
  7715. dealloc reg1
  7716. by
  7717. pxor reg2,reg2
  7718. }
  7719. else if GetNextInstruction(p,hp1) and
  7720. { we mix single and double opperations here because we assume that the compiler
  7721. generates vmovapd only after double operations and vmovaps only after single operations }
  7722. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7723. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7724. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7725. (taicpu(p).oper[0]^.typ=top_reg) then
  7726. begin
  7727. TransferUsedRegs(TmpUsedRegs);
  7728. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7729. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7730. begin
  7731. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7732. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7733. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7734. RemoveInstruction(hp1);
  7735. result:=true;
  7736. end;
  7737. end;
  7738. end;
  7739. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7740. var
  7741. hp1: tai;
  7742. begin
  7743. {
  7744. remove the second (v)pxor from
  7745. (v)pxor reg,reg
  7746. ...
  7747. (v)pxor reg,reg
  7748. }
  7749. Result:=false;
  7750. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7751. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7752. begin
  7753. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7754. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7755. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7756. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7757. begin
  7758. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7759. RemoveInstruction(hp1);
  7760. Result:=true;
  7761. Exit;
  7762. end;
  7763. {$ifdef x86_64}
  7764. {
  7765. replace
  7766. vpxor reg1,reg1,reg1
  7767. vmov reg,mem
  7768. by
  7769. movq $0,mem
  7770. }
  7771. if GetNextInstruction(p,hp1) and
  7772. MatchInstruction(hp1,A_VMOVSD,[]) and
  7773. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7774. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7775. begin
  7776. TransferUsedRegs(TmpUsedRegs);
  7777. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7778. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7779. begin
  7780. taicpu(hp1).loadconst(0,0);
  7781. taicpu(hp1).opcode:=A_MOV;
  7782. taicpu(hp1).opsize:=S_Q;
  7783. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7784. RemoveCurrentP(p);
  7785. result:=true;
  7786. Exit;
  7787. end;
  7788. end;
  7789. {$endif x86_64}
  7790. end
  7791. {
  7792. replace
  7793. vpxor reg1,reg1,reg2
  7794. by
  7795. vpxor reg2,reg2,reg2
  7796. to avoid unncessary data dependencies
  7797. }
  7798. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7799. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7800. begin
  7801. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7802. { avoid unncessary data dependency }
  7803. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7804. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7805. result:=true;
  7806. exit;
  7807. end;
  7808. Result:=OptPass1VOP(p);
  7809. end;
  7810. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7811. var
  7812. hp1 : tai;
  7813. begin
  7814. result:=false;
  7815. { replace
  7816. IMul const,%mreg1,%mreg2
  7817. Mov %reg2,%mreg3
  7818. dealloc %mreg3
  7819. by
  7820. Imul const,%mreg1,%mreg23
  7821. }
  7822. if (taicpu(p).ops=3) and
  7823. GetNextInstruction(p,hp1) and
  7824. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7825. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7826. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7827. begin
  7828. TransferUsedRegs(TmpUsedRegs);
  7829. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7830. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7831. begin
  7832. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7833. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7834. RemoveInstruction(hp1);
  7835. result:=true;
  7836. end;
  7837. end;
  7838. end;
  7839. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7840. var
  7841. hp1 : tai;
  7842. begin
  7843. result:=false;
  7844. { replace
  7845. IMul %reg0,%reg1,%reg2
  7846. Mov %reg2,%reg3
  7847. dealloc %reg2
  7848. by
  7849. Imul %reg0,%reg1,%reg3
  7850. }
  7851. if GetNextInstruction(p,hp1) and
  7852. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7853. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7854. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7855. begin
  7856. TransferUsedRegs(TmpUsedRegs);
  7857. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7858. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7859. begin
  7860. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7861. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7862. RemoveInstruction(hp1);
  7863. result:=true;
  7864. end;
  7865. end;
  7866. end;
  7867. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7868. var
  7869. hp1: tai;
  7870. begin
  7871. Result:=false;
  7872. { get rid of
  7873. (v)cvtss2sd reg0,<reg1,>reg2
  7874. (v)cvtss2sd reg2,<reg2,>reg0
  7875. }
  7876. if GetNextInstruction(p,hp1) and
  7877. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7878. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7879. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7880. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7881. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7882. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7883. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7884. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7885. )
  7886. ) then
  7887. begin
  7888. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7889. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7890. begin
  7891. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7892. RemoveCurrentP(p);
  7893. RemoveInstruction(hp1);
  7894. end
  7895. else
  7896. begin
  7897. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7898. if taicpu(hp1).opcode=A_CVTSD2SS then
  7899. begin
  7900. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7901. taicpu(p).opcode:=A_MOVAPS;
  7902. end
  7903. else
  7904. begin
  7905. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7906. taicpu(p).opcode:=A_VMOVAPS;
  7907. end;
  7908. taicpu(p).ops:=2;
  7909. RemoveInstruction(hp1);
  7910. end;
  7911. Result:=true;
  7912. Exit;
  7913. end;
  7914. end;
  7915. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7916. var
  7917. hp1, hp2, hp3, hp4, hp5: tai;
  7918. ThisReg: TRegister;
  7919. begin
  7920. Result := False;
  7921. if not GetNextInstruction(p,hp1) then
  7922. Exit;
  7923. {
  7924. convert
  7925. j<c> .L1
  7926. mov 1,reg
  7927. jmp .L2
  7928. .L1
  7929. mov 0,reg
  7930. .L2
  7931. into
  7932. mov 0,reg
  7933. set<not(c)> reg
  7934. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7935. would destroy the flag contents
  7936. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7937. executed at the same time as a previous comparison.
  7938. set<not(c)> reg
  7939. movzx reg, reg
  7940. }
  7941. if MatchInstruction(hp1,A_MOV,[]) and
  7942. (taicpu(hp1).oper[0]^.typ = top_const) and
  7943. (
  7944. (
  7945. (taicpu(hp1).oper[1]^.typ = top_reg)
  7946. {$ifdef i386}
  7947. { Under i386, ESI, EDI, EBP and ESP
  7948. don't have an 8-bit representation }
  7949. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7950. {$endif i386}
  7951. ) or (
  7952. {$ifdef i386}
  7953. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7954. {$endif i386}
  7955. (taicpu(hp1).opsize = S_B)
  7956. )
  7957. ) and
  7958. GetNextInstruction(hp1,hp2) and
  7959. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7960. GetNextInstruction(hp2,hp3) and
  7961. (hp3.typ=ait_label) and
  7962. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7963. GetNextInstruction(hp3,hp4) and
  7964. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7965. (taicpu(hp4).oper[0]^.typ = top_const) and
  7966. (
  7967. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7968. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7969. ) and
  7970. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7971. GetNextInstruction(hp4,hp5) and
  7972. (hp5.typ=ait_label) and
  7973. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7974. begin
  7975. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7976. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7977. tai_label(hp3).labsym.DecRefs;
  7978. { If this isn't the only reference to the middle label, we can
  7979. still make a saving - only that the first jump and everything
  7980. that follows will remain. }
  7981. if (tai_label(hp3).labsym.getrefs = 0) then
  7982. begin
  7983. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7984. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7985. else
  7986. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7987. { remove jump, first label and second MOV (also catching any aligns) }
  7988. repeat
  7989. if not GetNextInstruction(hp2, hp3) then
  7990. InternalError(2021040810);
  7991. RemoveInstruction(hp2);
  7992. hp2 := hp3;
  7993. until hp2 = hp5;
  7994. { Don't decrement reference count before the removal loop
  7995. above, otherwise GetNextInstruction won't stop on the
  7996. the label }
  7997. tai_label(hp5).labsym.DecRefs;
  7998. end
  7999. else
  8000. begin
  8001. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8002. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8003. else
  8004. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8005. end;
  8006. taicpu(p).opcode:=A_SETcc;
  8007. taicpu(p).opsize:=S_B;
  8008. taicpu(p).is_jmp:=False;
  8009. if taicpu(hp1).opsize=S_B then
  8010. begin
  8011. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8012. if taicpu(hp1).oper[1]^.typ = top_reg then
  8013. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8014. RemoveInstruction(hp1);
  8015. end
  8016. else
  8017. begin
  8018. { Will be a register because the size can't be S_B otherwise }
  8019. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8020. taicpu(p).loadreg(0, ThisReg);
  8021. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8022. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8023. begin
  8024. case taicpu(hp1).opsize of
  8025. S_W:
  8026. taicpu(hp1).opsize := S_BW;
  8027. S_L:
  8028. taicpu(hp1).opsize := S_BL;
  8029. {$ifdef x86_64}
  8030. S_Q:
  8031. begin
  8032. taicpu(hp1).opsize := S_BL;
  8033. { Change the destination register to 32-bit }
  8034. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8035. end;
  8036. {$endif x86_64}
  8037. else
  8038. InternalError(2021040820);
  8039. end;
  8040. taicpu(hp1).opcode := A_MOVZX;
  8041. taicpu(hp1).loadreg(0, ThisReg);
  8042. end
  8043. else
  8044. begin
  8045. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8046. { hp1 is already a MOV instruction with the correct register }
  8047. taicpu(hp1).loadconst(0, 0);
  8048. { Inserting it right before p will guarantee that the flags are also tracked }
  8049. asml.Remove(hp1);
  8050. asml.InsertBefore(hp1, p);
  8051. end;
  8052. end;
  8053. Result:=true;
  8054. exit;
  8055. end
  8056. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8057. Result := TryJccStcClcOpt(p, hp1)
  8058. else if (hp1.typ = ait_label) then
  8059. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8060. end;
  8061. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8062. var
  8063. hp1, hp2, hp3: tai;
  8064. SourceRef, TargetRef: TReference;
  8065. CurrentReg: TRegister;
  8066. begin
  8067. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8068. if not UseAVX then
  8069. InternalError(2021100501);
  8070. Result := False;
  8071. { Look for the following to simplify:
  8072. vmovdqa/u x(mem1), %xmmreg
  8073. vmovdqa/u %xmmreg, y(mem2)
  8074. vmovdqa/u x+16(mem1), %xmmreg
  8075. vmovdqa/u %xmmreg, y+16(mem2)
  8076. Change to:
  8077. vmovdqa/u x(mem1), %ymmreg
  8078. vmovdqa/u %ymmreg, y(mem2)
  8079. vpxor %ymmreg, %ymmreg, %ymmreg
  8080. ( The VPXOR instruction is to zero the upper half, thus removing the
  8081. need to call the potentially expensive VZEROUPPER instruction. Other
  8082. peephole optimisations can remove VPXOR if it's unnecessary )
  8083. }
  8084. TransferUsedRegs(TmpUsedRegs);
  8085. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8086. { NOTE: In the optimisations below, if the references dictate that an
  8087. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8088. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8089. if (taicpu(p).opsize = S_XMM) and
  8090. MatchOpType(taicpu(p), top_ref, top_reg) and
  8091. GetNextInstruction(p, hp1) and
  8092. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8093. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8094. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8095. begin
  8096. SourceRef := taicpu(p).oper[0]^.ref^;
  8097. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8098. if GetNextInstruction(hp1, hp2) and
  8099. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8100. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8101. begin
  8102. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8103. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8104. Inc(SourceRef.offset, 16);
  8105. { Reuse the register in the first block move }
  8106. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8107. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8108. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8109. begin
  8110. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8111. Inc(TargetRef.offset, 16);
  8112. if GetNextInstruction(hp2, hp3) and
  8113. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8114. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8115. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8116. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8117. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8118. begin
  8119. { Update the register tracking to the new size }
  8120. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8121. { Remember that the offsets are 16 ahead }
  8122. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8123. if not (
  8124. ((SourceRef.offset mod 32) = 16) and
  8125. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8126. ) then
  8127. taicpu(p).opcode := A_VMOVDQU;
  8128. taicpu(p).opsize := S_YMM;
  8129. taicpu(p).oper[1]^.reg := CurrentReg;
  8130. if not (
  8131. ((TargetRef.offset mod 32) = 16) and
  8132. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8133. ) then
  8134. taicpu(hp1).opcode := A_VMOVDQU;
  8135. taicpu(hp1).opsize := S_YMM;
  8136. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8137. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8138. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8139. if (pi_uses_ymm in current_procinfo.flags) then
  8140. RemoveInstruction(hp2)
  8141. else
  8142. begin
  8143. taicpu(hp2).opcode := A_VPXOR;
  8144. taicpu(hp2).opsize := S_YMM;
  8145. taicpu(hp2).loadreg(0, CurrentReg);
  8146. taicpu(hp2).loadreg(1, CurrentReg);
  8147. taicpu(hp2).loadreg(2, CurrentReg);
  8148. taicpu(hp2).ops := 3;
  8149. end;
  8150. RemoveInstruction(hp3);
  8151. Result := True;
  8152. Exit;
  8153. end;
  8154. end
  8155. else
  8156. begin
  8157. { See if the next references are 16 less rather than 16 greater }
  8158. Dec(SourceRef.offset, 32); { -16 the other way }
  8159. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8160. begin
  8161. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8162. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8163. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8164. GetNextInstruction(hp2, hp3) and
  8165. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8166. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8167. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8168. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8169. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8170. begin
  8171. { Update the register tracking to the new size }
  8172. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8173. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8174. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8175. if not(
  8176. ((SourceRef.offset mod 32) = 0) and
  8177. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8178. ) then
  8179. taicpu(hp2).opcode := A_VMOVDQU;
  8180. taicpu(hp2).opsize := S_YMM;
  8181. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8182. if not (
  8183. ((TargetRef.offset mod 32) = 0) and
  8184. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8185. ) then
  8186. taicpu(hp3).opcode := A_VMOVDQU;
  8187. taicpu(hp3).opsize := S_YMM;
  8188. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8189. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8190. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8191. if (pi_uses_ymm in current_procinfo.flags) then
  8192. RemoveInstruction(hp1)
  8193. else
  8194. begin
  8195. taicpu(hp1).opcode := A_VPXOR;
  8196. taicpu(hp1).opsize := S_YMM;
  8197. taicpu(hp1).loadreg(0, CurrentReg);
  8198. taicpu(hp1).loadreg(1, CurrentReg);
  8199. taicpu(hp1).loadreg(2, CurrentReg);
  8200. taicpu(hp1).ops := 3;
  8201. Asml.Remove(hp1);
  8202. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8203. end;
  8204. RemoveCurrentP(p, hp2);
  8205. Result := True;
  8206. Exit;
  8207. end;
  8208. end;
  8209. end;
  8210. end;
  8211. end;
  8212. end;
  8213. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8214. var
  8215. hp2, hp3, first_assignment: tai;
  8216. IncCount, OperIdx: Integer;
  8217. OrigLabel: TAsmLabel;
  8218. begin
  8219. Count := 0;
  8220. Result := False;
  8221. first_assignment := nil;
  8222. if (LoopCount >= 20) then
  8223. begin
  8224. { Guard against infinite loops }
  8225. Exit;
  8226. end;
  8227. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8228. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8229. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8230. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8231. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8232. Exit;
  8233. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8234. {
  8235. change
  8236. jmp .L1
  8237. ...
  8238. .L1:
  8239. mov ##, ## ( multiple movs possible )
  8240. jmp/ret
  8241. into
  8242. mov ##, ##
  8243. jmp/ret
  8244. }
  8245. if not Assigned(hp1) then
  8246. begin
  8247. hp1 := GetLabelWithSym(OrigLabel);
  8248. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8249. Exit;
  8250. end;
  8251. hp2 := hp1;
  8252. while Assigned(hp2) do
  8253. begin
  8254. if Assigned(hp2) and (hp2.typ = ait_label) then
  8255. SkipLabels(hp2,hp2);
  8256. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8257. Break;
  8258. case taicpu(hp2).opcode of
  8259. A_MOVSD:
  8260. begin
  8261. if taicpu(hp2).ops = 0 then
  8262. { Wrong MOVSD }
  8263. Break;
  8264. Inc(Count);
  8265. if Count >= 5 then
  8266. { Too many to be worthwhile }
  8267. Break;
  8268. GetNextInstruction(hp2, hp2);
  8269. Continue;
  8270. end;
  8271. A_MOV,
  8272. A_MOVD,
  8273. A_MOVQ,
  8274. A_MOVSX,
  8275. {$ifdef x86_64}
  8276. A_MOVSXD,
  8277. {$endif x86_64}
  8278. A_MOVZX,
  8279. A_MOVAPS,
  8280. A_MOVUPS,
  8281. A_MOVSS,
  8282. A_MOVAPD,
  8283. A_MOVUPD,
  8284. A_MOVDQA,
  8285. A_MOVDQU,
  8286. A_VMOVSS,
  8287. A_VMOVAPS,
  8288. A_VMOVUPS,
  8289. A_VMOVSD,
  8290. A_VMOVAPD,
  8291. A_VMOVUPD,
  8292. A_VMOVDQA,
  8293. A_VMOVDQU:
  8294. begin
  8295. Inc(Count);
  8296. if Count >= 5 then
  8297. { Too many to be worthwhile }
  8298. Break;
  8299. GetNextInstruction(hp2, hp2);
  8300. Continue;
  8301. end;
  8302. A_JMP:
  8303. begin
  8304. { Guard against infinite loops }
  8305. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8306. Exit;
  8307. { Analyse this jump first in case it also duplicates assignments }
  8308. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8309. begin
  8310. { Something did change! }
  8311. Result := True;
  8312. Inc(Count, IncCount);
  8313. if Count >= 5 then
  8314. begin
  8315. { Too many to be worthwhile }
  8316. Exit;
  8317. end;
  8318. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8319. Break;
  8320. end;
  8321. Result := True;
  8322. Break;
  8323. end;
  8324. A_RET:
  8325. begin
  8326. Result := True;
  8327. Break;
  8328. end;
  8329. else
  8330. Break;
  8331. end;
  8332. end;
  8333. if Result then
  8334. begin
  8335. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8336. if Count = 0 then
  8337. begin
  8338. Result := False;
  8339. Exit;
  8340. end;
  8341. TransferUsedRegs(TmpUsedRegs);
  8342. hp3 := p;
  8343. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8344. while True do
  8345. begin
  8346. if Assigned(hp1) and (hp1.typ = ait_label) then
  8347. SkipLabels(hp1,hp1);
  8348. case hp1.typ of
  8349. ait_regalloc:
  8350. if tai_regalloc(hp1).ratype = ra_dealloc then
  8351. begin
  8352. { Duplicate the register deallocation... }
  8353. hp3:=tai(hp1.getcopy);
  8354. if first_assignment = nil then
  8355. first_assignment := hp3;
  8356. asml.InsertBefore(hp3, p);
  8357. { ... but also reallocate it after the jump }
  8358. hp3:=tai(hp1.getcopy);
  8359. tai_regalloc(hp3).ratype := ra_alloc;
  8360. asml.InsertAfter(hp3, p);
  8361. end;
  8362. ait_instruction:
  8363. case taicpu(hp1).opcode of
  8364. A_JMP:
  8365. begin
  8366. { Change the original jump to the new destination }
  8367. OrigLabel.decrefs;
  8368. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8369. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8370. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8371. if not Assigned(first_assignment) then
  8372. InternalError(2021040810)
  8373. else
  8374. p := first_assignment;
  8375. Exit;
  8376. end;
  8377. A_RET:
  8378. begin
  8379. { Now change the jump into a RET instruction }
  8380. ConvertJumpToRET(p, hp1);
  8381. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8382. if not Assigned(first_assignment) then
  8383. InternalError(2021040811)
  8384. else
  8385. p := first_assignment;
  8386. Exit;
  8387. end;
  8388. else
  8389. begin
  8390. { Duplicate the MOV instruction }
  8391. hp3:=tai(hp1.getcopy);
  8392. if first_assignment = nil then
  8393. first_assignment := hp3;
  8394. asml.InsertBefore(hp3, p);
  8395. { Make sure the compiler knows about any final registers written here }
  8396. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8397. with taicpu(hp3).oper[OperIdx]^ do
  8398. begin
  8399. case typ of
  8400. top_ref:
  8401. begin
  8402. if (ref^.base <> NR_NO) and
  8403. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8404. (
  8405. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8406. (
  8407. { Allow the frame pointer if it's not being used by the procedure as such }
  8408. Assigned(current_procinfo) and
  8409. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8410. )
  8411. )
  8412. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8413. then
  8414. begin
  8415. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8416. if not Assigned(first_assignment) then
  8417. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8418. end;
  8419. if (ref^.index <> NR_NO) and
  8420. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8421. (
  8422. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8423. (
  8424. { Allow the frame pointer if it's not being used by the procedure as such }
  8425. Assigned(current_procinfo) and
  8426. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8427. )
  8428. )
  8429. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8430. (ref^.index <> ref^.base) then
  8431. begin
  8432. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8433. if not Assigned(first_assignment) then
  8434. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8435. end;
  8436. end;
  8437. top_reg:
  8438. begin
  8439. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8440. if not Assigned(first_assignment) then
  8441. IncludeRegInUsedRegs(reg, UsedRegs);
  8442. end;
  8443. else
  8444. ;
  8445. end;
  8446. end;
  8447. end;
  8448. end;
  8449. else
  8450. InternalError(2021040720);
  8451. end;
  8452. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8453. { Should have dropped out earlier }
  8454. InternalError(2021040710);
  8455. end;
  8456. end;
  8457. end;
  8458. const
  8459. WriteOp: array[0..3] of set of TInsChange = (
  8460. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8461. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8462. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8463. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8464. RegWriteFlags: array[0..7] of set of TInsChange = (
  8465. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8466. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8467. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8468. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8469. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8470. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8471. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8472. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8473. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8474. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8475. var
  8476. hp2: tai;
  8477. X: Integer;
  8478. begin
  8479. { If we have something like:
  8480. op ###,###
  8481. mov ###,###
  8482. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8483. interfere in regards to what they write to.
  8484. NOTE: p must be a 2-operand instruction
  8485. }
  8486. Result := False;
  8487. if (hp1.typ <> ait_instruction) or
  8488. taicpu(hp1).is_jmp or
  8489. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8490. Exit;
  8491. { NOP is a pipeline fence, likely marking the beginning of the function
  8492. epilogue, so drop out. Similarly, drop out if POP or RET are
  8493. encountered }
  8494. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8495. Exit;
  8496. if (taicpu(hp1).opcode = A_MOVSD) and
  8497. (taicpu(hp1).ops = 0) then
  8498. { Wrong MOVSD }
  8499. Exit;
  8500. { Check for writes to specific registers first }
  8501. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8502. for X := 0 to 7 do
  8503. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8504. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8505. Exit;
  8506. for X := 0 to taicpu(hp1).ops - 1 do
  8507. begin
  8508. { Check to see if this operand writes to something }
  8509. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8510. { And matches something in the CMP/TEST instruction }
  8511. (
  8512. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8513. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8514. (
  8515. { If it's a register, make sure the register written to doesn't
  8516. appear in the cmp instruction as part of a reference }
  8517. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8518. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8519. )
  8520. ) then
  8521. Exit;
  8522. end;
  8523. { Check p to make sure it doesn't write to something that affects hp1 }
  8524. { Check for writes to specific registers first }
  8525. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8526. for X := 0 to 7 do
  8527. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8528. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8529. Exit;
  8530. for X := 0 to taicpu(p).ops - 1 do
  8531. begin
  8532. { Check to see if this operand writes to something }
  8533. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8534. { And matches something in hp1 }
  8535. (taicpu(p).oper[X]^.typ = top_reg) and
  8536. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8537. Exit;
  8538. end;
  8539. { The instruction can be safely moved }
  8540. asml.Remove(hp1);
  8541. { Try to insert after the last instructions where the FLAGS register is not
  8542. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8543. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8544. asml.InsertBefore(hp1, hp2)
  8545. { Failing that, try to insert after the last instructions where the
  8546. FLAGS register is not yet in use }
  8547. else if GetLastInstruction(p, hp2) and
  8548. (
  8549. (hp2.typ <> ait_instruction) or
  8550. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8551. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8552. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8553. ) then
  8554. asml.InsertAfter(hp1, hp2)
  8555. else
  8556. { Note, if p.Previous is nil (even if it should logically never be the
  8557. case), FindRegAllocBackward immediately exits with False and so we
  8558. safely land here (we can't just pass p because FindRegAllocBackward
  8559. immediately exits on an instruction). [Kit] }
  8560. asml.InsertBefore(hp1, p);
  8561. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8562. { We can't trust UsedRegs because we're looking backwards, although we
  8563. know the registers are allocated after p at the very least, so manually
  8564. create tai_regalloc objects if needed }
  8565. for X := 0 to taicpu(hp1).ops - 1 do
  8566. case taicpu(hp1).oper[X]^.typ of
  8567. top_reg:
  8568. begin
  8569. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8570. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8571. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8572. end;
  8573. top_ref:
  8574. begin
  8575. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8576. begin
  8577. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8578. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8579. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8580. end;
  8581. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8582. begin
  8583. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8584. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8585. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8586. end;
  8587. end;
  8588. else
  8589. ;
  8590. end;
  8591. Result := True;
  8592. end;
  8593. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8594. var
  8595. hp2: tai;
  8596. X: Integer;
  8597. begin
  8598. { If we have something like:
  8599. cmp ###,%reg1
  8600. mov 0,%reg2
  8601. And no modified registers are shared, move the instruction to before
  8602. the comparison as this means it can be optimised without worrying
  8603. about the FLAGS register. (CMP/MOV is generated by
  8604. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8605. As long as the second instruction doesn't use the flags or one of the
  8606. registers used by CMP or TEST (also check any references that use the
  8607. registers), then it can be moved prior to the comparison.
  8608. }
  8609. Result := False;
  8610. if not TrySwapMovOp(p, hp1) then
  8611. Exit;
  8612. if taicpu(hp1).opcode = A_LEA then
  8613. { The flags will be overwritten by the CMP/TEST instruction }
  8614. ConvertLEA(taicpu(hp1));
  8615. Result := True;
  8616. { Can we move it one further back? }
  8617. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8618. { Check to see if CMP/TEST is a comparison against zero }
  8619. (
  8620. (
  8621. (taicpu(p).opcode = A_CMP) and
  8622. MatchOperand(taicpu(p).oper[0]^, 0)
  8623. ) or
  8624. (
  8625. (taicpu(p).opcode = A_TEST) and
  8626. (
  8627. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8628. MatchOperand(taicpu(p).oper[0]^, -1)
  8629. )
  8630. )
  8631. ) and
  8632. { These instructions set the zero flag if the result is zero }
  8633. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8634. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8635. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8636. TrySwapMovOp(hp2, hp1);
  8637. end;
  8638. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8639. var
  8640. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8641. JumpLabel: TAsmLabel;
  8642. TmpBool: Boolean;
  8643. begin
  8644. Result := False;
  8645. { Look for:
  8646. stc/clc
  8647. j(c) .L1
  8648. ...
  8649. .L1:
  8650. set(n)cb %reg
  8651. (flags deallocated)
  8652. j(c) .L2
  8653. Change to:
  8654. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8655. j(c) .L2
  8656. }
  8657. p_last := p;
  8658. while GetNextInstruction(p_last, hp1) and
  8659. (hp1.typ = ait_instruction) and
  8660. IsJumpToLabel(taicpu(hp1)) do
  8661. begin
  8662. if DoJumpOptimizations(hp1, TmpBool) then
  8663. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8664. Continue;
  8665. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8666. if not Assigned(JumpLabel) then
  8667. InternalError(2024012801);
  8668. { Optimise the J(c); stc/clc optimisation first since this will
  8669. get missed if the main optimisation takes place }
  8670. if (taicpu(hp1).opcode = A_JCC) then
  8671. begin
  8672. if GetNextInstruction(hp1, hp2) and
  8673. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8674. TryJccStcClcOpt(hp1, hp2) then
  8675. begin
  8676. Result := True;
  8677. Exit;
  8678. end;
  8679. hp2 := nil; { Suppress compiler warning }
  8680. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8681. { Make sure the flags aren't used again }
  8682. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8683. begin
  8684. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8685. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8686. begin
  8687. if (taicpu(p).opcode = A_STC) then
  8688. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8689. else
  8690. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8691. MakeUnconditional(taicpu(hp1));
  8692. { Move the jump to after the flag deallocations }
  8693. Asml.Remove(hp1);
  8694. Asml.InsertAfter(hp1, hp2);
  8695. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8696. Result := True;
  8697. Exit;
  8698. end
  8699. else
  8700. begin
  8701. if (taicpu(p).opcode = A_STC) then
  8702. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8703. else
  8704. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8705. { In this case, the jump is deterministic in that it will never be taken }
  8706. JumpLabel.DecRefs;
  8707. RemoveInstruction(hp1);
  8708. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8709. Result := True;
  8710. Exit;
  8711. end;
  8712. end;
  8713. end;
  8714. hp2 := nil; { Suppress compiler warning }
  8715. if
  8716. { Make sure the carry flag doesn't appear in the jump conditions }
  8717. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8718. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8719. GetNextInstruction(hp2, p_dist) and
  8720. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8721. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8722. begin
  8723. case taicpu(p_dist).opcode of
  8724. A_Jcc:
  8725. begin
  8726. if DoJumpOptimizations(p_dist, TmpBool) then
  8727. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8728. Continue;
  8729. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8730. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8731. begin
  8732. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8733. JumpLabel.decrefs;
  8734. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8735. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8736. Result := True;
  8737. Exit;
  8738. end
  8739. else if GetNextInstruction(p_dist, hp1_dist) and
  8740. (hp1_dist.typ = ait_label) then
  8741. begin
  8742. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8743. JumpLabel.decrefs;
  8744. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8745. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8746. Result := True;
  8747. Exit;
  8748. end;
  8749. end;
  8750. A_SETcc:
  8751. if { Make sure the flags aren't used again }
  8752. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8753. GetNextInstruction(hp2, hp1_dist) and
  8754. (hp1_dist.typ = ait_instruction) and
  8755. IsJumpToLabel(taicpu(hp1_dist)) and
  8756. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8757. { This works if hp1_dist or both are regular JMP instructions }
  8758. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8759. (
  8760. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8761. { Make sure the register isn't still in use, otherwise it
  8762. may get corrupted (fixes #40659) }
  8763. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8764. ) then
  8765. begin
  8766. taicpu(p).allocate_oper(2);
  8767. taicpu(p).ops := 2;
  8768. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8769. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8770. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8771. taicpu(p).opcode := A_MOV;
  8772. taicpu(p).opsize := S_B;
  8773. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8774. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8775. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8776. JumpLabel.decrefs;
  8777. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8778. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8779. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8780. (tai_regalloc(hp2).ratype = ra_alloc) then
  8781. begin
  8782. Asml.Remove(hp2);
  8783. Asml.InsertAfter(hp2, p);
  8784. end;
  8785. Result := True;
  8786. Exit;
  8787. end;
  8788. else
  8789. ;
  8790. end;
  8791. end;
  8792. p_last := hp1;
  8793. end;
  8794. end;
  8795. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8796. var
  8797. hp2, hp3: tai;
  8798. TempBool: Boolean;
  8799. begin
  8800. Result := False;
  8801. {
  8802. j(c) .L1
  8803. stc/clc
  8804. .L1:
  8805. jc/jnc .L2
  8806. (Flags deallocated)
  8807. Change to:
  8808. j)c) .L1
  8809. jmp .L2
  8810. .L1:
  8811. jc/jnc .L2
  8812. Then call DoJumpOptimizations to convert to:
  8813. j(nc) .L2
  8814. .L1: (may become a dead label)
  8815. jc/jnc .L2
  8816. }
  8817. if GetNextInstruction(hp1, hp2) and
  8818. (hp2.typ = ait_label) and
  8819. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8820. GetNextInstruction(hp2, hp3) and
  8821. MatchInstruction(hp3, A_Jcc, []) and
  8822. (
  8823. (
  8824. (taicpu(hp3).condition = C_C) and
  8825. (taicpu(hp1).opcode = A_STC)
  8826. ) or (
  8827. (taicpu(hp3).condition = C_NC) and
  8828. (taicpu(hp1).opcode = A_CLC)
  8829. )
  8830. ) and
  8831. { Make sure the flags aren't used again }
  8832. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8833. begin
  8834. taicpu(hp1).allocate_oper(1);
  8835. taicpu(hp1).ops := 1;
  8836. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8837. taicpu(hp1).opcode := A_JMP;
  8838. taicpu(hp1).is_jmp := True;
  8839. TempBool := True; { Prevent compiler warnings }
  8840. if DoJumpOptimizations(p, TempBool) then
  8841. Result := True
  8842. else
  8843. Include(OptsToCheck, aoc_ForceNewIteration);
  8844. end;
  8845. end;
  8846. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8847. begin
  8848. { This generally only executes under -O3 and above }
  8849. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8850. end;
  8851. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8852. var
  8853. hp1, hp2: tai;
  8854. FoundComparison: Boolean;
  8855. begin
  8856. { Run the pass 1 optimisations as well, since they may have some effect
  8857. after the CMOV blocks are created in OptPass2Jcc }
  8858. Result := False;
  8859. { Result := OptPass1CMOVcc(p);
  8860. if Result then
  8861. Exit;}
  8862. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8863. and make a slightly inefficent result on branching-type blocks, notably
  8864. when setting a function result then jumping to the function epilogue.
  8865. In this case, change:
  8866. cmov(c) %reg1,%reg2
  8867. j(c) @lbl
  8868. (%reg2 deallocated)
  8869. To:
  8870. mov %reg11,%reg2
  8871. j(c) @lbl
  8872. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8873. jump because if it's not present, we may end up with a jump that's
  8874. completely unrelated.
  8875. }
  8876. hp1 := p;
  8877. while GetNextInstruction(hp1, hp1) and
  8878. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8879. if (hp1.typ = ait_instruction) and
  8880. (taicpu(hp1).opcode = A_Jcc) and
  8881. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8882. begin
  8883. TransferUsedRegs(TmpUsedRegs);
  8884. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8885. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8886. (
  8887. { See if we can find a more distant instruction that overwrites
  8888. the destination register }
  8889. (cs_opt_level3 in current_settings.optimizerswitches) and
  8890. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8891. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  8892. ) then
  8893. begin
  8894. if (taicpu(p).oper[0]^.typ = top_reg) then
  8895. begin
  8896. { Search backwards to see if the source register is set to a
  8897. constant }
  8898. FoundComparison := False;
  8899. hp1 := p;
  8900. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  8901. begin
  8902. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  8903. begin
  8904. FoundComparison := True;
  8905. Continue;
  8906. end;
  8907. { Once we find the CMP, TEST or similar instruction, we
  8908. have to stop if we find anything other than a MOV }
  8909. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  8910. Break;
  8911. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  8912. { Destination register was modified }
  8913. Break;
  8914. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  8915. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  8916. begin
  8917. { Found a constant! }
  8918. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  8919. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8920. { The source register is no longer in use }
  8921. RemoveInstruction(hp1);
  8922. Break;
  8923. end;
  8924. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  8925. { Some other instruction has modified the source register }
  8926. Break;
  8927. end;
  8928. end;
  8929. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  8930. taicpu(p).opcode := A_MOV;
  8931. taicpu(p).condition := C_None;
  8932. { Rely on the post peephole stage to put the MOV before the
  8933. CMP/TEST instruction that appears prior }
  8934. Result := True;
  8935. Exit;
  8936. end;
  8937. end;
  8938. end;
  8939. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8940. function IsXCHGAcceptable: Boolean; inline;
  8941. begin
  8942. { Always accept if optimising for size }
  8943. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8944. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8945. than 3, so it becomes a saving compared to three MOVs with two of
  8946. them able to execute simultaneously. [Kit] }
  8947. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8948. end;
  8949. var
  8950. NewRef: TReference;
  8951. hp1, hp2, hp3, hp4: Tai;
  8952. {$ifndef x86_64}
  8953. OperIdx: Integer;
  8954. {$endif x86_64}
  8955. NewInstr : Taicpu;
  8956. NewAligh : Tai_align;
  8957. DestLabel: TAsmLabel;
  8958. TempTracking: TAllUsedRegs;
  8959. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8960. var
  8961. NextInstr: tai;
  8962. begin
  8963. Result := False;
  8964. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8965. if not GetNextInstruction(InputInstr, NextInstr) or
  8966. (
  8967. { The FLAGS register isn't always tracked properly, so do not
  8968. perform this optimisation if a conditional statement follows }
  8969. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8970. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8971. ) then
  8972. begin
  8973. reference_reset(NewRef, 1, []);
  8974. NewRef.base := taicpu(p).oper[0]^.reg;
  8975. NewRef.scalefactor := 1;
  8976. if taicpu(InputInstr).opcode = A_ADD then
  8977. begin
  8978. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8979. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8980. end
  8981. else
  8982. begin
  8983. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8984. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8985. end;
  8986. taicpu(p).opcode := A_LEA;
  8987. taicpu(p).loadref(0, NewRef);
  8988. { For the sake of debugging, have the line info match the
  8989. arithmetic instruction rather than the MOV instruction }
  8990. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  8991. RemoveInstruction(InputInstr);
  8992. Result := True;
  8993. end;
  8994. end;
  8995. begin
  8996. Result:=false;
  8997. { This optimisation adds an instruction, so only do it for speed }
  8998. if not (cs_opt_size in current_settings.optimizerswitches) and
  8999. MatchOpType(taicpu(p), top_const, top_reg) and
  9000. (taicpu(p).oper[0]^.val = 0) then
  9001. begin
  9002. { To avoid compiler warning }
  9003. DestLabel := nil;
  9004. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9005. InternalError(2021040750);
  9006. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9007. Exit;
  9008. case hp1.typ of
  9009. ait_label:
  9010. begin
  9011. { Change:
  9012. mov $0,%reg mov $0,%reg
  9013. @Lbl1: @Lbl1:
  9014. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9015. je @Lbl2 jne @Lbl2
  9016. To: To:
  9017. mov $0,%reg mov $0,%reg
  9018. jmp @Lbl2 jmp @Lbl3
  9019. (align) (align)
  9020. @Lbl1: @Lbl1:
  9021. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9022. je @Lbl2 je @Lbl2
  9023. @Lbl3: <-- Only if label exists
  9024. (Not if it's optimised for size)
  9025. }
  9026. if not GetNextInstruction(hp1, hp2) then
  9027. Exit;
  9028. if (hp2.typ = ait_instruction) and
  9029. (
  9030. { Register sizes must exactly match }
  9031. (
  9032. (taicpu(hp2).opcode = A_CMP) and
  9033. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9034. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9035. ) or (
  9036. (taicpu(hp2).opcode = A_TEST) and
  9037. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9038. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9039. )
  9040. ) and GetNextInstruction(hp2, hp3) and
  9041. (hp3.typ = ait_instruction) and
  9042. (taicpu(hp3).opcode = A_JCC) and
  9043. (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
  9044. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9045. begin
  9046. { Check condition of jump }
  9047. { Always true? }
  9048. if condition_in(C_E, taicpu(hp3).condition) then
  9049. begin
  9050. { Copy label symbol and obtain matching label entry for the
  9051. conditional jump, as this will be our destination}
  9052. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9053. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9054. Result := True;
  9055. end
  9056. { Always false? }
  9057. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9058. begin
  9059. { This is only worth it if there's a jump to take }
  9060. case hp2.typ of
  9061. ait_instruction:
  9062. begin
  9063. if taicpu(hp2).opcode = A_JMP then
  9064. begin
  9065. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9066. { An unconditional jump follows the conditional jump which will always be false,
  9067. so use this jump's destination for the new jump }
  9068. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9069. Result := True;
  9070. end
  9071. else if taicpu(hp2).opcode = A_JCC then
  9072. begin
  9073. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9074. if condition_in(C_E, taicpu(hp2).condition) then
  9075. begin
  9076. { A second conditional jump follows the conditional jump which will always be false,
  9077. while the second jump is always True, so use this jump's destination for the new jump }
  9078. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9079. Result := True;
  9080. end;
  9081. { Don't risk it if the jump isn't always true (Result remains False) }
  9082. end;
  9083. end;
  9084. else
  9085. { If anything else don't optimise };
  9086. end;
  9087. end;
  9088. if Result then
  9089. begin
  9090. { Just so we have something to insert as a paremeter}
  9091. reference_reset(NewRef, 1, []);
  9092. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9093. { Now actually load the correct parameter (this also
  9094. increases the reference count) }
  9095. NewInstr.loadsymbol(0, DestLabel, 0);
  9096. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9097. begin
  9098. { Get instruction before original label (may not be p under -O3) }
  9099. if not GetLastInstruction(hp1, hp2) then
  9100. { Shouldn't fail here }
  9101. InternalError(2021040701);
  9102. end
  9103. else
  9104. hp2 := p;
  9105. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9106. AsmL.InsertAfter(NewInstr, hp2);
  9107. { Add new alignment field }
  9108. (* AsmL.InsertAfter(
  9109. cai_align.create_max(
  9110. current_settings.alignment.jumpalign,
  9111. current_settings.alignment.jumpalignskipmax
  9112. ),
  9113. NewInstr
  9114. ); *)
  9115. end;
  9116. Exit;
  9117. end;
  9118. end;
  9119. else
  9120. ;
  9121. end;
  9122. end;
  9123. if not GetNextInstruction(p, hp1) then
  9124. Exit;
  9125. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9126. begin
  9127. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9128. begin
  9129. Result := True;
  9130. Exit;
  9131. end;
  9132. { This optimisation is only effective on a second run of Pass 2,
  9133. hence -O3 or above.
  9134. Change:
  9135. mov %reg1,%reg2
  9136. cmp/test (contains %reg1)
  9137. mov x, %reg1
  9138. (another mov or a j(c))
  9139. To:
  9140. mov %reg1,%reg2
  9141. mov x, %reg1
  9142. cmp (%reg1 replaced with %reg2)
  9143. (another mov or a j(c))
  9144. The requirement of an additional MOV or a jump ensures there
  9145. isn't performance loss, since a j(c) will permit macro-fusion
  9146. with the cmp instruction, while another MOV likely means it's
  9147. not all being executed in a single cycle due to parallelisation.
  9148. }
  9149. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9150. MatchOpType(taicpu(p), top_reg, top_reg) and
  9151. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9152. GetNextInstruction(hp1, hp2) and
  9153. MatchInstruction(hp2, A_MOV, []) and
  9154. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9155. { Registers don't have to be the same size in this case }
  9156. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9157. GetNextInstruction(hp2, hp3) and
  9158. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9159. { Make sure the operands in the camparison can be safely replaced }
  9160. (
  9161. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9162. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9163. ) and
  9164. (
  9165. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9166. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9167. ) then
  9168. begin
  9169. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9170. AsmL.Remove(hp2);
  9171. AsmL.InsertAfter(hp2, p);
  9172. Result := True;
  9173. Exit;
  9174. end;
  9175. end;
  9176. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9177. begin
  9178. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9179. further, but we can't just put this jump optimisation in pass 1
  9180. because it tends to perform worse when conditional jumps are
  9181. nearby (e.g. when converting CMOV instructions). [Kit] }
  9182. CopyUsedRegs(TempTracking);
  9183. UpdateUsedRegs(tai(p.Next));
  9184. if OptPass2JMP(hp1) then
  9185. begin
  9186. { Restore register state }
  9187. RestoreUsedRegs(TempTracking);
  9188. ReleaseUsedRegs(TempTracking);
  9189. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9190. OptPass1MOV(p);
  9191. Result := True;
  9192. Exit;
  9193. end;
  9194. { If OptPass2JMP returned False, no optimisations were done to
  9195. the jump and there are no further optimisations that can be done
  9196. to the MOV instruction on this pass other than FuncMov2Func }
  9197. { Restore register state }
  9198. RestoreUsedRegs(TempTracking);
  9199. ReleaseUsedRegs(TempTracking);
  9200. Result := FuncMov2Func(p, hp1);
  9201. Exit;
  9202. end;
  9203. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9204. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9205. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9206. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9207. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9208. begin
  9209. { Change:
  9210. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9211. addl/q $x,%reg2 subl/q $x,%reg2
  9212. To:
  9213. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9214. }
  9215. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9216. { be lazy, checking separately for sub would be slightly better }
  9217. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9218. begin
  9219. TransferUsedRegs(TmpUsedRegs);
  9220. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9221. if TryMovArith2Lea(hp1) then
  9222. begin
  9223. Result := True;
  9224. Exit;
  9225. end
  9226. end
  9227. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9228. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9229. { Same as above, but also adds or subtracts to %reg2 in between.
  9230. It's still valid as long as the flags aren't in use }
  9231. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9232. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9233. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9234. { be lazy, checking separately for sub would be slightly better }
  9235. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9236. begin
  9237. TransferUsedRegs(TmpUsedRegs);
  9238. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9239. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9240. if TryMovArith2Lea(hp2) then
  9241. begin
  9242. Result := True;
  9243. Exit;
  9244. end;
  9245. end;
  9246. end;
  9247. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9248. {$ifdef x86_64}
  9249. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9250. {$else x86_64}
  9251. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9252. {$endif x86_64}
  9253. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9254. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9255. { mov reg1, reg2 mov reg1, reg2
  9256. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9257. begin
  9258. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9259. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9260. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9261. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9262. TransferUsedRegs(TmpUsedRegs);
  9263. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9264. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9265. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9266. then
  9267. begin
  9268. RemoveCurrentP(p, hp1);
  9269. Result:=true;
  9270. end;
  9271. Exit;
  9272. end;
  9273. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9274. IsXCHGAcceptable and
  9275. { XCHG doesn't support 8-bit registers }
  9276. (taicpu(p).opsize <> S_B) and
  9277. MatchInstruction(hp1, A_MOV, []) and
  9278. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9279. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9280. GetNextInstruction(hp1, hp2) and
  9281. MatchInstruction(hp2, A_MOV, []) and
  9282. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9283. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9284. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9285. begin
  9286. { mov %reg1,%reg2
  9287. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9288. mov %reg2,%reg3
  9289. (%reg2 not used afterwards)
  9290. Note that xchg takes 3 cycles to execute, and generally mov's take
  9291. only one cycle apiece, but the first two mov's can be executed in
  9292. parallel, only taking 2 cycles overall. Older processors should
  9293. therefore only optimise for size. [Kit]
  9294. }
  9295. TransferUsedRegs(TmpUsedRegs);
  9296. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9297. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9298. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9299. begin
  9300. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9301. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9302. taicpu(hp1).opcode := A_XCHG;
  9303. RemoveCurrentP(p, hp1);
  9304. RemoveInstruction(hp2);
  9305. Result := True;
  9306. Exit;
  9307. end;
  9308. end;
  9309. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9310. MatchInstruction(hp1, A_SAR, []) then
  9311. begin
  9312. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9313. begin
  9314. { the use of %edx also covers the opsize being S_L }
  9315. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9316. begin
  9317. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9318. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9319. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9320. begin
  9321. { Change:
  9322. movl %eax,%edx
  9323. sarl $31,%edx
  9324. To:
  9325. cltd
  9326. }
  9327. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9328. RemoveInstruction(hp1);
  9329. taicpu(p).opcode := A_CDQ;
  9330. taicpu(p).opsize := S_NO;
  9331. taicpu(p).clearop(1);
  9332. taicpu(p).clearop(0);
  9333. taicpu(p).ops:=0;
  9334. Result := True;
  9335. Exit;
  9336. end
  9337. else if (cs_opt_size in current_settings.optimizerswitches) and
  9338. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9339. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9340. begin
  9341. { Change:
  9342. movl %edx,%eax
  9343. sarl $31,%edx
  9344. To:
  9345. movl %edx,%eax
  9346. cltd
  9347. Note that this creates a dependency between the two instructions,
  9348. so only perform if optimising for size.
  9349. }
  9350. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9351. taicpu(hp1).opcode := A_CDQ;
  9352. taicpu(hp1).opsize := S_NO;
  9353. taicpu(hp1).clearop(1);
  9354. taicpu(hp1).clearop(0);
  9355. taicpu(hp1).ops:=0;
  9356. Include(OptsToCheck, aoc_ForceNewIteration);
  9357. Exit;
  9358. end;
  9359. {$ifndef x86_64}
  9360. end
  9361. { Don't bother if CMOV is supported, because a more optimal
  9362. sequence would have been generated for the Abs() intrinsic }
  9363. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9364. { the use of %eax also covers the opsize being S_L }
  9365. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9366. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9367. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9368. GetNextInstruction(hp1, hp2) and
  9369. MatchInstruction(hp2, A_XOR, [S_L]) and
  9370. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9371. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9372. GetNextInstruction(hp2, hp3) and
  9373. MatchInstruction(hp3, A_SUB, [S_L]) and
  9374. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9375. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9376. begin
  9377. { Change:
  9378. movl %eax,%edx
  9379. sarl $31,%eax
  9380. xorl %eax,%edx
  9381. subl %eax,%edx
  9382. (Instruction that uses %edx)
  9383. (%eax deallocated)
  9384. (%edx deallocated)
  9385. To:
  9386. cltd
  9387. xorl %edx,%eax <-- Note the registers have swapped
  9388. subl %edx,%eax
  9389. (Instruction that uses %eax) <-- %eax rather than %edx
  9390. }
  9391. TransferUsedRegs(TmpUsedRegs);
  9392. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9394. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9395. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9396. begin
  9397. if GetNextInstruction(hp3, hp4) and
  9398. not RegModifiedByInstruction(NR_EDX, hp4) and
  9399. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9400. begin
  9401. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9402. taicpu(p).opcode := A_CDQ;
  9403. taicpu(p).clearop(1);
  9404. taicpu(p).clearop(0);
  9405. taicpu(p).ops:=0;
  9406. RemoveInstruction(hp1);
  9407. taicpu(hp2).loadreg(0, NR_EDX);
  9408. taicpu(hp2).loadreg(1, NR_EAX);
  9409. taicpu(hp3).loadreg(0, NR_EDX);
  9410. taicpu(hp3).loadreg(1, NR_EAX);
  9411. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9412. { Convert references in the following instruction (hp4) from %edx to %eax }
  9413. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9414. with taicpu(hp4).oper[OperIdx]^ do
  9415. case typ of
  9416. top_reg:
  9417. if getsupreg(reg) = RS_EDX then
  9418. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9419. top_ref:
  9420. begin
  9421. if getsupreg(reg) = RS_EDX then
  9422. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9423. if getsupreg(reg) = RS_EDX then
  9424. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9425. end;
  9426. else
  9427. ;
  9428. end;
  9429. Result := True;
  9430. Exit;
  9431. end;
  9432. end;
  9433. {$else x86_64}
  9434. end;
  9435. end
  9436. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9437. { the use of %rdx also covers the opsize being S_Q }
  9438. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9439. begin
  9440. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9441. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9442. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9443. begin
  9444. { Change:
  9445. movq %rax,%rdx
  9446. sarq $63,%rdx
  9447. To:
  9448. cqto
  9449. }
  9450. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9451. RemoveInstruction(hp1);
  9452. taicpu(p).opcode := A_CQO;
  9453. taicpu(p).opsize := S_NO;
  9454. taicpu(p).clearop(1);
  9455. taicpu(p).clearop(0);
  9456. taicpu(p).ops:=0;
  9457. Result := True;
  9458. Exit;
  9459. end
  9460. else if (cs_opt_size in current_settings.optimizerswitches) and
  9461. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9462. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9463. begin
  9464. { Change:
  9465. movq %rdx,%rax
  9466. sarq $63,%rdx
  9467. To:
  9468. movq %rdx,%rax
  9469. cqto
  9470. Note that this creates a dependency between the two instructions,
  9471. so only perform if optimising for size.
  9472. }
  9473. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9474. taicpu(hp1).opcode := A_CQO;
  9475. taicpu(hp1).opsize := S_NO;
  9476. taicpu(hp1).clearop(1);
  9477. taicpu(hp1).clearop(0);
  9478. taicpu(hp1).ops:=0;
  9479. Include(OptsToCheck, aoc_ForceNewIteration);
  9480. Exit;
  9481. {$endif x86_64}
  9482. end;
  9483. end;
  9484. end;
  9485. if MatchInstruction(hp1, A_MOV, []) and
  9486. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9487. { Though "GetNextInstruction" could be factored out, along with
  9488. the instructions that depend on hp2, it is an expensive call that
  9489. should be delayed for as long as possible, hence we do cheaper
  9490. checks first that are likely to be False. [Kit] }
  9491. begin
  9492. if (
  9493. (
  9494. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9495. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9496. (
  9497. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9498. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9499. )
  9500. ) or
  9501. (
  9502. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9503. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9504. (
  9505. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9506. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9507. )
  9508. )
  9509. ) and
  9510. GetNextInstruction(hp1, hp2) and
  9511. MatchInstruction(hp2, A_SAR, []) and
  9512. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9513. begin
  9514. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9515. begin
  9516. { Change:
  9517. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9518. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9519. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9520. To:
  9521. movl r/m,%eax <- Note the change in register
  9522. cltd
  9523. }
  9524. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9525. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9526. taicpu(p).loadreg(1, NR_EAX);
  9527. taicpu(hp1).opcode := A_CDQ;
  9528. taicpu(hp1).clearop(1);
  9529. taicpu(hp1).clearop(0);
  9530. taicpu(hp1).ops:=0;
  9531. RemoveInstruction(hp2);
  9532. Include(OptsToCheck, aoc_ForceNewIteration);
  9533. (*
  9534. {$ifdef x86_64}
  9535. end
  9536. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9537. { This code sequence does not get generated - however it might become useful
  9538. if and when 128-bit signed integer types make an appearance, so the code
  9539. is kept here for when it is eventually needed. [Kit] }
  9540. (
  9541. (
  9542. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9543. (
  9544. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9545. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9546. )
  9547. ) or
  9548. (
  9549. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9550. (
  9551. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9552. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9553. )
  9554. )
  9555. ) and
  9556. GetNextInstruction(hp1, hp2) and
  9557. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9558. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9559. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9560. begin
  9561. { Change:
  9562. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9563. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9564. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9565. To:
  9566. movq r/m,%rax <- Note the change in register
  9567. cqto
  9568. }
  9569. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9570. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9571. taicpu(p).loadreg(1, NR_RAX);
  9572. taicpu(hp1).opcode := A_CQO;
  9573. taicpu(hp1).clearop(1);
  9574. taicpu(hp1).clearop(0);
  9575. taicpu(hp1).ops:=0;
  9576. RemoveInstruction(hp2);
  9577. Include(OptsToCheck, aoc_ForceNewIteration);
  9578. {$endif x86_64}
  9579. *)
  9580. end;
  9581. end;
  9582. {$ifdef x86_64}
  9583. end;
  9584. if (taicpu(p).opsize = S_L) and
  9585. (taicpu(p).oper[1]^.typ = top_reg) and
  9586. (
  9587. MatchInstruction(hp1, A_MOV,[]) and
  9588. (taicpu(hp1).opsize = S_L) and
  9589. (taicpu(hp1).oper[1]^.typ = top_reg)
  9590. ) and (
  9591. GetNextInstruction(hp1, hp2) and
  9592. (tai(hp2).typ=ait_instruction) and
  9593. (taicpu(hp2).opsize = S_Q) and
  9594. (
  9595. (
  9596. MatchInstruction(hp2, A_ADD,[]) and
  9597. (taicpu(hp2).opsize = S_Q) and
  9598. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9599. (
  9600. (
  9601. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9602. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9603. ) or (
  9604. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9605. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9606. )
  9607. )
  9608. ) or (
  9609. MatchInstruction(hp2, A_LEA,[]) and
  9610. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9611. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9612. (
  9613. (
  9614. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9615. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9616. ) or (
  9617. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9618. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9619. )
  9620. ) and (
  9621. (
  9622. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9623. ) or (
  9624. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9625. )
  9626. )
  9627. )
  9628. )
  9629. ) and (
  9630. GetNextInstruction(hp2, hp3) and
  9631. MatchInstruction(hp3, A_SHR,[]) and
  9632. (taicpu(hp3).opsize = S_Q) and
  9633. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9634. (taicpu(hp3).oper[0]^.val = 1) and
  9635. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9636. ) then
  9637. begin
  9638. { Change movl x, reg1d movl x, reg1d
  9639. movl y, reg2d movl y, reg2d
  9640. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9641. shrq $1, reg1q shrq $1, reg1q
  9642. ( reg1d and reg2d can be switched around in the first two instructions )
  9643. To movl x, reg1d
  9644. addl y, reg1d
  9645. rcrl $1, reg1d
  9646. This corresponds to the common expression (x + y) shr 1, where
  9647. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9648. smaller code, but won't account for x + y causing an overflow). [Kit]
  9649. }
  9650. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9651. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9652. begin
  9653. { Change first MOV command to have the same register as the final output }
  9654. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9655. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9656. Result := True;
  9657. end
  9658. else
  9659. begin
  9660. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9661. Include(OptsToCheck, aoc_ForceNewIteration);
  9662. end;
  9663. { Change second MOV command to an ADD command. This is easier than
  9664. converting the existing command because it means we don't have to
  9665. touch 'y', which might be a complicated reference, and also the
  9666. fact that the third command might either be ADD or LEA. [Kit] }
  9667. taicpu(hp1).opcode := A_ADD;
  9668. { Delete old ADD/LEA instruction }
  9669. RemoveInstruction(hp2);
  9670. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9671. taicpu(hp3).opcode := A_RCR;
  9672. taicpu(hp3).changeopsize(S_L);
  9673. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9674. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9675. called, so FuncMov2Func below is safe to call }
  9676. {$endif x86_64}
  9677. end;
  9678. if FuncMov2Func(p, hp1) then
  9679. begin
  9680. Result := True;
  9681. Exit;
  9682. end;
  9683. end;
  9684. {$push}
  9685. {$q-}{$r-}
  9686. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9687. var
  9688. ThisReg: TRegister;
  9689. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9690. TargetSubReg: TSubRegister;
  9691. hp1, hp2: tai;
  9692. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9693. { Store list of found instructions so we don't have to call
  9694. GetNextInstructionUsingReg multiple times }
  9695. InstrList: array of taicpu;
  9696. InstrMax, Index: Integer;
  9697. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9698. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9699. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9700. WorkingValue: TCgInt;
  9701. PreMessage: string;
  9702. { Data flow analysis }
  9703. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9704. BitwiseOnly, OrXorUsed,
  9705. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9706. function CheckOverflowConditions: Boolean;
  9707. begin
  9708. Result := True;
  9709. if (TestValSignedMax > SignedUpperLimit) then
  9710. UpperSignedOverflow := True;
  9711. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9712. LowerSignedOverflow := True;
  9713. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9714. LowerUnsignedOverflow := True;
  9715. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9716. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9717. begin
  9718. { Absolute overflow }
  9719. Result := False;
  9720. Exit;
  9721. end;
  9722. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9723. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9724. ShiftDownOverflow := True;
  9725. if (TestValMin < 0) or (TestValMax < 0) then
  9726. begin
  9727. LowerUnsignedOverflow := True;
  9728. UpperUnsignedOverflow := True;
  9729. end;
  9730. end;
  9731. function AdjustInitialLoadAndSize: Boolean;
  9732. begin
  9733. Result := False;
  9734. if not p_removed then
  9735. begin
  9736. if TargetSize = MinSize then
  9737. begin
  9738. { Convert the input MOVZX to a MOV }
  9739. if (taicpu(p).oper[0]^.typ = top_reg) and
  9740. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9741. begin
  9742. { Or remove it completely! }
  9743. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9744. RemoveCurrentP(p);
  9745. p_removed := True;
  9746. end
  9747. else
  9748. begin
  9749. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9750. taicpu(p).opcode := A_MOV;
  9751. taicpu(p).oper[1]^.reg := ThisReg;
  9752. taicpu(p).opsize := TargetSize;
  9753. end;
  9754. Result := True;
  9755. end
  9756. else if TargetSize <> MaxSize then
  9757. begin
  9758. case MaxSize of
  9759. S_L:
  9760. if TargetSize = S_W then
  9761. begin
  9762. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9763. taicpu(p).opsize := S_BW;
  9764. taicpu(p).oper[1]^.reg := ThisReg;
  9765. Result := True;
  9766. end
  9767. else
  9768. InternalError(2020112341);
  9769. S_W:
  9770. if TargetSize = S_L then
  9771. begin
  9772. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9773. taicpu(p).opsize := S_BL;
  9774. taicpu(p).oper[1]^.reg := ThisReg;
  9775. Result := True;
  9776. end
  9777. else
  9778. InternalError(2020112342);
  9779. else
  9780. ;
  9781. end;
  9782. end
  9783. else if not hp1_removed and not RegInUse then
  9784. begin
  9785. { If we have something like:
  9786. movzbl (oper),%regd
  9787. add x, %regd
  9788. movzbl %regb, %regd
  9789. We can reduce the register size to the input of the final
  9790. movzbl instruction. Overflows won't have any effect.
  9791. }
  9792. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9793. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9794. begin
  9795. TargetSize := S_B;
  9796. setsubreg(ThisReg, R_SUBL);
  9797. Result := True;
  9798. end
  9799. else if (taicpu(p).opsize = S_WL) and
  9800. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9801. begin
  9802. TargetSize := S_W;
  9803. setsubreg(ThisReg, R_SUBW);
  9804. Result := True;
  9805. end;
  9806. if Result then
  9807. begin
  9808. { Convert the input MOVZX to a MOV }
  9809. if (taicpu(p).oper[0]^.typ = top_reg) and
  9810. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9811. begin
  9812. { Or remove it completely! }
  9813. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9814. RemoveCurrentP(p);
  9815. p_removed := True;
  9816. end
  9817. else
  9818. begin
  9819. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9820. taicpu(p).opcode := A_MOV;
  9821. taicpu(p).oper[1]^.reg := ThisReg;
  9822. taicpu(p).opsize := TargetSize;
  9823. end;
  9824. end;
  9825. end;
  9826. end;
  9827. end;
  9828. procedure AdjustFinalLoad;
  9829. begin
  9830. if not LowerUnsignedOverflow then
  9831. begin
  9832. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9833. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9834. begin
  9835. { Convert the output MOVZX to a MOV }
  9836. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9837. begin
  9838. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9839. if (MinSize = S_B) or
  9840. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9841. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9842. begin
  9843. { Remove it completely! }
  9844. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9845. { Be careful; if p = hp1 and p was also removed, p
  9846. will become a dangling pointer }
  9847. if p = hp1 then
  9848. begin
  9849. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9850. p_removed := True;
  9851. end
  9852. else
  9853. RemoveInstruction(hp1);
  9854. hp1_removed := True;
  9855. end;
  9856. end
  9857. else
  9858. begin
  9859. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9860. taicpu(hp1).opcode := A_MOV;
  9861. taicpu(hp1).oper[0]^.reg := ThisReg;
  9862. taicpu(hp1).opsize := TargetSize;
  9863. end;
  9864. end
  9865. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9866. begin
  9867. { Need to change the size of the output }
  9868. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9869. taicpu(hp1).oper[0]^.reg := ThisReg;
  9870. taicpu(hp1).opsize := S_BL;
  9871. end;
  9872. end;
  9873. end;
  9874. function CompressInstructions: Boolean;
  9875. var
  9876. LocalIndex: Integer;
  9877. begin
  9878. Result := False;
  9879. { The objective here is to try to find a combination that
  9880. removes one of the MOV/Z instructions. }
  9881. if (
  9882. (taicpu(p).oper[0]^.typ <> top_reg) or
  9883. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9884. ) and
  9885. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9886. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9887. begin
  9888. { Make a preference to remove the second MOVZX instruction }
  9889. case taicpu(hp1).opsize of
  9890. S_BL, S_WL:
  9891. begin
  9892. TargetSize := S_L;
  9893. TargetSubReg := R_SUBD;
  9894. end;
  9895. S_BW:
  9896. begin
  9897. TargetSize := S_W;
  9898. TargetSubReg := R_SUBW;
  9899. end;
  9900. else
  9901. InternalError(2020112302);
  9902. end;
  9903. end
  9904. else
  9905. begin
  9906. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9907. begin
  9908. { Exceeded lower bound but not upper bound }
  9909. TargetSize := MaxSize;
  9910. end
  9911. else if not LowerUnsignedOverflow then
  9912. begin
  9913. { Size didn't exceed lower bound }
  9914. TargetSize := MinSize;
  9915. end
  9916. else
  9917. Exit;
  9918. end;
  9919. case TargetSize of
  9920. S_B:
  9921. TargetSubReg := R_SUBL;
  9922. S_W:
  9923. TargetSubReg := R_SUBW;
  9924. S_L:
  9925. TargetSubReg := R_SUBD;
  9926. else
  9927. InternalError(2020112350);
  9928. end;
  9929. { Update the register to its new size }
  9930. setsubreg(ThisReg, TargetSubReg);
  9931. RegInUse := False;
  9932. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9933. begin
  9934. { Check to see if the active register is used afterwards;
  9935. if not, we can change it and make a saving. }
  9936. TransferUsedRegs(TmpUsedRegs);
  9937. { The target register may be marked as in use to cross
  9938. a jump to a distant label, so exclude it }
  9939. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9940. hp2 := p;
  9941. repeat
  9942. { Explicitly check for the excluded register (don't include the first
  9943. instruction as it may be reading from here }
  9944. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9945. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9946. begin
  9947. RegInUse := True;
  9948. Break;
  9949. end;
  9950. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9951. if not GetNextInstruction(hp2, hp2) then
  9952. InternalError(2020112340);
  9953. until (hp2 = hp1);
  9954. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9955. { We might still be able to get away with this }
  9956. RegInUse := not
  9957. (
  9958. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9959. (hp2.typ = ait_instruction) and
  9960. (
  9961. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9962. instruction that doesn't actually contain ThisReg }
  9963. (cs_opt_level3 in current_settings.optimizerswitches) or
  9964. RegInInstruction(ThisReg, hp2)
  9965. ) and
  9966. RegLoadedWithNewValue(ThisReg, hp2)
  9967. );
  9968. if not RegInUse then
  9969. begin
  9970. { Force the register size to the same as this instruction so it can be removed}
  9971. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9972. begin
  9973. TargetSize := S_L;
  9974. TargetSubReg := R_SUBD;
  9975. end
  9976. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9977. begin
  9978. TargetSize := S_W;
  9979. TargetSubReg := R_SUBW;
  9980. end;
  9981. ThisReg := taicpu(hp1).oper[1]^.reg;
  9982. setsubreg(ThisReg, TargetSubReg);
  9983. RegChanged := True;
  9984. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9985. TransferUsedRegs(TmpUsedRegs);
  9986. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9987. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9988. if p = hp1 then
  9989. begin
  9990. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9991. p_removed := True;
  9992. end
  9993. else
  9994. RemoveInstruction(hp1);
  9995. hp1_removed := True;
  9996. { Instruction will become "mov %reg,%reg" }
  9997. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9998. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9999. begin
  10000. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10001. RemoveCurrentP(p);
  10002. p_removed := True;
  10003. end
  10004. else
  10005. taicpu(p).oper[1]^.reg := ThisReg;
  10006. Result := True;
  10007. end
  10008. else
  10009. begin
  10010. if TargetSize <> MaxSize then
  10011. begin
  10012. { Since the register is in use, we have to force it to
  10013. MaxSize otherwise part of it may become undefined later on }
  10014. TargetSize := MaxSize;
  10015. case TargetSize of
  10016. S_B:
  10017. TargetSubReg := R_SUBL;
  10018. S_W:
  10019. TargetSubReg := R_SUBW;
  10020. S_L:
  10021. TargetSubReg := R_SUBD;
  10022. else
  10023. InternalError(2020112351);
  10024. end;
  10025. setsubreg(ThisReg, TargetSubReg);
  10026. end;
  10027. AdjustFinalLoad;
  10028. end;
  10029. end
  10030. else
  10031. AdjustFinalLoad;
  10032. Result := AdjustInitialLoadAndSize or Result;
  10033. { Now go through every instruction we found and change the
  10034. size. If TargetSize = MaxSize, then almost no changes are
  10035. needed and Result can remain False if it hasn't been set
  10036. yet.
  10037. If RegChanged is True, then the register requires changing
  10038. and so the point about TargetSize = MaxSize doesn't apply. }
  10039. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10040. begin
  10041. for LocalIndex := 0 to InstrMax do
  10042. begin
  10043. { If p_removed is true, then the original MOV/Z was removed
  10044. and removing the AND instruction may not be safe if it
  10045. appears first }
  10046. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10047. InternalError(2020112310);
  10048. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10049. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10050. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10051. InstrList[LocalIndex].opsize := TargetSize;
  10052. end;
  10053. Result := True;
  10054. end;
  10055. end;
  10056. begin
  10057. Result := False;
  10058. p_removed := False;
  10059. hp1_removed := False;
  10060. ThisReg := taicpu(p).oper[1]^.reg;
  10061. { Check for:
  10062. movs/z ###,%ecx (or %cx or %rcx)
  10063. ...
  10064. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10065. (dealloc %ecx)
  10066. Change to:
  10067. mov ###,%cl (if ### = %cl, then remove completely)
  10068. ...
  10069. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10070. }
  10071. if (getsupreg(ThisReg) = RS_ECX) and
  10072. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10073. (hp1.typ = ait_instruction) and
  10074. (
  10075. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10076. instruction that doesn't actually contain ECX }
  10077. (cs_opt_level3 in current_settings.optimizerswitches) or
  10078. RegInInstruction(NR_ECX, hp1) or
  10079. (
  10080. { It's common for the shift/rotate's read/write register to be
  10081. initialised in between, so under -O2 and under, search ahead
  10082. one more instruction
  10083. }
  10084. GetNextInstruction(hp1, hp1) and
  10085. (hp1.typ = ait_instruction) and
  10086. RegInInstruction(NR_ECX, hp1)
  10087. )
  10088. ) and
  10089. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10090. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10091. begin
  10092. TransferUsedRegs(TmpUsedRegs);
  10093. hp2 := p;
  10094. repeat
  10095. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10096. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10097. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10098. begin
  10099. case taicpu(p).opsize of
  10100. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10101. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10102. begin
  10103. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10104. RemoveCurrentP(p);
  10105. end
  10106. else
  10107. begin
  10108. taicpu(p).opcode := A_MOV;
  10109. taicpu(p).opsize := S_B;
  10110. taicpu(p).oper[1]^.reg := NR_CL;
  10111. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10112. end;
  10113. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10114. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10115. begin
  10116. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10117. RemoveCurrentP(p);
  10118. end
  10119. else
  10120. begin
  10121. taicpu(p).opcode := A_MOV;
  10122. taicpu(p).opsize := S_W;
  10123. taicpu(p).oper[1]^.reg := NR_CX;
  10124. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10125. end;
  10126. {$ifdef x86_64}
  10127. S_LQ:
  10128. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10129. begin
  10130. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10131. RemoveCurrentP(p);
  10132. end
  10133. else
  10134. begin
  10135. taicpu(p).opcode := A_MOV;
  10136. taicpu(p).opsize := S_L;
  10137. taicpu(p).oper[1]^.reg := NR_ECX;
  10138. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10139. end;
  10140. {$endif x86_64}
  10141. else
  10142. InternalError(2021120401);
  10143. end;
  10144. Result := True;
  10145. Exit;
  10146. end;
  10147. end;
  10148. { This is anything but quick! }
  10149. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10150. Exit;
  10151. SetLength(InstrList, 0);
  10152. InstrMax := -1;
  10153. case taicpu(p).opsize of
  10154. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10155. begin
  10156. {$if defined(i386) or defined(i8086)}
  10157. { If the target size is 8-bit, make sure we can actually encode it }
  10158. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10159. Exit;
  10160. {$endif i386 or i8086}
  10161. LowerLimit := $FF;
  10162. SignedLowerLimit := $7F;
  10163. SignedLowerLimitBottom := -128;
  10164. MinSize := S_B;
  10165. if taicpu(p).opsize = S_BW then
  10166. begin
  10167. MaxSize := S_W;
  10168. UpperLimit := $FFFF;
  10169. SignedUpperLimit := $7FFF;
  10170. SignedUpperLimitBottom := -32768;
  10171. end
  10172. else
  10173. begin
  10174. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10175. MaxSize := S_L;
  10176. UpperLimit := $FFFFFFFF;
  10177. SignedUpperLimit := $7FFFFFFF;
  10178. SignedUpperLimitBottom := -2147483648;
  10179. end;
  10180. end;
  10181. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10182. begin
  10183. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10184. LowerLimit := $FFFF;
  10185. SignedLowerLimit := $7FFF;
  10186. SignedLowerLimitBottom := -32768;
  10187. UpperLimit := $FFFFFFFF;
  10188. SignedUpperLimit := $7FFFFFFF;
  10189. SignedUpperLimitBottom := -2147483648;
  10190. MinSize := S_W;
  10191. MaxSize := S_L;
  10192. end;
  10193. {$ifdef x86_64}
  10194. S_LQ:
  10195. begin
  10196. { Both the lower and upper limits are set to 32-bit. If a limit
  10197. is breached, then optimisation is impossible }
  10198. LowerLimit := $FFFFFFFF;
  10199. SignedLowerLimit := $7FFFFFFF;
  10200. SignedLowerLimitBottom := -2147483648;
  10201. UpperLimit := $FFFFFFFF;
  10202. SignedUpperLimit := $7FFFFFFF;
  10203. SignedUpperLimitBottom := -2147483648;
  10204. MinSize := S_L;
  10205. MaxSize := S_L;
  10206. end;
  10207. {$endif x86_64}
  10208. else
  10209. InternalError(2020112301);
  10210. end;
  10211. TestValMin := 0;
  10212. TestValMax := LowerLimit;
  10213. TestValSignedMax := SignedLowerLimit;
  10214. TryShiftDownLimit := LowerLimit;
  10215. TryShiftDown := S_NO;
  10216. ShiftDownOverflow := False;
  10217. RegChanged := False;
  10218. BitwiseOnly := True;
  10219. OrXorUsed := False;
  10220. UpperSignedOverflow := False;
  10221. LowerSignedOverflow := False;
  10222. UpperUnsignedOverflow := False;
  10223. LowerUnsignedOverflow := False;
  10224. hp1 := p;
  10225. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10226. (hp1.typ = ait_instruction) and
  10227. (
  10228. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10229. instruction that doesn't actually contain ThisReg }
  10230. (cs_opt_level3 in current_settings.optimizerswitches) or
  10231. { This allows this Movx optimisation to work through the SETcc instructions
  10232. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10233. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10234. skip over these SETcc instructions). }
  10235. (taicpu(hp1).opcode = A_SETcc) or
  10236. RegInInstruction(ThisReg, hp1)
  10237. ) do
  10238. begin
  10239. case taicpu(hp1).opcode of
  10240. A_INC,A_DEC:
  10241. begin
  10242. { Has to be an exact match on the register }
  10243. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10244. Break;
  10245. if taicpu(hp1).opcode = A_INC then
  10246. begin
  10247. Inc(TestValMin);
  10248. Inc(TestValMax);
  10249. Inc(TestValSignedMax);
  10250. end
  10251. else
  10252. begin
  10253. Dec(TestValMin);
  10254. Dec(TestValMax);
  10255. Dec(TestValSignedMax);
  10256. end;
  10257. end;
  10258. A_TEST, A_CMP:
  10259. begin
  10260. if (
  10261. { Too high a risk of non-linear behaviour that breaks DFA
  10262. here, unless it's cmp $0,%reg, which is equivalent to
  10263. test %reg,%reg }
  10264. OrXorUsed and
  10265. (taicpu(hp1).opcode = A_CMP) and
  10266. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10267. ) or
  10268. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10269. { Has to be an exact match on the register }
  10270. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10271. (
  10272. { Permit "test %reg,%reg" }
  10273. (taicpu(hp1).opcode = A_TEST) and
  10274. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10275. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10276. ) or
  10277. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10278. { Make sure the comparison value is not smaller than the
  10279. smallest allowed signed value for the minimum size (e.g.
  10280. -128 for 8-bit) }
  10281. not (
  10282. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10283. { Is it in the negative range? }
  10284. (
  10285. (taicpu(hp1).oper[0]^.val < 0) and
  10286. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10287. )
  10288. ) then
  10289. Break;
  10290. { Check to see if the active register is used afterwards }
  10291. TransferUsedRegs(TmpUsedRegs);
  10292. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10293. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10294. begin
  10295. { Make sure the comparison or any previous instructions
  10296. hasn't pushed the test values outside of the range of
  10297. MinSize }
  10298. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10299. begin
  10300. { Exceeded lower bound but not upper bound }
  10301. Exit;
  10302. end
  10303. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10304. begin
  10305. { Size didn't exceed lower bound }
  10306. TargetSize := MinSize;
  10307. end
  10308. else
  10309. Break;
  10310. case TargetSize of
  10311. S_B:
  10312. TargetSubReg := R_SUBL;
  10313. S_W:
  10314. TargetSubReg := R_SUBW;
  10315. S_L:
  10316. TargetSubReg := R_SUBD;
  10317. else
  10318. InternalError(2021051002);
  10319. end;
  10320. if TargetSize <> MaxSize then
  10321. begin
  10322. { Update the register to its new size }
  10323. setsubreg(ThisReg, TargetSubReg);
  10324. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10325. taicpu(hp1).oper[1]^.reg := ThisReg;
  10326. taicpu(hp1).opsize := TargetSize;
  10327. { Convert the input MOVZX to a MOV if necessary }
  10328. AdjustInitialLoadAndSize;
  10329. if (InstrMax >= 0) then
  10330. begin
  10331. for Index := 0 to InstrMax do
  10332. begin
  10333. { If p_removed is true, then the original MOV/Z was removed
  10334. and removing the AND instruction may not be safe if it
  10335. appears first }
  10336. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10337. InternalError(2020112311);
  10338. if InstrList[Index].oper[0]^.typ = top_reg then
  10339. InstrList[Index].oper[0]^.reg := ThisReg;
  10340. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10341. InstrList[Index].opsize := MinSize;
  10342. end;
  10343. end;
  10344. Result := True;
  10345. end;
  10346. Exit;
  10347. end;
  10348. end;
  10349. A_SETcc:
  10350. begin
  10351. { This allows this Movx optimisation to work through the SETcc instructions
  10352. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10353. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10354. skip over these SETcc instructions). }
  10355. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10356. { Of course, break out if the current register is used }
  10357. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10358. Break
  10359. else
  10360. { We must use Continue so the instruction doesn't get added
  10361. to InstrList }
  10362. Continue;
  10363. end;
  10364. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10365. begin
  10366. if
  10367. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10368. { Has to be an exact match on the register }
  10369. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10370. (
  10371. (
  10372. (taicpu(hp1).oper[0]^.typ = top_const) and
  10373. (
  10374. (
  10375. (taicpu(hp1).opcode = A_SHL) and
  10376. (
  10377. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10378. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10379. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10380. )
  10381. ) or (
  10382. (taicpu(hp1).opcode <> A_SHL) and
  10383. (
  10384. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10385. { Is it in the negative range? }
  10386. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10387. )
  10388. )
  10389. )
  10390. ) or (
  10391. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10392. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10393. )
  10394. ) then
  10395. Break;
  10396. { Only process OR and XOR if there are only bitwise operations,
  10397. since otherwise they can too easily fool the data flow
  10398. analysis (they can cause non-linear behaviour) }
  10399. case taicpu(hp1).opcode of
  10400. A_ADD:
  10401. begin
  10402. if OrXorUsed then
  10403. { Too high a risk of non-linear behaviour that breaks DFA here }
  10404. Break
  10405. else
  10406. BitwiseOnly := False;
  10407. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10408. begin
  10409. TestValMin := TestValMin * 2;
  10410. TestValMax := TestValMax * 2;
  10411. TestValSignedMax := TestValSignedMax * 2;
  10412. end
  10413. else
  10414. begin
  10415. WorkingValue := taicpu(hp1).oper[0]^.val;
  10416. TestValMin := TestValMin + WorkingValue;
  10417. TestValMax := TestValMax + WorkingValue;
  10418. TestValSignedMax := TestValSignedMax + WorkingValue;
  10419. end;
  10420. end;
  10421. A_SUB:
  10422. begin
  10423. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10424. begin
  10425. TestValMin := 0;
  10426. TestValMax := 0;
  10427. TestValSignedMax := 0;
  10428. end
  10429. else
  10430. begin
  10431. if OrXorUsed then
  10432. { Too high a risk of non-linear behaviour that breaks DFA here }
  10433. Break
  10434. else
  10435. BitwiseOnly := False;
  10436. WorkingValue := taicpu(hp1).oper[0]^.val;
  10437. TestValMin := TestValMin - WorkingValue;
  10438. TestValMax := TestValMax - WorkingValue;
  10439. TestValSignedMax := TestValSignedMax - WorkingValue;
  10440. end;
  10441. end;
  10442. A_AND:
  10443. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10444. begin
  10445. { we might be able to go smaller if AND appears first }
  10446. if InstrMax = -1 then
  10447. case MinSize of
  10448. S_B:
  10449. ;
  10450. S_W:
  10451. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10452. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10453. begin
  10454. TryShiftDown := S_B;
  10455. TryShiftDownLimit := $FF;
  10456. end;
  10457. S_L:
  10458. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10459. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10460. begin
  10461. TryShiftDown := S_B;
  10462. TryShiftDownLimit := $FF;
  10463. end
  10464. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10465. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10466. begin
  10467. TryShiftDown := S_W;
  10468. TryShiftDownLimit := $FFFF;
  10469. end;
  10470. else
  10471. InternalError(2020112320);
  10472. end;
  10473. WorkingValue := taicpu(hp1).oper[0]^.val;
  10474. TestValMin := TestValMin and WorkingValue;
  10475. TestValMax := TestValMax and WorkingValue;
  10476. TestValSignedMax := TestValSignedMax and WorkingValue;
  10477. end;
  10478. A_OR:
  10479. begin
  10480. if not BitwiseOnly then
  10481. Break;
  10482. OrXorUsed := True;
  10483. WorkingValue := taicpu(hp1).oper[0]^.val;
  10484. TestValMin := TestValMin or WorkingValue;
  10485. TestValMax := TestValMax or WorkingValue;
  10486. TestValSignedMax := TestValSignedMax or WorkingValue;
  10487. end;
  10488. A_XOR:
  10489. begin
  10490. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10491. begin
  10492. TestValMin := 0;
  10493. TestValMax := 0;
  10494. TestValSignedMax := 0;
  10495. end
  10496. else
  10497. begin
  10498. if not BitwiseOnly then
  10499. Break;
  10500. OrXorUsed := True;
  10501. WorkingValue := taicpu(hp1).oper[0]^.val;
  10502. TestValMin := TestValMin xor WorkingValue;
  10503. TestValMax := TestValMax xor WorkingValue;
  10504. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10505. end;
  10506. end;
  10507. A_SHL:
  10508. begin
  10509. BitwiseOnly := False;
  10510. WorkingValue := taicpu(hp1).oper[0]^.val;
  10511. TestValMin := TestValMin shl WorkingValue;
  10512. TestValMax := TestValMax shl WorkingValue;
  10513. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10514. end;
  10515. A_SHR,
  10516. { The first instruction was MOVZX, so the value won't be negative }
  10517. A_SAR:
  10518. begin
  10519. if InstrMax <> -1 then
  10520. BitwiseOnly := False
  10521. else
  10522. { we might be able to go smaller if SHR appears first }
  10523. case MinSize of
  10524. S_B:
  10525. ;
  10526. S_W:
  10527. if (taicpu(hp1).oper[0]^.val >= 8) then
  10528. begin
  10529. TryShiftDown := S_B;
  10530. TryShiftDownLimit := $FF;
  10531. TryShiftDownSignedLimit := $7F;
  10532. TryShiftDownSignedLimitLower := -128;
  10533. end;
  10534. S_L:
  10535. if (taicpu(hp1).oper[0]^.val >= 24) then
  10536. begin
  10537. TryShiftDown := S_B;
  10538. TryShiftDownLimit := $FF;
  10539. TryShiftDownSignedLimit := $7F;
  10540. TryShiftDownSignedLimitLower := -128;
  10541. end
  10542. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10543. begin
  10544. TryShiftDown := S_W;
  10545. TryShiftDownLimit := $FFFF;
  10546. TryShiftDownSignedLimit := $7FFF;
  10547. TryShiftDownSignedLimitLower := -32768;
  10548. end;
  10549. else
  10550. InternalError(2020112321);
  10551. end;
  10552. WorkingValue := taicpu(hp1).oper[0]^.val;
  10553. if taicpu(hp1).opcode = A_SAR then
  10554. begin
  10555. TestValMin := SarInt64(TestValMin, WorkingValue);
  10556. TestValMax := SarInt64(TestValMax, WorkingValue);
  10557. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10558. end
  10559. else
  10560. begin
  10561. TestValMin := TestValMin shr WorkingValue;
  10562. TestValMax := TestValMax shr WorkingValue;
  10563. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10564. end;
  10565. end;
  10566. else
  10567. InternalError(2020112303);
  10568. end;
  10569. end;
  10570. (*
  10571. A_IMUL:
  10572. case taicpu(hp1).ops of
  10573. 2:
  10574. begin
  10575. if not MatchOpType(hp1, top_reg, top_reg) or
  10576. { Has to be an exact match on the register }
  10577. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10578. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10579. Break;
  10580. TestValMin := TestValMin * TestValMin;
  10581. TestValMax := TestValMax * TestValMax;
  10582. TestValSignedMax := TestValSignedMax * TestValMax;
  10583. end;
  10584. 3:
  10585. begin
  10586. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10587. { Has to be an exact match on the register }
  10588. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10589. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10590. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10591. { Is it in the negative range? }
  10592. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10593. Break;
  10594. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10595. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10596. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10597. end;
  10598. else
  10599. Break;
  10600. end;
  10601. A_IDIV:
  10602. case taicpu(hp1).ops of
  10603. 3:
  10604. begin
  10605. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10606. { Has to be an exact match on the register }
  10607. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10608. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10609. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10610. { Is it in the negative range? }
  10611. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10612. Break;
  10613. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10614. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10615. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10616. end;
  10617. else
  10618. Break;
  10619. end;
  10620. *)
  10621. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10622. begin
  10623. { If there are no instructions in between, then we might be able to make a saving }
  10624. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10625. Break;
  10626. { We have something like:
  10627. movzbw %dl,%dx
  10628. ...
  10629. movswl %dx,%edx
  10630. Change the latter to a zero-extension then enter the
  10631. A_MOVZX case branch.
  10632. }
  10633. {$ifdef x86_64}
  10634. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10635. begin
  10636. { this becomes a zero extension from 32-bit to 64-bit, but
  10637. the upper 32 bits are already zero, so just delete the
  10638. instruction }
  10639. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10640. RemoveInstruction(hp1);
  10641. Result := True;
  10642. Exit;
  10643. end
  10644. else
  10645. {$endif x86_64}
  10646. begin
  10647. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10648. taicpu(hp1).opcode := A_MOVZX;
  10649. {$ifdef x86_64}
  10650. case taicpu(hp1).opsize of
  10651. S_BQ:
  10652. begin
  10653. taicpu(hp1).opsize := S_BL;
  10654. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10655. end;
  10656. S_WQ:
  10657. begin
  10658. taicpu(hp1).opsize := S_WL;
  10659. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10660. end;
  10661. S_LQ:
  10662. begin
  10663. taicpu(hp1).opcode := A_MOV;
  10664. taicpu(hp1).opsize := S_L;
  10665. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10666. { In this instance, we need to break out because the
  10667. instruction is no longer MOVZX or MOVSXD }
  10668. Result := True;
  10669. Exit;
  10670. end;
  10671. else
  10672. ;
  10673. end;
  10674. {$endif x86_64}
  10675. Result := CompressInstructions;
  10676. Exit;
  10677. end;
  10678. end;
  10679. A_MOVZX:
  10680. begin
  10681. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10682. Break;
  10683. if (InstrMax = -1) then
  10684. begin
  10685. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10686. begin
  10687. { Optimise around i40003 }
  10688. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10689. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10690. {$ifndef x86_64}
  10691. and (
  10692. (taicpu(p).oper[0]^.typ <> top_reg) or
  10693. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10694. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10695. )
  10696. {$endif not x86_64}
  10697. then
  10698. begin
  10699. if (taicpu(p).oper[0]^.typ = top_reg) then
  10700. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10701. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10702. taicpu(p).opsize := S_BL;
  10703. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10704. RemoveInstruction(hp1);
  10705. Result := True;
  10706. Exit;
  10707. end;
  10708. end
  10709. else
  10710. begin
  10711. { Will return false if the second parameter isn't ThisReg
  10712. (can happen on -O2 and under) }
  10713. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10714. begin
  10715. { The two MOVZX instructions are adjacent, so remove the first one }
  10716. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10717. RemoveCurrentP(p);
  10718. Result := True;
  10719. Exit;
  10720. end;
  10721. Break;
  10722. end;
  10723. end;
  10724. Result := CompressInstructions;
  10725. Exit;
  10726. end;
  10727. else
  10728. { This includes ADC, SBB and IDIV }
  10729. Break;
  10730. end;
  10731. if not CheckOverflowConditions then
  10732. Break;
  10733. { Contains highest index (so instruction count - 1) }
  10734. Inc(InstrMax);
  10735. if InstrMax > High(InstrList) then
  10736. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10737. InstrList[InstrMax] := taicpu(hp1);
  10738. end;
  10739. end;
  10740. {$pop}
  10741. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10742. var
  10743. hp1 : tai;
  10744. begin
  10745. Result:=false;
  10746. if (taicpu(p).ops >= 2) and
  10747. ((taicpu(p).oper[0]^.typ = top_const) or
  10748. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10749. (taicpu(p).oper[1]^.typ = top_reg) and
  10750. ((taicpu(p).ops = 2) or
  10751. ((taicpu(p).oper[2]^.typ = top_reg) and
  10752. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10753. GetLastInstruction(p,hp1) and
  10754. MatchInstruction(hp1,A_MOV,[]) and
  10755. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10756. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10757. begin
  10758. TransferUsedRegs(TmpUsedRegs);
  10759. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10760. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10761. { change
  10762. mov reg1,reg2
  10763. imul y,reg2 to imul y,reg1,reg2 }
  10764. begin
  10765. taicpu(p).ops := 3;
  10766. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10767. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10768. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10769. RemoveInstruction(hp1);
  10770. result:=true;
  10771. end;
  10772. end;
  10773. end;
  10774. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10775. var
  10776. ThisLabel: TAsmLabel;
  10777. begin
  10778. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10779. ThisLabel.decrefs;
  10780. taicpu(p).condition := C_None;
  10781. taicpu(p).opcode := A_RET;
  10782. taicpu(p).is_jmp := false;
  10783. taicpu(p).ops := taicpu(ret_p).ops;
  10784. case taicpu(ret_p).ops of
  10785. 0:
  10786. taicpu(p).clearop(0);
  10787. 1:
  10788. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10789. else
  10790. internalerror(2016041301);
  10791. end;
  10792. { If the original label is now dead, it might turn out that the label
  10793. immediately follows p. As a result, everything beyond it, which will
  10794. be just some final register configuration and a RET instruction, is
  10795. now dead code. [Kit] }
  10796. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10797. running RemoveDeadCodeAfterJump for each RET instruction, because
  10798. this optimisation rarely happens and most RETs appear at the end of
  10799. routines where there is nothing that can be stripped. [Kit] }
  10800. if not ThisLabel.is_used then
  10801. RemoveDeadCodeAfterJump(p);
  10802. end;
  10803. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10804. var
  10805. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10806. Unconditional, PotentialModified: Boolean;
  10807. OperPtr: POper;
  10808. NewRef: TReference;
  10809. InstrList: array of taicpu;
  10810. InstrMax, Index: Integer;
  10811. const
  10812. {$ifdef DEBUG_AOPTCPU}
  10813. SNoFlags: shortstring = ' so the flags aren''t modified';
  10814. {$else DEBUG_AOPTCPU}
  10815. SNoFlags = '';
  10816. {$endif DEBUG_AOPTCPU}
  10817. begin
  10818. Result:=false;
  10819. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10820. begin
  10821. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10822. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10823. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10824. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10825. GetNextInstruction(hp1, hp2) and
  10826. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10827. { Change from: To:
  10828. set(C) %reg j(~C) label
  10829. test %reg,%reg/cmp $0,%reg
  10830. je label
  10831. set(C) %reg j(C) label
  10832. test %reg,%reg/cmp $0,%reg
  10833. jne label
  10834. (Also do something similar with sete/setne instead of je/jne)
  10835. }
  10836. begin
  10837. { Before we do anything else, we need to check the instructions
  10838. in between SETcc and TEST to make sure they don't modify the
  10839. FLAGS register - if -O2 or under, there won't be any
  10840. instructions between SET and TEST }
  10841. TransferUsedRegs(TmpUsedRegs);
  10842. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10843. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10844. begin
  10845. next := p;
  10846. SetLength(InstrList, 0);
  10847. InstrMax := -1;
  10848. PotentialModified := False;
  10849. { Make a note of every instruction that modifies the FLAGS
  10850. register }
  10851. while GetNextInstruction(next, next) and (next <> hp1) do
  10852. begin
  10853. if next.typ <> ait_instruction then
  10854. { GetNextInstructionUsingReg should have returned False }
  10855. InternalError(2021051701);
  10856. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10857. begin
  10858. case taicpu(next).opcode of
  10859. A_SETcc,
  10860. A_CMOVcc,
  10861. A_Jcc:
  10862. begin
  10863. if PotentialModified then
  10864. { Not safe because the flags were modified earlier }
  10865. Exit
  10866. else
  10867. { Condition is the same as the initial SETcc, so this is safe
  10868. (don't add to instruction list though) }
  10869. Continue;
  10870. end;
  10871. A_ADD:
  10872. begin
  10873. if (taicpu(next).opsize = S_B) or
  10874. { LEA doesn't support 8-bit operands }
  10875. (taicpu(next).oper[1]^.typ <> top_reg) or
  10876. { Must write to a register }
  10877. (taicpu(next).oper[0]^.typ = top_ref) then
  10878. { Require a constant or a register }
  10879. Exit;
  10880. PotentialModified := True;
  10881. end;
  10882. A_SUB:
  10883. begin
  10884. if (taicpu(next).opsize = S_B) or
  10885. { LEA doesn't support 8-bit operands }
  10886. (taicpu(next).oper[1]^.typ <> top_reg) or
  10887. { Must write to a register }
  10888. (taicpu(next).oper[0]^.typ <> top_const) or
  10889. (taicpu(next).oper[0]^.val = $80000000) then
  10890. { Can't subtract a register with LEA - also
  10891. check that the value isn't -2^31, as this
  10892. can't be negated }
  10893. Exit;
  10894. PotentialModified := True;
  10895. end;
  10896. A_SAL,
  10897. A_SHL:
  10898. begin
  10899. if (taicpu(next).opsize = S_B) or
  10900. { LEA doesn't support 8-bit operands }
  10901. (taicpu(next).oper[1]^.typ <> top_reg) or
  10902. { Must write to a register }
  10903. (taicpu(next).oper[0]^.typ <> top_const) or
  10904. (taicpu(next).oper[0]^.val < 0) or
  10905. (taicpu(next).oper[0]^.val > 3) then
  10906. Exit;
  10907. PotentialModified := True;
  10908. end;
  10909. A_IMUL:
  10910. begin
  10911. if (taicpu(next).ops <> 3) or
  10912. (taicpu(next).oper[1]^.typ <> top_reg) or
  10913. { Must write to a register }
  10914. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10915. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10916. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10917. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10918. Exit
  10919. else
  10920. PotentialModified := True;
  10921. end;
  10922. else
  10923. { Don't know how to change this, so abort }
  10924. Exit;
  10925. end;
  10926. { Contains highest index (so instruction count - 1) }
  10927. Inc(InstrMax);
  10928. if InstrMax > High(InstrList) then
  10929. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10930. InstrList[InstrMax] := taicpu(next);
  10931. end;
  10932. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10933. end;
  10934. if not Assigned(next) or (next <> hp1) then
  10935. { It should be equal to hp1 }
  10936. InternalError(2021051702);
  10937. { Cycle through each instruction and check to see if we can
  10938. change them to versions that don't modify the flags }
  10939. if (InstrMax >= 0) then
  10940. begin
  10941. for Index := 0 to InstrMax do
  10942. case InstrList[Index].opcode of
  10943. A_ADD:
  10944. begin
  10945. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10946. InstrList[Index].opcode := A_LEA;
  10947. reference_reset(NewRef, 1, []);
  10948. NewRef.base := InstrList[Index].oper[1]^.reg;
  10949. if InstrList[Index].oper[0]^.typ = top_reg then
  10950. begin
  10951. NewRef.index := InstrList[Index].oper[0]^.reg;
  10952. NewRef.scalefactor := 1;
  10953. end
  10954. else
  10955. NewRef.offset := InstrList[Index].oper[0]^.val;
  10956. InstrList[Index].loadref(0, NewRef);
  10957. end;
  10958. A_SUB:
  10959. begin
  10960. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10961. InstrList[Index].opcode := A_LEA;
  10962. reference_reset(NewRef, 1, []);
  10963. NewRef.base := InstrList[Index].oper[1]^.reg;
  10964. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10965. InstrList[Index].loadref(0, NewRef);
  10966. end;
  10967. A_SHL,
  10968. A_SAL:
  10969. begin
  10970. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10971. InstrList[Index].opcode := A_LEA;
  10972. reference_reset(NewRef, 1, []);
  10973. NewRef.index := InstrList[Index].oper[1]^.reg;
  10974. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10975. InstrList[Index].loadref(0, NewRef);
  10976. end;
  10977. A_IMUL:
  10978. begin
  10979. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10980. InstrList[Index].opcode := A_LEA;
  10981. reference_reset(NewRef, 1, []);
  10982. NewRef.index := InstrList[Index].oper[1]^.reg;
  10983. case InstrList[Index].oper[0]^.val of
  10984. 2, 4, 8:
  10985. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10986. else {3, 5 and 9}
  10987. begin
  10988. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10989. NewRef.base := InstrList[Index].oper[1]^.reg;
  10990. end;
  10991. end;
  10992. InstrList[Index].loadref(0, NewRef);
  10993. end;
  10994. else
  10995. InternalError(2021051710);
  10996. end;
  10997. end;
  10998. { Mark the FLAGS register as used across this whole block }
  10999. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11000. end;
  11001. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11002. JumpC := taicpu(hp2).condition;
  11003. Unconditional := False;
  11004. if conditions_equal(JumpC, C_E) then
  11005. SetC := inverse_cond(taicpu(p).condition)
  11006. else if conditions_equal(JumpC, C_NE) then
  11007. SetC := taicpu(p).condition
  11008. else
  11009. { We've got something weird here (and inefficent) }
  11010. begin
  11011. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11012. SetC := C_NONE;
  11013. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11014. if condition_in(C_AE, JumpC) then
  11015. Unconditional := True
  11016. else
  11017. { Not sure what to do with this jump - drop out }
  11018. Exit;
  11019. end;
  11020. RemoveInstruction(hp1);
  11021. if Unconditional then
  11022. MakeUnconditional(taicpu(hp2))
  11023. else
  11024. begin
  11025. if SetC = C_NONE then
  11026. InternalError(2018061402);
  11027. taicpu(hp2).SetCondition(SetC);
  11028. end;
  11029. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11030. TmpUsedRegs }
  11031. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11032. begin
  11033. RemoveCurrentp(p, hp2);
  11034. if taicpu(hp2).opcode = A_SETcc then
  11035. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11036. else
  11037. begin
  11038. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11039. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11040. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11041. end;
  11042. end
  11043. else
  11044. if taicpu(hp2).opcode = A_SETcc then
  11045. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11046. else
  11047. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11048. Result := True;
  11049. end
  11050. else if
  11051. { Make sure the instructions are adjacent }
  11052. (
  11053. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11054. GetNextInstruction(p, hp1)
  11055. ) and
  11056. MatchInstruction(hp1, A_MOV, [S_B]) and
  11057. { Writing to memory is allowed }
  11058. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11059. begin
  11060. {
  11061. Watch out for sequences such as:
  11062. set(c)b %regb
  11063. movb %regb,(ref)
  11064. movb $0,1(ref)
  11065. movb $0,2(ref)
  11066. movb $0,3(ref)
  11067. Much more efficient to turn it into:
  11068. movl $0,%regl
  11069. set(c)b %regb
  11070. movl %regl,(ref)
  11071. Or:
  11072. set(c)b %regb
  11073. movzbl %regb,%regl
  11074. movl %regl,(ref)
  11075. }
  11076. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11077. GetNextInstruction(hp1, hp2) and
  11078. MatchInstruction(hp2, A_MOV, [S_B]) and
  11079. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11080. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11081. begin
  11082. { Don't do anything else except set Result to True }
  11083. end
  11084. else
  11085. begin
  11086. if taicpu(p).oper[0]^.typ = top_reg then
  11087. begin
  11088. TransferUsedRegs(TmpUsedRegs);
  11089. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11090. end;
  11091. { If it's not a register, it's a memory address }
  11092. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11093. begin
  11094. { Even if the register is still in use, we can minimise the
  11095. pipeline stall by changing the MOV into another SETcc. }
  11096. taicpu(hp1).opcode := A_SETcc;
  11097. taicpu(hp1).condition := taicpu(p).condition;
  11098. if taicpu(hp1).oper[1]^.typ = top_ref then
  11099. begin
  11100. { Swapping the operand pointers like this is probably a
  11101. bit naughty, but it is far faster than using loadoper
  11102. to transfer the reference from oper[1] to oper[0] if
  11103. you take into account the extra procedure calls and
  11104. the memory allocation and deallocation required }
  11105. OperPtr := taicpu(hp1).oper[1];
  11106. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11107. taicpu(hp1).oper[0] := OperPtr;
  11108. end
  11109. else
  11110. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11111. taicpu(hp1).clearop(1);
  11112. taicpu(hp1).ops := 1;
  11113. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11114. end
  11115. else
  11116. begin
  11117. if taicpu(hp1).oper[1]^.typ = top_reg then
  11118. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11119. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11120. RemoveInstruction(hp1);
  11121. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11122. end
  11123. end;
  11124. Result := True;
  11125. end;
  11126. end;
  11127. end;
  11128. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11129. var
  11130. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11131. TargetReg: TRegister;
  11132. condition, inverted_condition: TAsmCond;
  11133. FoundMOV: Boolean;
  11134. begin
  11135. Result := False;
  11136. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11137. create the most optimial instructions possible due to limited
  11138. register availability, and there are situations where two
  11139. complementary "simple" CMOV blocks are created which, after the fact
  11140. can be merged into a "double" block. For example:
  11141. movw $257,%ax
  11142. movw $2,%r8w
  11143. xorl r9d,%r9d
  11144. testw $16,18(%rcx)
  11145. cmovew %ax,%dx
  11146. cmovew %r8w,%bx
  11147. cmovel %r9d,%r14d
  11148. movw $1283,%ax
  11149. movw $4,%r8w
  11150. movl $9,%r9d
  11151. cmovnew %ax,%dx
  11152. cmovnew %r8w,%bx
  11153. cmovnel %r9d,%r14d
  11154. The CMOVNE instructions at the end can be removed, and the
  11155. destination registers copied into the MOV instructions directly
  11156. above them, before finally being moved to before the first CMOVE
  11157. instructions, to produce:
  11158. movw $257,%ax
  11159. movw $2,%r8w
  11160. xorl r9d,%r9d
  11161. testw $16,18(%rcx)
  11162. movw $1283,%dx
  11163. movw $4,%bx
  11164. movl $9,%r14d
  11165. cmovew %ax,%dx
  11166. cmovew %r8w,%bx
  11167. cmovel %r9d,%r14d
  11168. Which can then be later optimised to:
  11169. movw $257,%ax
  11170. movw $2,%r8w
  11171. xorl r9d,%r9d
  11172. movw $1283,%dx
  11173. movw $4,%bx
  11174. movl $9,%r14d
  11175. testw $16,18(%rcx)
  11176. cmovew %ax,%dx
  11177. cmovew %r8w,%bx
  11178. cmovel %r9d,%r14d
  11179. }
  11180. TargetReg := taicpu(hp1).oper[1]^.reg;
  11181. condition := taicpu(hp1).condition;
  11182. inverted_condition := inverse_cond(condition);
  11183. pFirstMov := nil;
  11184. pLastMov := nil;
  11185. pCMOV := nil;
  11186. if (p.typ = ait_instruction) then
  11187. pCond := p
  11188. else if not GetNextInstruction(p, pCond) then
  11189. InternalError(2024012501);
  11190. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11191. { We should get the CMP or TEST instructeion }
  11192. InternalError(2024012502);
  11193. if (
  11194. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11195. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11196. ) then
  11197. begin
  11198. { We have to tread carefully here, hence why we're not using
  11199. GetNextInstructionUsingReg... we can only accept MOV and other
  11200. CMOV instructions. Anything else and we must drop out}
  11201. hp2 := hp1;
  11202. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11203. begin
  11204. if (hp2.typ <> ait_instruction) then
  11205. Exit;
  11206. case taicpu(hp2).opcode of
  11207. A_MOV:
  11208. begin
  11209. if not Assigned(pFirstMov) then
  11210. pFirstMov := hp2;
  11211. pLastMOV := hp2;
  11212. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11213. { Something different - drop out }
  11214. Exit;
  11215. { Otherwise, leave it for now }
  11216. end;
  11217. A_CMOVcc:
  11218. begin
  11219. if taicpu(hp2).condition = inverted_condition then
  11220. begin
  11221. { We found what we're looking for }
  11222. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11223. begin
  11224. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11225. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11226. begin
  11227. pCMOV := hp2;
  11228. Break;
  11229. end
  11230. else
  11231. { Unsafe reference - drop out }
  11232. Exit;
  11233. end;
  11234. end
  11235. else if taicpu(hp2).condition <> condition then
  11236. { Something weird - drop out }
  11237. Exit;
  11238. end;
  11239. else
  11240. { Invalid }
  11241. Exit;
  11242. end;
  11243. end;
  11244. if not Assigned(pCMOV) then
  11245. { No complementary CMOV found }
  11246. Exit;
  11247. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11248. begin
  11249. { Don't need to do anything special or search for a matching MOV }
  11250. Asml.Remove(pCMOV);
  11251. if RegInInstruction(TargetReg, pCond) then
  11252. { Make sure we don't overwrite the register if it's being used in the condition }
  11253. Asml.InsertAfter(pCMOV, pCond)
  11254. else
  11255. Asml.InsertBefore(pCMOV, pCond);
  11256. taicpu(pCMOV).opcode := A_MOV;
  11257. taicpu(pCMOV).condition := C_None;
  11258. { Don't need to worry about allocating new registers in these cases }
  11259. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11260. Result := True;
  11261. Exit;
  11262. end
  11263. else
  11264. begin
  11265. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11266. FoundMOV := False;
  11267. { Search for the MOV that sets the target register }
  11268. hp2 := pFirstMov;
  11269. repeat
  11270. if (taicpu(hp2).opcode = A_MOV) and
  11271. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11272. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11273. begin
  11274. { Change the destination }
  11275. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11276. if not FoundMOV then
  11277. begin
  11278. FoundMOV := True;
  11279. { Make sure the register is allocated }
  11280. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11281. end;
  11282. hp1 := tai(hp2.Previous);
  11283. Asml.Remove(hp2);
  11284. if RegInInstruction(TargetReg, pCond) then
  11285. { Make sure we don't overwrite the register if it's being used in the condition }
  11286. Asml.InsertAfter(hp2, pCond)
  11287. else
  11288. Asml.InsertBefore(hp2, pCond);
  11289. if (hp2 = pLastMov) then
  11290. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11291. Break;
  11292. hp2 := hp1;
  11293. end;
  11294. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11295. if FoundMOV then
  11296. { Delete the CMOV }
  11297. RemoveInstruction(pCMOV)
  11298. else
  11299. begin
  11300. { If no MOV was found, we have to actually move and transmute the CMOV }
  11301. Asml.Remove(pCMOV);
  11302. if RegInInstruction(TargetReg, pCond) then
  11303. { Make sure we don't overwrite the register if it's being used in the condition }
  11304. Asml.InsertAfter(pCMOV, pCond)
  11305. else
  11306. Asml.InsertBefore(pCMOV, pCond);
  11307. taicpu(pCMOV).opcode := A_MOV;
  11308. taicpu(pCMOV).condition := C_None;
  11309. end;
  11310. Result := True;
  11311. Exit;
  11312. end;
  11313. end;
  11314. end;
  11315. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11316. var
  11317. hp1, hp2, pCond: tai;
  11318. begin
  11319. Result := False;
  11320. { Search ahead for CMOV instructions }
  11321. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11322. begin
  11323. hp1 := p;
  11324. hp2 := p;
  11325. pCond := nil; { To prevent compiler warnings }
  11326. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11327. DEFAULTFLAGS }
  11328. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11329. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11330. pCond := p;
  11331. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11332. begin
  11333. if (hp1.typ <> ait_instruction) then
  11334. { Break out on markers and labels etc. }
  11335. Break;
  11336. case taicpu(hp1).opcode of
  11337. A_MOV:
  11338. { Ignore regular MOVs unless they are obviously not related
  11339. to a CMOV block }
  11340. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11341. Break;
  11342. A_CMOVcc:
  11343. if TryCmpCMovOpts(pCond, hp1) then
  11344. begin
  11345. hp1 := hp2;
  11346. { p itself isn't changed, and we're still inside a
  11347. while loop to catch subsequent CMOVs, so just flag
  11348. a new iteration }
  11349. Include(OptsToCheck, aoc_ForceNewIteration);
  11350. Continue;
  11351. end;
  11352. else
  11353. { Drop out if we find anything else }
  11354. Break;
  11355. end;
  11356. hp2 := hp1;
  11357. end;
  11358. end;
  11359. end;
  11360. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11361. var
  11362. hp1, hp2, pCond: tai;
  11363. SourceReg, TargetReg: TRegister;
  11364. begin
  11365. Result := False;
  11366. { In some situations, we end up with an inefficient arrangement of
  11367. instructions in the form of:
  11368. or %reg1,%reg2
  11369. (%reg1 deallocated)
  11370. test %reg2,%reg2
  11371. mov x,%reg2
  11372. we may be able to swap and rearrange the registers to produce:
  11373. or %reg2,%reg1
  11374. mov x,%reg2
  11375. test %reg1,%reg1
  11376. (%reg1 deallocated)
  11377. }
  11378. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11379. (taicpu(p).oper[1]^.typ = top_reg) and
  11380. (
  11381. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11382. MatchOperand(taicpu(p).oper[0]^, -1)
  11383. ) and
  11384. GetNextInstruction(p, hp1) and
  11385. MatchInstruction(hp1, A_MOV, []) and
  11386. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11387. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11388. begin
  11389. TargetReg := taicpu(p).oper[1]^.reg;
  11390. { Now look backwards to find a simple commutative operation: ADD,
  11391. IMUL (2-register version), OR, AND or XOR - whose destination
  11392. register is the same as TEST }
  11393. hp2 := p;
  11394. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11395. if RegInInstruction(TargetReg, hp2) then
  11396. begin
  11397. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11398. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11399. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11400. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11401. begin
  11402. SourceReg := taicpu(hp2).oper[0]^.reg;
  11403. if
  11404. { Make sure the MOV doesn't use the other register }
  11405. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11406. { And make sure the source register is not used afterwards }
  11407. not RegInUsedRegs(SourceReg, UsedRegs) then
  11408. begin
  11409. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11410. taicpu(hp2).oper[0]^.reg := TargetReg;
  11411. taicpu(hp2).oper[1]^.reg := SourceReg;
  11412. if taicpu(p).oper[0]^.typ = top_reg then
  11413. taicpu(p).oper[0]^.reg := SourceReg;
  11414. taicpu(p).oper[1]^.reg := SourceReg;
  11415. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11416. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11417. Include(OptsToCheck, aoc_ForceNewIteration);
  11418. { We can still check the following optimisations since
  11419. the instruction is still a TEST }
  11420. end;
  11421. end;
  11422. Break;
  11423. end;
  11424. end;
  11425. { Search ahead3 for CMOV instructions }
  11426. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11427. begin
  11428. hp1 := p;
  11429. hp2 := p;
  11430. pCond := nil; { To prevent compiler warnings }
  11431. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11432. DEFAULTFLAGS }
  11433. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11434. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11435. pCond := p;
  11436. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11437. begin
  11438. if (hp1.typ <> ait_instruction) then
  11439. { Break out on markers and labels etc. }
  11440. Break;
  11441. case taicpu(hp1).opcode of
  11442. A_MOV:
  11443. { Ignore regular MOVs unless they are obviously not related
  11444. to a CMOV block }
  11445. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11446. Break;
  11447. A_CMOVcc:
  11448. if TryCmpCMovOpts(pCond, hp1) then
  11449. begin
  11450. hp1 := hp2;
  11451. { p itself isn't changed, and we're still inside a
  11452. while loop to catch subsequent CMOVs, so just flag
  11453. a new iteration }
  11454. Include(OptsToCheck, aoc_ForceNewIteration);
  11455. Continue;
  11456. end;
  11457. else
  11458. { Drop out if we find anything else }
  11459. Break;
  11460. end;
  11461. hp2 := hp1;
  11462. end;
  11463. end;
  11464. end;
  11465. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11466. var
  11467. hp1: tai;
  11468. Count: Integer;
  11469. OrigLabel: TAsmLabel;
  11470. begin
  11471. result := False;
  11472. { Sometimes, the optimisations below can permit this }
  11473. RemoveDeadCodeAfterJump(p);
  11474. 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
  11475. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11476. begin
  11477. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11478. { Also a side-effect of optimisations }
  11479. if CollapseZeroDistJump(p, OrigLabel) then
  11480. begin
  11481. Result := True;
  11482. Exit;
  11483. end;
  11484. hp1 := GetLabelWithSym(OrigLabel);
  11485. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11486. begin
  11487. if taicpu(hp1).opcode = A_RET then
  11488. begin
  11489. {
  11490. change
  11491. jmp .L1
  11492. ...
  11493. .L1:
  11494. ret
  11495. into
  11496. ret
  11497. }
  11498. begin
  11499. ConvertJumpToRET(p, hp1);
  11500. result:=true;
  11501. end;
  11502. end
  11503. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11504. not (cs_opt_size in current_settings.optimizerswitches) and
  11505. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11506. begin
  11507. Result := True;
  11508. Exit;
  11509. end;
  11510. end;
  11511. end;
  11512. end;
  11513. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11514. begin
  11515. Result := assigned(p) and
  11516. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11517. (taicpu(p).oper[1]^.typ = top_reg) and
  11518. (
  11519. (taicpu(p).oper[0]^.typ = top_reg) or
  11520. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11521. it is not expected that this can cause a seg. violation }
  11522. (
  11523. (taicpu(p).oper[0]^.typ = top_ref) and
  11524. { TODO: Can we detect which references become constants at this
  11525. stage so we don't have to do a blanket ban? }
  11526. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11527. (
  11528. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11529. (
  11530. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11531. not RefModified and
  11532. { If the reference also appears in the condition, then we know it's safe, otherwise
  11533. any kind of access violation would have occurred already }
  11534. Assigned(cond_p) and
  11535. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11536. (cond_p.typ = ait_instruction) and
  11537. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11538. { Just consider 2-operand comparison instructions for now to be safe }
  11539. (taicpu(cond_p).ops = 2) and
  11540. (
  11541. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11542. (
  11543. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11544. { Don't risk identical registers but different offsets, as we may have constructs
  11545. such as buffer streams with things like length fields that indicate whether
  11546. any more data follows. And there are probably some contrived examples where
  11547. writing to offsets behind the one being read also lead to access violations }
  11548. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11549. (
  11550. { Check that we're not modifying a register that appears in the reference }
  11551. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11552. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11553. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11554. )
  11555. )
  11556. )
  11557. )
  11558. )
  11559. )
  11560. );
  11561. end;
  11562. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11563. begin
  11564. { Update integer registers, ignoring deallocations }
  11565. repeat
  11566. while assigned(p) and
  11567. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11568. (p.typ = ait_label) or
  11569. ((p.typ = ait_marker) and
  11570. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11571. p := tai(p.next);
  11572. while assigned(p) and
  11573. (p.typ=ait_RegAlloc) Do
  11574. begin
  11575. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11576. begin
  11577. case tai_regalloc(p).ratype of
  11578. ra_alloc :
  11579. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11580. else
  11581. ;
  11582. end;
  11583. end;
  11584. p := tai(p.next);
  11585. end;
  11586. until not(assigned(p)) or
  11587. (not(p.typ in SkipInstr) and
  11588. not((p.typ = ait_label) and
  11589. labelCanBeSkipped(tai_label(p))));
  11590. end;
  11591. {$ifndef 8086}
  11592. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11593. begin
  11594. Result := False;
  11595. EndJump := nil;
  11596. BlockStop := nil;
  11597. while (BlockStart <> fOptimizer.BlockEnd) and
  11598. { stop on labels }
  11599. (BlockStart.typ <> ait_label) do
  11600. begin
  11601. { Keep track of all integer registers that are used }
  11602. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11603. if BlockStart.typ = ait_instruction then
  11604. begin
  11605. if (taicpu(BlockStart).opcode = A_JMP) then
  11606. begin
  11607. if not IsJumpToLabel(taicpu(BlockStart)) or
  11608. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11609. Exit;
  11610. EndJump := BlockStart;
  11611. Break;
  11612. end
  11613. { Check to see if we have a valid MOV instruction instead }
  11614. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11615. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11616. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11617. begin
  11618. Exit;
  11619. end
  11620. else
  11621. { This will be a valid MOV }
  11622. fAllocationRange := BlockStart;
  11623. end;
  11624. OneBeforeBlock := BlockStart;
  11625. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11626. end;
  11627. if (BlockStart = fOptimizer.BlockEnd) then
  11628. Exit;
  11629. BlockStop := BlockStart;
  11630. Result := True;
  11631. end;
  11632. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11633. var
  11634. hp1: tai;
  11635. RefModified: Boolean;
  11636. begin
  11637. Result := 0;
  11638. hp1 := BlockStart;
  11639. RefModified := False; { As long as the condition is inverted, this can be reset }
  11640. while assigned(hp1) and
  11641. (hp1 <> BlockStop) do
  11642. begin
  11643. case hp1.typ of
  11644. ait_instruction:
  11645. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11646. begin
  11647. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11648. begin
  11649. Inc(Result);
  11650. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11651. Assigned(fCondition) and
  11652. { Will have 2 operands }
  11653. (
  11654. (
  11655. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11656. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11657. ) or
  11658. (
  11659. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11660. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11661. )
  11662. ) then
  11663. { It is no longer safe to use the reference in the condition.
  11664. this prevents problems such as:
  11665. mov (%reg),%reg
  11666. mov (%reg),...
  11667. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11668. (fixes #40165)
  11669. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11670. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11671. }
  11672. RefModified := True;
  11673. end
  11674. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11675. { CMOV with constants grows the code size }
  11676. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11677. begin
  11678. { Register was reserved by TryCMOVConst and
  11679. stored on ConstRegs }
  11680. end
  11681. else
  11682. begin
  11683. Result := -1;
  11684. Exit;
  11685. end;
  11686. end
  11687. else
  11688. begin
  11689. Result := -1;
  11690. Exit;
  11691. end;
  11692. else
  11693. { Most likely an align };
  11694. end;
  11695. fOptimizer.GetNextInstruction(hp1, hp1);
  11696. end;
  11697. end;
  11698. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11699. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11700. (this is done as a separate stage because the double types are extensions of the branching type,
  11701. but we can't discount the conditional jump until the last step) }
  11702. procedure EvaluateBranchingType;
  11703. begin
  11704. Inc(CMOVScore);
  11705. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11706. { Too many instructions to be worthwhile }
  11707. fState := tsInvalid;
  11708. end;
  11709. var
  11710. hp1: tai;
  11711. Count: Integer;
  11712. begin
  11713. { Table of valid CMOV block types
  11714. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11715. ---------- --------- --------- --------- --------- ---------
  11716. tsSimple X Yes X X X
  11717. tsDetour = 1st X X X X
  11718. tsBranching <> Mid Yes X X X
  11719. tsDouble End-label Yes * Yes X Yes
  11720. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11721. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11722. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11723. * Only one reference allowed
  11724. }
  11725. hp1 := nil; { To prevent compiler warnings }
  11726. Optimizer.CopyUsedRegs(RegisterTracking);
  11727. fOptimizer := Optimizer;
  11728. fLabel := AFirstLabel;
  11729. CMOVScore := 0;
  11730. ConstCount := 0;
  11731. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11732. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11733. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11734. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11735. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11736. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11737. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11738. fInsertionPoint := p_initialjump;
  11739. fCondition := nil;
  11740. fInitialJump := p_initialjump;
  11741. fFirstMovBlock := p_initialmov;
  11742. fFirstMovBlockStop := nil;
  11743. fSecondJump := nil;
  11744. fSecondMovBlock := nil;
  11745. fSecondMovBlockStop := nil;
  11746. fMidLabel := nil;
  11747. fSecondJump := nil;
  11748. fSecondMovBlock := nil;
  11749. fEndLabel := nil;
  11750. fAllocationRange := nil;
  11751. { Assume it all goes horribly wrong! }
  11752. fState := tsInvalid;
  11753. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11754. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11755. 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
  11756. begin
  11757. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11758. for Count := 0 to 1 do
  11759. with taicpu(fCondition).oper[Count]^ do
  11760. case typ of
  11761. top_reg:
  11762. if getregtype(reg) = R_INTREGISTER then
  11763. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11764. top_ref:
  11765. begin
  11766. if
  11767. {$ifdef x86_64}
  11768. (ref^.base <> NR_RIP) and
  11769. {$endif x86_64}
  11770. (ref^.base <> NR_NO) then
  11771. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11772. if (ref^.index <> NR_NO) then
  11773. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11774. end
  11775. else
  11776. ;
  11777. end;
  11778. { When inserting instructions before hp_prev, try to insert them
  11779. before the allocation of the FLAGS register }
  11780. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11781. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11782. { If not found, set it equal to the condition so it's something sensible }
  11783. fInsertionPoint := fCondition;
  11784. { When dealing with a comparison against zero, take note of the
  11785. instruction before it to see if we can move instructions further
  11786. back in order to benefit PostPeepholeOptTestOr.
  11787. }
  11788. if (
  11789. (
  11790. (taicpu(fCondition).opcode = A_CMP) and
  11791. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11792. ) or
  11793. (
  11794. (taicpu(fCondition).opcode = A_TEST) and
  11795. (
  11796. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11797. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11798. )
  11799. )
  11800. ) and
  11801. Optimizer.GetLastInstruction(fCondition, hp1) then
  11802. begin
  11803. { These instructions set the zero flag if the result is zero }
  11804. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11805. begin
  11806. fInsertionPoint := hp1;
  11807. { Also mark all the registers in this previous instruction
  11808. as 'in use', even if they've just been deallocated }
  11809. for Count := 0 to 1 do
  11810. with taicpu(hp1).oper[Count]^ do
  11811. case typ of
  11812. top_reg:
  11813. if getregtype(reg) = R_INTREGISTER then
  11814. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11815. top_ref:
  11816. begin
  11817. if
  11818. {$ifdef x86_64}
  11819. (ref^.base <> NR_RIP) and
  11820. {$endif x86_64}
  11821. (ref^.base <> NR_NO) then
  11822. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11823. if (ref^.index <> NR_NO) then
  11824. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11825. end
  11826. else
  11827. ;
  11828. end;
  11829. end;
  11830. end;
  11831. end
  11832. else
  11833. fCondition := nil;
  11834. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11835. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11836. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11837. { If not found, set it equal to p so it's something sensible }
  11838. fInsertionPoint := hp1;
  11839. hp1 := p_initialmov;
  11840. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11841. Exit;
  11842. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11843. if (hp1.typ <> ait_label) then { should be on a jump }
  11844. begin
  11845. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11846. { Need a label afterwards }
  11847. Exit;
  11848. end
  11849. else
  11850. fMidLabel := hp1;
  11851. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11852. { Not the correct label }
  11853. fMidLabel := nil;
  11854. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11855. { If there's neither a 2nd jump nor correct label, then it's invalid
  11856. (see above table) }
  11857. Exit;
  11858. { Analyse the first block of MOVs more closely }
  11859. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11860. if Assigned(fSecondJump) then
  11861. begin
  11862. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11863. begin
  11864. fState := tsDetour
  11865. end
  11866. else
  11867. begin
  11868. { Need the correct mid-label for this one }
  11869. if not Assigned(fMidLabel) then
  11870. Exit;
  11871. fState := tsBranching;
  11872. end;
  11873. end
  11874. else
  11875. { No jump. but mid-label is present }
  11876. fState := tsSimple;
  11877. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11878. begin
  11879. { Invalid or too many instructions to be worthwhile }
  11880. fState := tsInvalid;
  11881. Exit;
  11882. end;
  11883. { check further for
  11884. jCC xxx
  11885. <several movs 1>
  11886. jmp yyy
  11887. xxx:
  11888. <several movs 2>
  11889. yyy:
  11890. etc.
  11891. }
  11892. if (fState = tsBranching) and
  11893. { Estimate for required savings for extra jump }
  11894. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11895. { Only one reference is allowed for double blocks }
  11896. (AFirstLabel.getrefs = 1) then
  11897. begin
  11898. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11899. fSecondMovBlock := hp1;
  11900. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11901. begin
  11902. EvaluateBranchingType;
  11903. Exit;
  11904. end;
  11905. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11906. if (hp1.typ <> ait_label) then { should be on a jump }
  11907. begin
  11908. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11909. begin
  11910. { Need a label afterwards }
  11911. EvaluateBranchingType;
  11912. Exit;
  11913. end;
  11914. end
  11915. else
  11916. fEndLabel := hp1;
  11917. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11918. { Second jump doesn't go to the end }
  11919. fEndLabel := nil;
  11920. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11921. begin
  11922. { If there's neither a 3rd jump nor correct end label, then it's
  11923. not a invalid double block, but is a valid single branching
  11924. block (see above table) }
  11925. EvaluateBranchingType;
  11926. Exit;
  11927. end;
  11928. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11929. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11930. { Invalid or too many instructions to be worthwhile }
  11931. Exit;
  11932. Inc(CMOVScore, Count);
  11933. if Assigned(fThirdJump) then
  11934. begin
  11935. if not Assigned(fSecondJump) then
  11936. fState := tsDoubleSecondBranching
  11937. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11938. fState := tsDoubleBranchSame
  11939. else
  11940. fState := tsDoubleBranchDifferent;
  11941. end
  11942. else
  11943. fState := tsDouble;
  11944. end;
  11945. if fState = tsBranching then
  11946. EvaluateBranchingType;
  11947. end;
  11948. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11949. new register to store the constant }
  11950. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11951. var
  11952. RegSize: TSubRegister;
  11953. CurrentVal: TCGInt;
  11954. ANewReg: TRegister;
  11955. X: ShortInt;
  11956. begin
  11957. Result := False;
  11958. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11959. Exit;
  11960. if ConstCount >= MAX_CMOV_REGISTERS then
  11961. { Arrays are full }
  11962. Exit;
  11963. { Remember that CMOV can't encode 8-bit registers }
  11964. case taicpu(p).opsize of
  11965. S_W:
  11966. RegSize := R_SUBW;
  11967. S_L:
  11968. RegSize := R_SUBD;
  11969. {$ifdef x86_64}
  11970. S_Q:
  11971. RegSize := R_SUBQ;
  11972. {$endif x86_64}
  11973. else
  11974. InternalError(2021100401);
  11975. end;
  11976. { See if the value has already been reserved for another CMOV instruction }
  11977. CurrentVal := taicpu(p).oper[0]^.val;
  11978. for X := 0 to ConstCount - 1 do
  11979. if ConstVals[X] = CurrentVal then
  11980. begin
  11981. ConstRegs[ConstCount] := ConstRegs[X];
  11982. ConstSizes[ConstCount] := RegSize;
  11983. ConstVals[ConstCount] := CurrentVal;
  11984. Inc(ConstCount);
  11985. Inc(Count);
  11986. Result := True;
  11987. Exit;
  11988. end;
  11989. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11990. if ANewReg = NR_NO then
  11991. { No free registers }
  11992. Exit;
  11993. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11994. up vying for the same register }
  11995. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11996. ConstRegs[ConstCount] := ANewReg;
  11997. ConstSizes[ConstCount] := RegSize;
  11998. ConstVals[ConstCount] := CurrentVal;
  11999. Inc(ConstCount);
  12000. Inc(Count);
  12001. Result := True;
  12002. end;
  12003. destructor TCMOVTracking.Done;
  12004. begin
  12005. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12006. end;
  12007. procedure TCMOVTracking.Process(out new_p: tai);
  12008. var
  12009. Count, Writes: LongInt;
  12010. RegMatch: Boolean;
  12011. hp1, hp_new: tai;
  12012. inverted_condition, condition: TAsmCond;
  12013. begin
  12014. if (fState in [tsInvalid, tsProcessed]) then
  12015. InternalError(2023110701);
  12016. { Repurpose RegisterTracking to mark registers that we've defined }
  12017. RegisterTracking[R_INTREGISTER].Clear;
  12018. Count := 0;
  12019. Writes := 0;
  12020. condition := taicpu(fInitialJump).condition;
  12021. inverted_condition := inverse_cond(condition);
  12022. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12023. doesn't get CMOVs in this case }
  12024. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12025. begin
  12026. { Include the jump in the flag tracking }
  12027. if Assigned(fThirdJump) then
  12028. begin
  12029. if (fState = tsDoubleBranchSame) then
  12030. begin
  12031. { Will be an unconditional jump, so track to the instruction before it }
  12032. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12033. InternalError(2023110710);
  12034. end
  12035. else
  12036. hp1 := fThirdJump;
  12037. end
  12038. else
  12039. hp1 := fSecondMovBlockStop;
  12040. end
  12041. else
  12042. begin
  12043. { Include a conditional jump in the flag tracking }
  12044. if Assigned(fSecondJump) then
  12045. begin
  12046. if (fState = tsDetour) then
  12047. begin
  12048. { Will be an unconditional jump, so track to the instruction before it }
  12049. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12050. InternalError(2023110711);
  12051. end
  12052. else
  12053. hp1 := fSecondJump;
  12054. end
  12055. else
  12056. hp1 := fFirstMovBlockStop;
  12057. end;
  12058. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12059. { Process the second set of MOVs first, because if a destination
  12060. register is shared between the first and second MOV sets, it is more
  12061. efficient to turn the first one into a MOV instruction and place it
  12062. before the CMP if possible, but we won't know which registers are
  12063. shared until we've processed at least one list, so we might as well
  12064. make it the second one since that won't be modified again. }
  12065. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12066. begin
  12067. hp1 := fSecondMovBlock;
  12068. repeat
  12069. if not Assigned(hp1) then
  12070. InternalError(2018062902);
  12071. if (hp1.typ = ait_instruction) then
  12072. begin
  12073. { Extra safeguard }
  12074. if (taicpu(hp1).opcode <> A_MOV) then
  12075. InternalError(2018062903);
  12076. { Note: tsDoubleBranchDifferent is essentially identical to
  12077. tsBranching and the 2nd block is best left largely
  12078. untouched, but we need to evaluate which registers the MOVs
  12079. write to in order to track what would be complementary CMOV
  12080. pairs that can be further optimised. [Kit] }
  12081. if fState <> tsDoubleBranchDifferent then
  12082. begin
  12083. if taicpu(hp1).oper[0]^.typ = top_const then
  12084. begin
  12085. RegMatch := False;
  12086. for Count := 0 to ConstCount - 1 do
  12087. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12088. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12089. begin
  12090. RegMatch := True;
  12091. { If it's in RegisterTracking, then this register
  12092. is being used more than once and hence has
  12093. already had its value defined (it gets added to
  12094. UsedRegs through AllocRegBetween below) }
  12095. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12096. begin
  12097. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12098. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12099. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12100. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12101. ConstMovs[Count] := hp_new;
  12102. end
  12103. else
  12104. { We just need an instruction between hp_prev and hp1
  12105. where we know the register is marked as in use }
  12106. hp_new := fSecondMovBlock;
  12107. { Keep track of largest write for this register so it can be optimised later }
  12108. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12109. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12110. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12111. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12112. Break;
  12113. end;
  12114. if not RegMatch then
  12115. InternalError(2021100411);
  12116. end;
  12117. taicpu(hp1).opcode := A_CMOVcc;
  12118. taicpu(hp1).condition := condition;
  12119. end;
  12120. { Store these writes to search for duplicates later on }
  12121. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12122. Inc(Writes);
  12123. end;
  12124. fOptimizer.GetNextInstruction(hp1, hp1);
  12125. until (hp1 = fSecondMovBlockStop);
  12126. end;
  12127. { Now do the first set of MOVs }
  12128. hp1 := fFirstMovBlock;
  12129. repeat
  12130. if not Assigned(hp1) then
  12131. InternalError(2018062904);
  12132. if (hp1.typ = ait_instruction) then
  12133. begin
  12134. RegMatch := False;
  12135. { Extra safeguard }
  12136. if (taicpu(hp1).opcode <> A_MOV) then
  12137. InternalError(2018062905);
  12138. { Search through the RegWrites list to see if there are any
  12139. opposing CMOV pairs that write to the same register }
  12140. for Count := 0 to Writes - 1 do
  12141. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12142. begin
  12143. { We have a match. Keep this as a MOV }
  12144. { Move ahead in preparation }
  12145. fOptimizer.GetNextInstruction(hp1, hp1);
  12146. RegMatch := True;
  12147. Break;
  12148. end;
  12149. if RegMatch then
  12150. Continue;
  12151. if taicpu(hp1).oper[0]^.typ = top_const then
  12152. begin
  12153. for Count := 0 to ConstCount - 1 do
  12154. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12155. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12156. begin
  12157. RegMatch := True;
  12158. { If it's in RegisterTracking, then this register is
  12159. being used more than once and hence has already had
  12160. its value defined (it gets added to UsedRegs through
  12161. AllocRegBetween below) }
  12162. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12163. begin
  12164. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12165. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12166. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12167. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12168. ConstMovs[Count] := hp_new;
  12169. end
  12170. else
  12171. { We just need an instruction between hp_prev and hp1
  12172. where we know the register is marked as in use }
  12173. hp_new := fFirstMovBlock;
  12174. { Keep track of largest write for this register so it can be optimised later }
  12175. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12176. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12177. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12178. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12179. Break;
  12180. end;
  12181. if not RegMatch then
  12182. InternalError(2021100412);
  12183. end;
  12184. taicpu(hp1).opcode := A_CMOVcc;
  12185. taicpu(hp1).condition := inverted_condition;
  12186. if (fState = tsDoubleBranchDifferent) then
  12187. begin
  12188. { Store these writes to search for duplicates later on }
  12189. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12190. Inc(Writes);
  12191. end;
  12192. end;
  12193. fOptimizer.GetNextInstruction(hp1, hp1);
  12194. until (hp1 = fFirstMovBlockStop);
  12195. { Update initialisation MOVs to the smallest possible size }
  12196. for Count := 0 to ConstCount - 1 do
  12197. if Assigned(ConstMovs[Count]) then
  12198. begin
  12199. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12200. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12201. end;
  12202. case fState of
  12203. tsSimple:
  12204. begin
  12205. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12206. { No branch to delete }
  12207. end;
  12208. tsDetour:
  12209. begin
  12210. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12211. { Preserve jump }
  12212. end;
  12213. tsBranching, tsDoubleBranchDifferent:
  12214. begin
  12215. if (fState = tsBranching) then
  12216. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12217. else
  12218. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12219. taicpu(fSecondJump).opcode := A_JCC;
  12220. taicpu(fSecondJump).condition := inverted_condition;
  12221. end;
  12222. tsDouble, tsDoubleBranchSame:
  12223. begin
  12224. if (fState = tsDouble) then
  12225. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12226. else
  12227. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12228. { Delete second jump }
  12229. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12230. fOptimizer.RemoveInstruction(fSecondJump);
  12231. end;
  12232. tsDoubleSecondBranching:
  12233. begin
  12234. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12235. { Delete second jump, preserve third jump as conditional }
  12236. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12237. fOptimizer.RemoveInstruction(fSecondJump);
  12238. taicpu(fThirdJump).opcode := A_JCC;
  12239. taicpu(fThirdJump).condition := condition;
  12240. end;
  12241. else
  12242. InternalError(2023110720);
  12243. end;
  12244. { Now we can safely decrement the reference count }
  12245. tasmlabel(fLabel).decrefs;
  12246. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12247. { Remove the original jump }
  12248. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12249. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12250. fState := tsProcessed;
  12251. end;
  12252. {$endif 8086}
  12253. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12254. var
  12255. hp1,hp2: tai;
  12256. carryadd_opcode : TAsmOp;
  12257. symbol: TAsmSymbol;
  12258. increg, tmpreg: TRegister;
  12259. {$ifndef i8086}
  12260. CMOVTracking: PCMOVTracking;
  12261. hp3,hp4,hp5: tai;
  12262. {$endif i8086}
  12263. TempBool: Boolean;
  12264. begin
  12265. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12266. DoJumpOptimizations(p, TempBool) then
  12267. Exit(True);
  12268. result:=false;
  12269. if GetNextInstruction(p,hp1) then
  12270. begin
  12271. if (hp1.typ=ait_label) then
  12272. begin
  12273. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12274. Exit;
  12275. end
  12276. else if (hp1.typ<>ait_instruction) then
  12277. Exit;
  12278. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12279. if (
  12280. (
  12281. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12282. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12283. (Taicpu(hp1).oper[0]^.val=1)
  12284. ) or
  12285. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12286. ) and
  12287. GetNextInstruction(hp1,hp2) and
  12288. (hp2.typ = ait_label) and
  12289. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12290. { jb @@1 cmc
  12291. inc/dec operand --> adc/sbb operand,0
  12292. @@1:
  12293. ... and ...
  12294. jnb @@1
  12295. inc/dec operand --> adc/sbb operand,0
  12296. @@1: }
  12297. begin
  12298. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12299. begin
  12300. case taicpu(hp1).opcode of
  12301. A_INC,
  12302. A_ADD:
  12303. carryadd_opcode:=A_ADC;
  12304. A_DEC,
  12305. A_SUB:
  12306. carryadd_opcode:=A_SBB;
  12307. else
  12308. InternalError(2021011001);
  12309. end;
  12310. Taicpu(p).clearop(0);
  12311. Taicpu(p).ops:=0;
  12312. Taicpu(p).is_jmp:=false;
  12313. Taicpu(p).opcode:=A_CMC;
  12314. Taicpu(p).condition:=C_NONE;
  12315. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12316. Taicpu(hp1).ops:=2;
  12317. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12318. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12319. else
  12320. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12321. Taicpu(hp1).loadconst(0,0);
  12322. Taicpu(hp1).opcode:=carryadd_opcode;
  12323. result:=true;
  12324. exit;
  12325. end
  12326. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12327. begin
  12328. case taicpu(hp1).opcode of
  12329. A_INC,
  12330. A_ADD:
  12331. carryadd_opcode:=A_ADC;
  12332. A_DEC,
  12333. A_SUB:
  12334. carryadd_opcode:=A_SBB;
  12335. else
  12336. InternalError(2021011002);
  12337. end;
  12338. Taicpu(hp1).ops:=2;
  12339. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12340. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12341. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12342. else
  12343. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12344. Taicpu(hp1).loadconst(0,0);
  12345. Taicpu(hp1).opcode:=carryadd_opcode;
  12346. RemoveCurrentP(p, hp1);
  12347. result:=true;
  12348. exit;
  12349. end
  12350. {
  12351. jcc @@1 setcc tmpreg
  12352. inc/dec/add/sub operand -> (movzx tmpreg)
  12353. @@1: add/sub tmpreg,operand
  12354. While this increases code size slightly, it makes the code much faster if the
  12355. jump is unpredictable
  12356. }
  12357. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12358. begin
  12359. { search for an available register which is volatile }
  12360. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12361. if increg <> NR_NO then
  12362. begin
  12363. { We don't need to check if tmpreg is in hp1 or not, because
  12364. it will be marked as in use at p (if not, this is
  12365. indictive of a compiler bug). }
  12366. TAsmLabel(symbol).decrefs;
  12367. Taicpu(p).clearop(0);
  12368. Taicpu(p).ops:=1;
  12369. Taicpu(p).is_jmp:=false;
  12370. Taicpu(p).opcode:=A_SETcc;
  12371. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12372. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12373. Taicpu(p).loadreg(0,increg);
  12374. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12375. begin
  12376. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12377. R_SUBW:
  12378. begin
  12379. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12380. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12381. end;
  12382. R_SUBD:
  12383. begin
  12384. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12385. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12386. end;
  12387. {$ifdef x86_64}
  12388. R_SUBQ:
  12389. begin
  12390. { MOVZX doesn't have a 64-bit variant, because
  12391. the 32-bit version implicitly zeroes the
  12392. upper 32-bits of the destination register }
  12393. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12394. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12395. setsubreg(tmpreg, R_SUBQ);
  12396. end;
  12397. {$endif x86_64}
  12398. else
  12399. Internalerror(2020030601);
  12400. end;
  12401. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12402. asml.InsertAfter(hp2,p);
  12403. end
  12404. else
  12405. tmpreg := increg;
  12406. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12407. begin
  12408. Taicpu(hp1).ops:=2;
  12409. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12410. end;
  12411. Taicpu(hp1).loadreg(0,tmpreg);
  12412. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12413. Result := True;
  12414. { p is no longer a Jcc instruction, so exit }
  12415. Exit;
  12416. end;
  12417. end;
  12418. end;
  12419. { Detect the following:
  12420. jmp<cond> @Lbl1
  12421. jmp @Lbl2
  12422. ...
  12423. @Lbl1:
  12424. ret
  12425. Change to:
  12426. jmp<inv_cond> @Lbl2
  12427. ret
  12428. }
  12429. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12430. begin
  12431. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12432. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12433. MatchInstruction(hp2,A_RET,[S_NO]) then
  12434. begin
  12435. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12436. { Change label address to that of the unconditional jump }
  12437. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12438. TAsmLabel(symbol).DecRefs;
  12439. taicpu(hp1).opcode := A_RET;
  12440. taicpu(hp1).is_jmp := false;
  12441. taicpu(hp1).ops := taicpu(hp2).ops;
  12442. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12443. case taicpu(hp2).ops of
  12444. 0:
  12445. taicpu(hp1).clearop(0);
  12446. 1:
  12447. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12448. else
  12449. internalerror(2016041302);
  12450. end;
  12451. end;
  12452. {$ifndef i8086}
  12453. end
  12454. {
  12455. convert
  12456. j<c> .L1
  12457. mov 1,reg
  12458. jmp .L2
  12459. .L1
  12460. mov 0,reg
  12461. .L2
  12462. into
  12463. mov 0,reg
  12464. set<not(c)> reg
  12465. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12466. would destroy the flag contents
  12467. }
  12468. else if MatchInstruction(hp1,A_MOV,[]) and
  12469. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12470. {$ifdef i386}
  12471. (
  12472. { Under i386, ESI, EDI, EBP and ESP
  12473. don't have an 8-bit representation }
  12474. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12475. ) and
  12476. {$endif i386}
  12477. (taicpu(hp1).oper[0]^.val=1) and
  12478. GetNextInstruction(hp1,hp2) and
  12479. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12480. GetNextInstruction(hp2,hp3) and
  12481. (hp3.typ=ait_label) and
  12482. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12483. (tai_label(hp3).labsym.getrefs=1) and
  12484. GetNextInstruction(hp3,hp4) and
  12485. MatchInstruction(hp4,A_MOV,[]) and
  12486. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12487. (taicpu(hp4).oper[0]^.val=0) and
  12488. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12489. GetNextInstruction(hp4,hp5) and
  12490. (hp5.typ=ait_label) and
  12491. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12492. (tai_label(hp5).labsym.getrefs=1) then
  12493. begin
  12494. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12495. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12496. { remove last label }
  12497. RemoveInstruction(hp5);
  12498. { remove second label }
  12499. RemoveInstruction(hp3);
  12500. { remove jmp }
  12501. RemoveInstruction(hp2);
  12502. if taicpu(hp1).opsize=S_B then
  12503. RemoveInstruction(hp1)
  12504. else
  12505. taicpu(hp1).loadconst(0,0);
  12506. taicpu(hp4).opcode:=A_SETcc;
  12507. taicpu(hp4).opsize:=S_B;
  12508. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12509. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12510. taicpu(hp4).opercnt:=1;
  12511. taicpu(hp4).ops:=1;
  12512. taicpu(hp4).freeop(1);
  12513. RemoveCurrentP(p);
  12514. Result:=true;
  12515. exit;
  12516. end
  12517. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12518. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12519. begin
  12520. { check for
  12521. jCC xxx
  12522. <several movs>
  12523. xxx:
  12524. Also spot:
  12525. Jcc xxx
  12526. <several movs>
  12527. jmp xxx
  12528. Change to:
  12529. <several cmovs with inverted condition>
  12530. jmp xxx (only for the 2nd case)
  12531. }
  12532. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12533. if CMOVTracking^.State <> tsInvalid then
  12534. begin
  12535. CMovTracking^.Process(p);
  12536. Result := True;
  12537. end;
  12538. CMOVTracking^.Done;
  12539. {$endif i8086}
  12540. end;
  12541. end;
  12542. end;
  12543. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12544. var
  12545. hp1,hp2,hp3: tai;
  12546. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12547. NewSize: TOpSize;
  12548. NewRegSize: TSubRegister;
  12549. Limit: TCgInt;
  12550. SwapOper: POper;
  12551. begin
  12552. result:=false;
  12553. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12554. GetNextInstruction(p,hp1) and
  12555. (hp1.typ = ait_instruction);
  12556. if reg_and_hp1_is_instr and
  12557. (
  12558. (taicpu(hp1).opcode <> A_LEA) or
  12559. { If the LEA instruction can be converted into an arithmetic instruction,
  12560. it may be possible to then fold it. }
  12561. (
  12562. { If the flags register is in use, don't change the instruction
  12563. to an ADD otherwise this will scramble the flags. [Kit] }
  12564. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12565. ConvertLEA(taicpu(hp1))
  12566. )
  12567. ) and
  12568. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12569. GetNextInstruction(hp1,hp2) and
  12570. MatchInstruction(hp2,A_MOV,[]) and
  12571. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12572. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12573. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12574. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12575. {$ifdef i386}
  12576. { not all registers have byte size sub registers on i386 }
  12577. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12578. {$endif i386}
  12579. (((taicpu(hp1).ops=2) and
  12580. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12581. ((taicpu(hp1).ops=1) and
  12582. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12583. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12584. begin
  12585. { change movsX/movzX reg/ref, reg2
  12586. add/sub/or/... reg3/$const, reg2
  12587. mov reg2 reg/ref
  12588. to add/sub/or/... reg3/$const, reg/ref }
  12589. { by example:
  12590. movswl %si,%eax movswl %si,%eax p
  12591. decl %eax addl %edx,%eax hp1
  12592. movw %ax,%si movw %ax,%si hp2
  12593. ->
  12594. movswl %si,%eax movswl %si,%eax p
  12595. decw %eax addw %edx,%eax hp1
  12596. movw %ax,%si movw %ax,%si hp2
  12597. }
  12598. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12599. {
  12600. ->
  12601. movswl %si,%eax movswl %si,%eax p
  12602. decw %si addw %dx,%si hp1
  12603. movw %ax,%si movw %ax,%si hp2
  12604. }
  12605. case taicpu(hp1).ops of
  12606. 1:
  12607. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12608. 2:
  12609. begin
  12610. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12611. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12612. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12613. end;
  12614. else
  12615. internalerror(2008042702);
  12616. end;
  12617. {
  12618. ->
  12619. decw %si addw %dx,%si p
  12620. }
  12621. DebugMsg(SPeepholeOptimization + 'var3',p);
  12622. RemoveCurrentP(p, hp1);
  12623. RemoveInstruction(hp2);
  12624. Result := True;
  12625. Exit;
  12626. end;
  12627. if reg_and_hp1_is_instr and
  12628. (taicpu(hp1).opcode = A_MOV) and
  12629. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12630. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12631. {$ifdef x86_64}
  12632. { check for implicit extension to 64 bit }
  12633. or
  12634. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12635. (taicpu(hp1).opsize=S_Q) and
  12636. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12637. )
  12638. {$endif x86_64}
  12639. )
  12640. then
  12641. begin
  12642. { change
  12643. movx %reg1,%reg2
  12644. mov %reg2,%reg3
  12645. dealloc %reg2
  12646. into
  12647. movx %reg,%reg3
  12648. }
  12649. TransferUsedRegs(TmpUsedRegs);
  12650. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12651. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12652. begin
  12653. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12654. {$ifdef x86_64}
  12655. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12656. (taicpu(hp1).opsize=S_Q) then
  12657. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12658. else
  12659. {$endif x86_64}
  12660. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12661. RemoveInstruction(hp1);
  12662. Result := True;
  12663. Exit;
  12664. end;
  12665. end;
  12666. if reg_and_hp1_is_instr and
  12667. ((taicpu(hp1).opcode=A_MOV) or
  12668. (taicpu(hp1).opcode=A_ADD) or
  12669. (taicpu(hp1).opcode=A_SUB) or
  12670. (taicpu(hp1).opcode=A_CMP) or
  12671. (taicpu(hp1).opcode=A_OR) or
  12672. (taicpu(hp1).opcode=A_XOR) or
  12673. (taicpu(hp1).opcode=A_AND)
  12674. ) and
  12675. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12676. begin
  12677. AndTest := (taicpu(hp1).opcode=A_AND) and
  12678. GetNextInstruction(hp1, hp2) and
  12679. (hp2.typ = ait_instruction) and
  12680. (
  12681. (
  12682. (taicpu(hp2).opcode=A_TEST) and
  12683. (
  12684. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12685. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12686. (
  12687. { If the AND and TEST instructions share a constant, this is also valid }
  12688. (taicpu(hp1).oper[0]^.typ = top_const) and
  12689. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12690. )
  12691. ) and
  12692. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12693. ) or
  12694. (
  12695. (taicpu(hp2).opcode=A_CMP) and
  12696. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12697. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12698. )
  12699. );
  12700. { change
  12701. movx (oper),%reg2
  12702. and $x,%reg2
  12703. test %reg2,%reg2
  12704. dealloc %reg2
  12705. into
  12706. op %reg1,%reg3
  12707. if the second op accesses only the bits stored in reg1
  12708. }
  12709. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12710. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12711. (taicpu(hp1).oper[0]^.typ = top_const) and
  12712. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12713. AndTest then
  12714. begin
  12715. { Check if the AND constant is in range }
  12716. case taicpu(p).opsize of
  12717. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12718. begin
  12719. NewSize := S_B;
  12720. Limit := $FF;
  12721. end;
  12722. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12723. begin
  12724. NewSize := S_W;
  12725. Limit := $FFFF;
  12726. end;
  12727. {$ifdef x86_64}
  12728. S_LQ:
  12729. begin
  12730. NewSize := S_L;
  12731. Limit := $FFFFFFFF;
  12732. end;
  12733. {$endif x86_64}
  12734. else
  12735. InternalError(2021120303);
  12736. end;
  12737. if (
  12738. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12739. { Check for negative operands }
  12740. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12741. ) and
  12742. GetNextInstruction(hp2,hp3) and
  12743. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12744. (taicpu(hp3).condition in [C_E,C_NE]) then
  12745. begin
  12746. TransferUsedRegs(TmpUsedRegs);
  12747. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12748. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12749. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12750. begin
  12751. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12752. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12753. taicpu(hp1).opcode := A_TEST;
  12754. taicpu(hp1).opsize := NewSize;
  12755. RemoveInstruction(hp2);
  12756. RemoveCurrentP(p, hp1);
  12757. Result:=true;
  12758. exit;
  12759. end;
  12760. end;
  12761. end;
  12762. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12763. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12764. (taicpu(hp1).opsize=S_B)) or
  12765. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12766. (taicpu(hp1).opsize=S_W))
  12767. {$ifdef x86_64}
  12768. or ((taicpu(p).opsize=S_LQ) and
  12769. (taicpu(hp1).opsize=S_L))
  12770. {$endif x86_64}
  12771. ) and
  12772. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12773. begin
  12774. { change
  12775. movx %reg1,%reg2
  12776. op %reg2,%reg3
  12777. dealloc %reg2
  12778. into
  12779. op %reg1,%reg3
  12780. if the second op accesses only the bits stored in reg1
  12781. }
  12782. TransferUsedRegs(TmpUsedRegs);
  12783. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12784. if AndTest then
  12785. begin
  12786. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12787. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12788. end
  12789. else
  12790. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12791. if not RegUsed then
  12792. begin
  12793. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12794. if taicpu(p).oper[0]^.typ=top_reg then
  12795. begin
  12796. case taicpu(hp1).opsize of
  12797. S_B:
  12798. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12799. S_W:
  12800. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12801. S_L:
  12802. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12803. else
  12804. Internalerror(2020102301);
  12805. end;
  12806. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12807. end
  12808. else
  12809. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12810. RemoveCurrentP(p);
  12811. if AndTest then
  12812. RemoveInstruction(hp2);
  12813. result:=true;
  12814. exit;
  12815. end;
  12816. end
  12817. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12818. (
  12819. { Bitwise operations only }
  12820. (taicpu(hp1).opcode=A_AND) or
  12821. (taicpu(hp1).opcode=A_TEST) or
  12822. (
  12823. (taicpu(hp1).oper[0]^.typ = top_const) and
  12824. (
  12825. (taicpu(hp1).opcode=A_OR) or
  12826. (taicpu(hp1).opcode=A_XOR)
  12827. )
  12828. )
  12829. ) and
  12830. (
  12831. (taicpu(hp1).oper[0]^.typ = top_const) or
  12832. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12833. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12834. ) then
  12835. begin
  12836. { change
  12837. movx %reg2,%reg2
  12838. op const,%reg2
  12839. into
  12840. op const,%reg2 (smaller version)
  12841. movx %reg2,%reg2
  12842. also change
  12843. movx %reg1,%reg2
  12844. and/test (oper),%reg2
  12845. dealloc %reg2
  12846. into
  12847. and/test (oper),%reg1
  12848. }
  12849. case taicpu(p).opsize of
  12850. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12851. begin
  12852. NewSize := S_B;
  12853. NewRegSize := R_SUBL;
  12854. Limit := $FF;
  12855. end;
  12856. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12857. begin
  12858. NewSize := S_W;
  12859. NewRegSize := R_SUBW;
  12860. Limit := $FFFF;
  12861. end;
  12862. {$ifdef x86_64}
  12863. S_LQ:
  12864. begin
  12865. NewSize := S_L;
  12866. NewRegSize := R_SUBD;
  12867. Limit := $FFFFFFFF;
  12868. end;
  12869. {$endif x86_64}
  12870. else
  12871. Internalerror(2021120302);
  12872. end;
  12873. TransferUsedRegs(TmpUsedRegs);
  12874. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12875. if AndTest then
  12876. begin
  12877. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12878. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12879. end
  12880. else
  12881. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12882. if
  12883. (
  12884. (taicpu(p).opcode = A_MOVZX) and
  12885. (
  12886. (taicpu(hp1).opcode=A_AND) or
  12887. (taicpu(hp1).opcode=A_TEST)
  12888. ) and
  12889. not (
  12890. { If both are references, then the final instruction will have
  12891. both operands as references, which is not allowed }
  12892. (taicpu(p).oper[0]^.typ = top_ref) and
  12893. (taicpu(hp1).oper[0]^.typ = top_ref)
  12894. ) and
  12895. not RegUsed
  12896. ) or
  12897. (
  12898. (
  12899. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12900. not RegUsed
  12901. ) and
  12902. (taicpu(p).oper[0]^.typ = top_reg) and
  12903. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12904. (taicpu(hp1).oper[0]^.typ = top_const) and
  12905. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12906. ) then
  12907. begin
  12908. {$if defined(i386) or defined(i8086)}
  12909. { If the target size is 8-bit, make sure we can actually encode it }
  12910. 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
  12911. Exit;
  12912. {$endif i386 or i8086}
  12913. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12914. taicpu(hp1).opsize := NewSize;
  12915. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12916. if AndTest then
  12917. begin
  12918. RemoveInstruction(hp2);
  12919. if not RegUsed then
  12920. begin
  12921. taicpu(hp1).opcode := A_TEST;
  12922. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12923. begin
  12924. { Make sure the reference is the second operand }
  12925. SwapOper := taicpu(hp1).oper[0];
  12926. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12927. taicpu(hp1).oper[1] := SwapOper;
  12928. end;
  12929. end;
  12930. end;
  12931. case taicpu(hp1).oper[0]^.typ of
  12932. top_reg:
  12933. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12934. top_const:
  12935. { For the AND/TEST case }
  12936. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12937. else
  12938. ;
  12939. end;
  12940. if RegUsed then
  12941. begin
  12942. AsmL.Remove(p);
  12943. AsmL.InsertAfter(p, hp1);
  12944. p := hp1;
  12945. end
  12946. else
  12947. RemoveCurrentP(p, hp1);
  12948. result:=true;
  12949. exit;
  12950. end;
  12951. end;
  12952. end;
  12953. if reg_and_hp1_is_instr and
  12954. (taicpu(p).oper[0]^.typ = top_reg) and
  12955. (
  12956. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12957. ) and
  12958. (taicpu(hp1).oper[0]^.typ = top_const) and
  12959. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12960. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12961. { Minimum shift value allowed is the bit difference between the sizes }
  12962. (taicpu(hp1).oper[0]^.val >=
  12963. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12964. 8 * (
  12965. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12966. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12967. )
  12968. ) then
  12969. begin
  12970. { For:
  12971. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12972. shl/sal ##, %reg1
  12973. Remove the movsx/movzx instruction if the shift overwrites the
  12974. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12975. }
  12976. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12977. RemoveCurrentP(p, hp1);
  12978. Result := True;
  12979. Exit;
  12980. end
  12981. else if reg_and_hp1_is_instr and
  12982. (taicpu(p).oper[0]^.typ = top_reg) and
  12983. (
  12984. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12985. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12986. ) and
  12987. (taicpu(hp1).oper[0]^.typ = top_const) and
  12988. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12989. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12990. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12991. (taicpu(hp1).oper[0]^.val <
  12992. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12993. 8 * (
  12994. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12995. )
  12996. ) then
  12997. begin
  12998. { For:
  12999. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13000. sar ##, %reg1 shr ##, %reg1
  13001. Move the shift to before the movx instruction if the shift value
  13002. is not too large.
  13003. }
  13004. asml.Remove(hp1);
  13005. asml.InsertBefore(hp1, p);
  13006. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13007. case taicpu(p).opsize of
  13008. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13009. taicpu(hp1).opsize := S_B;
  13010. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13011. taicpu(hp1).opsize := S_W;
  13012. {$ifdef x86_64}
  13013. S_LQ:
  13014. taicpu(hp1).opsize := S_L;
  13015. {$endif}
  13016. else
  13017. InternalError(2020112401);
  13018. end;
  13019. if (taicpu(hp1).opcode = A_SHR) then
  13020. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13021. else
  13022. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13023. Result := True;
  13024. end;
  13025. if reg_and_hp1_is_instr and
  13026. (taicpu(p).oper[0]^.typ = top_reg) and
  13027. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13028. (
  13029. (taicpu(hp1).opcode = taicpu(p).opcode)
  13030. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13031. {$ifdef x86_64}
  13032. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13033. {$endif x86_64}
  13034. ) then
  13035. begin
  13036. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13037. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13038. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13039. begin
  13040. {
  13041. For example:
  13042. movzbw %al,%ax
  13043. movzwl %ax,%eax
  13044. Compress into:
  13045. movzbl %al,%eax
  13046. }
  13047. RegUsed := False;
  13048. case taicpu(p).opsize of
  13049. S_BW:
  13050. case taicpu(hp1).opsize of
  13051. S_WL:
  13052. begin
  13053. taicpu(p).opsize := S_BL;
  13054. RegUsed := True;
  13055. end;
  13056. {$ifdef x86_64}
  13057. S_WQ:
  13058. begin
  13059. if taicpu(p).opcode = A_MOVZX then
  13060. begin
  13061. taicpu(p).opsize := S_BL;
  13062. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13063. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13064. end
  13065. else
  13066. taicpu(p).opsize := S_BQ;
  13067. RegUsed := True;
  13068. end;
  13069. {$endif x86_64}
  13070. else
  13071. ;
  13072. end;
  13073. {$ifdef x86_64}
  13074. S_BL:
  13075. case taicpu(hp1).opsize of
  13076. S_LQ:
  13077. begin
  13078. if taicpu(p).opcode = A_MOVZX then
  13079. begin
  13080. taicpu(p).opsize := S_BL;
  13081. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13082. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13083. end
  13084. else
  13085. taicpu(p).opsize := S_BQ;
  13086. RegUsed := True;
  13087. end;
  13088. else
  13089. ;
  13090. end;
  13091. S_WL:
  13092. case taicpu(hp1).opsize of
  13093. S_LQ:
  13094. begin
  13095. if taicpu(p).opcode = A_MOVZX then
  13096. begin
  13097. taicpu(p).opsize := S_WL;
  13098. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13099. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13100. end
  13101. else
  13102. taicpu(p).opsize := S_WQ;
  13103. RegUsed := True;
  13104. end;
  13105. else
  13106. ;
  13107. end;
  13108. {$endif x86_64}
  13109. else
  13110. ;
  13111. end;
  13112. if RegUsed then
  13113. begin
  13114. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13115. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13116. RemoveInstruction(hp1);
  13117. Result := True;
  13118. Exit;
  13119. end;
  13120. end;
  13121. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13122. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13123. GetNextInstruction(hp1, hp2) and
  13124. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13125. (
  13126. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13127. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13128. {$ifdef x86_64}
  13129. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13130. {$endif x86_64}
  13131. ) and
  13132. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13133. (
  13134. (
  13135. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13136. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13137. ) or
  13138. (
  13139. { Only allow the operands in reverse order for TEST instructions }
  13140. (taicpu(hp2).opcode = A_TEST) and
  13141. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13142. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13143. )
  13144. ) then
  13145. begin
  13146. {
  13147. For example:
  13148. movzbl %al,%eax
  13149. movzbl (ref),%edx
  13150. andl %edx,%eax
  13151. (%edx deallocated)
  13152. Change to:
  13153. andb (ref),%al
  13154. movzbl %al,%eax
  13155. Rules are:
  13156. - First two instructions have the same opcode and opsize
  13157. - First instruction's operands are the same super-register
  13158. - Second instruction operates on a different register
  13159. - Third instruction is AND, OR, XOR or TEST
  13160. - Third instruction's operands are the destination registers of the first two instructions
  13161. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13162. - Second instruction's destination register is deallocated afterwards
  13163. }
  13164. TransferUsedRegs(TmpUsedRegs);
  13165. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13166. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13167. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13168. begin
  13169. case taicpu(p).opsize of
  13170. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13171. NewSize := S_B;
  13172. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13173. NewSize := S_W;
  13174. {$ifdef x86_64}
  13175. S_LQ:
  13176. NewSize := S_L;
  13177. {$endif x86_64}
  13178. else
  13179. InternalError(2021120301);
  13180. end;
  13181. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13182. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13183. taicpu(hp2).opsize := NewSize;
  13184. RemoveInstruction(hp1);
  13185. { With TEST, it's best to keep the MOVX instruction at the top }
  13186. if (taicpu(hp2).opcode <> A_TEST) then
  13187. begin
  13188. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13189. asml.Remove(p);
  13190. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13191. asml.InsertAfter(p, hp2);
  13192. p := hp2;
  13193. end
  13194. else
  13195. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13196. Result := True;
  13197. Exit;
  13198. end;
  13199. end;
  13200. end;
  13201. if taicpu(p).opcode=A_MOVZX then
  13202. begin
  13203. { removes superfluous And's after movzx's }
  13204. if reg_and_hp1_is_instr and
  13205. (taicpu(hp1).opcode = A_AND) and
  13206. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13207. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13208. {$ifdef x86_64}
  13209. { check for implicit extension to 64 bit }
  13210. or
  13211. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13212. (taicpu(hp1).opsize=S_Q) and
  13213. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13214. )
  13215. {$endif x86_64}
  13216. )
  13217. then
  13218. begin
  13219. case taicpu(p).opsize Of
  13220. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13221. if (taicpu(hp1).oper[0]^.val = $ff) then
  13222. begin
  13223. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13224. RemoveInstruction(hp1);
  13225. Result:=true;
  13226. exit;
  13227. end;
  13228. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13229. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13230. begin
  13231. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13232. RemoveInstruction(hp1);
  13233. Result:=true;
  13234. exit;
  13235. end;
  13236. {$ifdef x86_64}
  13237. S_LQ:
  13238. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13239. begin
  13240. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13241. RemoveInstruction(hp1);
  13242. Result:=true;
  13243. exit;
  13244. end;
  13245. {$endif x86_64}
  13246. else
  13247. ;
  13248. end;
  13249. { we cannot get rid of the and, but can we get rid of the movz ?}
  13250. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13251. begin
  13252. case taicpu(p).opsize Of
  13253. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13254. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13255. begin
  13256. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13257. RemoveCurrentP(p,hp1);
  13258. Result:=true;
  13259. exit;
  13260. end;
  13261. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13262. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13263. begin
  13264. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13265. RemoveCurrentP(p,hp1);
  13266. Result:=true;
  13267. exit;
  13268. end;
  13269. {$ifdef x86_64}
  13270. S_LQ:
  13271. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13272. begin
  13273. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13274. RemoveCurrentP(p,hp1);
  13275. Result:=true;
  13276. exit;
  13277. end;
  13278. {$endif x86_64}
  13279. else
  13280. ;
  13281. end;
  13282. end;
  13283. end;
  13284. { changes some movzx constructs to faster synonyms (all examples
  13285. are given with eax/ax, but are also valid for other registers)}
  13286. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13287. begin
  13288. case taicpu(p).opsize of
  13289. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13290. (the machine code is equivalent to movzbl %al,%eax), but the
  13291. code generator still generates that assembler instruction and
  13292. it is silently converted. This should probably be checked.
  13293. [Kit] }
  13294. S_BW:
  13295. begin
  13296. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13297. (
  13298. not IsMOVZXAcceptable
  13299. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13300. or (
  13301. (cs_opt_size in current_settings.optimizerswitches) and
  13302. (taicpu(p).oper[1]^.reg = NR_AX)
  13303. )
  13304. ) then
  13305. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13306. begin
  13307. DebugMsg(SPeepholeOptimization + 'var7',p);
  13308. taicpu(p).opcode := A_AND;
  13309. taicpu(p).changeopsize(S_W);
  13310. taicpu(p).loadConst(0,$ff);
  13311. Result := True;
  13312. end
  13313. else if not IsMOVZXAcceptable and
  13314. GetNextInstruction(p, hp1) and
  13315. (tai(hp1).typ = ait_instruction) and
  13316. (taicpu(hp1).opcode = A_AND) and
  13317. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13318. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13319. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13320. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13321. begin
  13322. DebugMsg(SPeepholeOptimization + 'var8',p);
  13323. taicpu(p).opcode := A_MOV;
  13324. taicpu(p).changeopsize(S_W);
  13325. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13326. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13327. Result := True;
  13328. end;
  13329. end;
  13330. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13331. S_BL:
  13332. if not IsMOVZXAcceptable then
  13333. begin
  13334. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13335. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13336. begin
  13337. DebugMsg(SPeepholeOptimization + 'var9',p);
  13338. taicpu(p).opcode := A_AND;
  13339. taicpu(p).changeopsize(S_L);
  13340. taicpu(p).loadConst(0,$ff);
  13341. Result := True;
  13342. end
  13343. else if GetNextInstruction(p, hp1) and
  13344. (tai(hp1).typ = ait_instruction) and
  13345. (taicpu(hp1).opcode = A_AND) and
  13346. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13347. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13348. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13349. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13350. begin
  13351. DebugMsg(SPeepholeOptimization + 'var10',p);
  13352. taicpu(p).opcode := A_MOV;
  13353. taicpu(p).changeopsize(S_L);
  13354. { do not use R_SUBWHOLE
  13355. as movl %rdx,%eax
  13356. is invalid in assembler PM }
  13357. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13358. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13359. Result := True;
  13360. end;
  13361. end;
  13362. {$endif i8086}
  13363. S_WL:
  13364. if not IsMOVZXAcceptable then
  13365. begin
  13366. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13367. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13368. begin
  13369. DebugMsg(SPeepholeOptimization + 'var11',p);
  13370. taicpu(p).opcode := A_AND;
  13371. taicpu(p).changeopsize(S_L);
  13372. taicpu(p).loadConst(0,$ffff);
  13373. Result := True;
  13374. end
  13375. else if GetNextInstruction(p, hp1) and
  13376. (tai(hp1).typ = ait_instruction) and
  13377. (taicpu(hp1).opcode = A_AND) and
  13378. (taicpu(hp1).oper[0]^.typ = top_const) and
  13379. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13380. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13381. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13382. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13383. begin
  13384. DebugMsg(SPeepholeOptimization + 'var12',p);
  13385. taicpu(p).opcode := A_MOV;
  13386. taicpu(p).changeopsize(S_L);
  13387. { do not use R_SUBWHOLE
  13388. as movl %rdx,%eax
  13389. is invalid in assembler PM }
  13390. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13391. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13392. Result := True;
  13393. end;
  13394. end;
  13395. else
  13396. InternalError(2017050705);
  13397. end;
  13398. end
  13399. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13400. begin
  13401. if GetNextInstruction(p, hp1) and
  13402. (tai(hp1).typ = ait_instruction) and
  13403. (taicpu(hp1).opcode = A_AND) and
  13404. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13405. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13406. begin
  13407. case taicpu(p).opsize Of
  13408. S_BL:
  13409. if (taicpu(hp1).opsize <> S_L) or
  13410. (taicpu(hp1).oper[0]^.val > $FF) then
  13411. begin
  13412. DebugMsg(SPeepholeOptimization + 'var13',p);
  13413. taicpu(hp1).changeopsize(S_L);
  13414. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13415. Include(OptsToCheck, aoc_ForceNewIteration);
  13416. end;
  13417. S_WL:
  13418. if (taicpu(hp1).opsize <> S_L) or
  13419. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13420. begin
  13421. DebugMsg(SPeepholeOptimization + 'var14',p);
  13422. taicpu(hp1).changeopsize(S_L);
  13423. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13424. Include(OptsToCheck, aoc_ForceNewIteration);
  13425. end;
  13426. S_BW:
  13427. if (taicpu(hp1).opsize <> S_W) or
  13428. (taicpu(hp1).oper[0]^.val > $FF) then
  13429. begin
  13430. DebugMsg(SPeepholeOptimization + 'var15',p);
  13431. taicpu(hp1).changeopsize(S_W);
  13432. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13433. Include(OptsToCheck, aoc_ForceNewIteration);
  13434. end;
  13435. else
  13436. Internalerror(2017050704)
  13437. end;
  13438. end;
  13439. end;
  13440. end;
  13441. end;
  13442. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13443. var
  13444. hp1, hp2 : tai;
  13445. MaskLength : Cardinal;
  13446. MaskedBits : TCgInt;
  13447. ActiveReg : TRegister;
  13448. begin
  13449. Result:=false;
  13450. { There are no optimisations for reference targets }
  13451. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13452. Exit;
  13453. while GetNextInstruction(p, hp1) and
  13454. (hp1.typ = ait_instruction) do
  13455. begin
  13456. if (taicpu(p).oper[0]^.typ = top_const) then
  13457. begin
  13458. case taicpu(hp1).opcode of
  13459. A_AND:
  13460. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13461. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13462. { the second register must contain the first one, so compare their subreg types }
  13463. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13464. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13465. { change
  13466. and const1, reg
  13467. and const2, reg
  13468. to
  13469. and (const1 and const2), reg
  13470. }
  13471. begin
  13472. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13473. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13474. RemoveCurrentP(p, hp1);
  13475. Result:=true;
  13476. exit;
  13477. end;
  13478. A_CMP:
  13479. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13480. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13481. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13482. { Just check that the condition on the next instruction is compatible }
  13483. GetNextInstruction(hp1, hp2) and
  13484. (hp2.typ = ait_instruction) and
  13485. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13486. then
  13487. { change
  13488. and 2^n, reg
  13489. cmp 2^n, reg
  13490. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13491. to
  13492. and 2^n, reg
  13493. test reg, reg
  13494. j(~c) / set(~c) / cmov(~c)
  13495. }
  13496. begin
  13497. { Keep TEST instruction in, rather than remove it, because
  13498. it may trigger other optimisations such as MovAndTest2Test }
  13499. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13500. taicpu(hp1).opcode := A_TEST;
  13501. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13502. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13503. Result := True;
  13504. Exit;
  13505. end
  13506. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13507. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13508. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13509. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13510. { change
  13511. and $ff/$ff/$ffff, reg
  13512. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13513. dealloc reg
  13514. to
  13515. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13516. }
  13517. begin
  13518. TransferUsedRegs(TmpUsedRegs);
  13519. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13520. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13521. begin
  13522. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13523. case taicpu(p).oper[0]^.val of
  13524. $ff:
  13525. begin
  13526. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13527. taicpu(hp1).opsize:=S_B;
  13528. end;
  13529. $ffff:
  13530. begin
  13531. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13532. taicpu(hp1).opsize:=S_W;
  13533. end;
  13534. $ffffffff:
  13535. begin
  13536. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13537. taicpu(hp1).opsize:=S_L;
  13538. end;
  13539. else
  13540. Internalerror(2023030401);
  13541. end;
  13542. RemoveCurrentP(p);
  13543. Result := True;
  13544. Exit;
  13545. end;
  13546. end;
  13547. A_MOVZX:
  13548. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13549. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13550. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13551. (
  13552. (
  13553. (taicpu(p).opsize=S_W) and
  13554. (taicpu(hp1).opsize=S_BW)
  13555. ) or
  13556. (
  13557. (taicpu(p).opsize=S_L) and
  13558. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13559. )
  13560. {$ifdef x86_64}
  13561. or
  13562. (
  13563. (taicpu(p).opsize=S_Q) and
  13564. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13565. )
  13566. {$endif x86_64}
  13567. ) then
  13568. begin
  13569. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13570. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13571. ) or
  13572. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13573. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13574. then
  13575. begin
  13576. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13577. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13578. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13579. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13580. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13581. }
  13582. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13583. RemoveInstruction(hp1);
  13584. { See if there are other optimisations possible }
  13585. Continue;
  13586. end;
  13587. end;
  13588. A_SHL:
  13589. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13590. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13591. begin
  13592. {$ifopt R+}
  13593. {$define RANGE_WAS_ON}
  13594. {$R-}
  13595. {$endif}
  13596. { get length of potential and mask }
  13597. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13598. { really a mask? }
  13599. {$ifdef RANGE_WAS_ON}
  13600. {$R+}
  13601. {$endif}
  13602. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13603. { unmasked part shifted out? }
  13604. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13605. begin
  13606. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13607. RemoveCurrentP(p, hp1);
  13608. Result:=true;
  13609. exit;
  13610. end;
  13611. end;
  13612. A_SHR:
  13613. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13614. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13615. (taicpu(hp1).oper[0]^.val <= 63) then
  13616. begin
  13617. { Does SHR combined with the AND cover all the bits?
  13618. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13619. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13620. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13621. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13622. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13623. begin
  13624. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13625. RemoveCurrentP(p, hp1);
  13626. Result := True;
  13627. Exit;
  13628. end;
  13629. end;
  13630. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13631. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13632. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13633. begin
  13634. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13635. (
  13636. (
  13637. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13638. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13639. ) or (
  13640. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13641. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13642. {$ifdef x86_64}
  13643. ) or (
  13644. (taicpu(hp1).opsize = S_LQ) and
  13645. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13646. {$endif x86_64}
  13647. )
  13648. ) then
  13649. begin
  13650. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13651. begin
  13652. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13653. RemoveInstruction(hp1);
  13654. { See if there are other optimisations possible }
  13655. Continue;
  13656. end;
  13657. { The super-registers are the same though.
  13658. Note that this change by itself doesn't improve
  13659. code speed, but it opens up other optimisations. }
  13660. {$ifdef x86_64}
  13661. { Convert 64-bit register to 32-bit }
  13662. case taicpu(hp1).opsize of
  13663. S_BQ:
  13664. begin
  13665. taicpu(hp1).opsize := S_BL;
  13666. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13667. end;
  13668. S_WQ:
  13669. begin
  13670. taicpu(hp1).opsize := S_WL;
  13671. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13672. end
  13673. else
  13674. ;
  13675. end;
  13676. {$endif x86_64}
  13677. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13678. taicpu(hp1).opcode := A_MOVZX;
  13679. { See if there are other optimisations possible }
  13680. Continue;
  13681. end;
  13682. end;
  13683. else
  13684. ;
  13685. end;
  13686. end
  13687. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13688. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13689. begin
  13690. {$ifdef x86_64}
  13691. if (taicpu(p).opsize = S_Q) then
  13692. begin
  13693. { Never necessary }
  13694. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13695. RemoveCurrentP(p, hp1);
  13696. Result := True;
  13697. Exit;
  13698. end;
  13699. {$endif x86_64}
  13700. { Forward check to determine necessity of and %reg,%reg }
  13701. TransferUsedRegs(TmpUsedRegs);
  13702. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13703. { Saves on a bunch of dereferences }
  13704. ActiveReg := taicpu(p).oper[1]^.reg;
  13705. case taicpu(hp1).opcode of
  13706. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13707. if (
  13708. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13709. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13710. ) and
  13711. (
  13712. (taicpu(hp1).opcode <> A_MOV) or
  13713. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13714. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13715. ) and
  13716. not (
  13717. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13718. (taicpu(hp1).opcode = A_MOV) and
  13719. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13720. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13721. ) and
  13722. (
  13723. (
  13724. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13725. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13726. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13727. ) or
  13728. (
  13729. {$ifdef x86_64}
  13730. (
  13731. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13732. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13733. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13734. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13735. ) and
  13736. {$endif x86_64}
  13737. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13738. )
  13739. ) then
  13740. begin
  13741. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13742. RemoveCurrentP(p, hp1);
  13743. Result := True;
  13744. Exit;
  13745. end;
  13746. A_ADD,
  13747. A_AND,
  13748. A_BSF,
  13749. A_BSR,
  13750. A_BTC,
  13751. A_BTR,
  13752. A_BTS,
  13753. A_OR,
  13754. A_SUB,
  13755. A_XOR:
  13756. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13757. if (
  13758. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13759. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13760. ) and
  13761. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13762. begin
  13763. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13764. RemoveCurrentP(p, hp1);
  13765. Result := True;
  13766. Exit;
  13767. end;
  13768. A_CMP,
  13769. A_TEST:
  13770. if (
  13771. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13772. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13773. ) and
  13774. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13775. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13776. begin
  13777. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13778. RemoveCurrentP(p, hp1);
  13779. Result := True;
  13780. Exit;
  13781. end;
  13782. A_BSWAP,
  13783. A_NEG,
  13784. A_NOT:
  13785. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13786. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13787. begin
  13788. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13789. RemoveCurrentP(p, hp1);
  13790. Result := True;
  13791. Exit;
  13792. end;
  13793. else
  13794. ;
  13795. end;
  13796. end;
  13797. if (taicpu(hp1).is_jmp) and
  13798. (taicpu(hp1).opcode<>A_JMP) and
  13799. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13800. begin
  13801. { change
  13802. and x, reg
  13803. jxx
  13804. to
  13805. test x, reg
  13806. jxx
  13807. if reg is deallocated before the
  13808. jump, but only if it's a conditional jump (PFV)
  13809. }
  13810. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13811. taicpu(p).opcode := A_TEST;
  13812. Exit;
  13813. end;
  13814. Break;
  13815. end;
  13816. { Lone AND tests }
  13817. if (taicpu(p).oper[0]^.typ = top_const) then
  13818. begin
  13819. {
  13820. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13821. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13822. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13823. }
  13824. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13825. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13826. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13827. begin
  13828. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13829. if taicpu(p).opsize = S_L then
  13830. begin
  13831. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13832. Result := True;
  13833. end;
  13834. end;
  13835. end;
  13836. { Backward check to determine necessity of and %reg,%reg }
  13837. if (taicpu(p).oper[0]^.typ = top_reg) and
  13838. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13839. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13840. GetLastInstruction(p, hp2) and
  13841. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13842. { Check size of adjacent instruction to determine if the AND is
  13843. effectively a null operation }
  13844. (
  13845. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13846. { Note: Don't include S_Q }
  13847. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13848. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13849. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13850. ) then
  13851. begin
  13852. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13853. { If GetNextInstruction returned False, hp1 will be nil }
  13854. RemoveCurrentP(p, hp1);
  13855. Result := True;
  13856. Exit;
  13857. end;
  13858. end;
  13859. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13860. var
  13861. hp1, hp2: tai;
  13862. NewRef: TReference;
  13863. Distance: Cardinal;
  13864. TempTracking: TAllUsedRegs;
  13865. { This entire nested function is used in an if-statement below, but we
  13866. want to avoid all the used reg transfers and GetNextInstruction calls
  13867. until we really have to check }
  13868. function MemRegisterNotUsedLater: Boolean; inline;
  13869. var
  13870. hp2: tai;
  13871. begin
  13872. TransferUsedRegs(TmpUsedRegs);
  13873. hp2 := p;
  13874. repeat
  13875. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13876. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13877. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13878. end;
  13879. begin
  13880. Result := False;
  13881. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13882. (taicpu(p).oper[1]^.typ = top_reg) then
  13883. begin
  13884. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13885. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13886. (hp1.typ <> ait_instruction) or
  13887. not
  13888. (
  13889. (cs_opt_level3 in current_settings.optimizerswitches) or
  13890. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13891. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13892. ) then
  13893. Exit;
  13894. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13895. addq $x, %rax
  13896. movq %rax, %rdx
  13897. sarq $63, %rdx
  13898. (%rax still in use)
  13899. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13900. leaq $x(%rax),%rdx
  13901. addq $x, %rax
  13902. sarq $63, %rdx
  13903. ...which is okay since it breaks the dependency chain between
  13904. addq and movq, but if OptPass2MOV is called first:
  13905. addq $x, %rax
  13906. cqto
  13907. ...which is better in all ways, taking only 2 cycles to execute
  13908. and much smaller in code size.
  13909. }
  13910. { The extra register tracking is quite strenuous }
  13911. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13912. MatchInstruction(hp1, A_MOV, []) then
  13913. begin
  13914. { Update the register tracking to the MOV instruction }
  13915. CopyUsedRegs(TempTracking);
  13916. hp2 := p;
  13917. repeat
  13918. UpdateUsedRegs(tai(hp2.Next));
  13919. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13920. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13921. OptPass2ADD get called again }
  13922. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13923. begin
  13924. { Reset the tracking to the current instruction }
  13925. RestoreUsedRegs(TempTracking);
  13926. ReleaseUsedRegs(TempTracking);
  13927. Result := True;
  13928. Exit;
  13929. end;
  13930. { Reset the tracking to the current instruction }
  13931. RestoreUsedRegs(TempTracking);
  13932. ReleaseUsedRegs(TempTracking);
  13933. { If OptPass2MOV returned True, we don't need to set Result to
  13934. True if hp1 didn't change because the ADD instruction didn't
  13935. get modified and we'll be evaluating hp1 again when the
  13936. peephole optimizer reaches it }
  13937. end;
  13938. { Change:
  13939. add %reg2,%reg1
  13940. (%reg2 not modified in between)
  13941. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13942. To:
  13943. mov/s/z #(%reg1,%reg2),%reg1
  13944. }
  13945. if (taicpu(p).oper[0]^.typ = top_reg) and
  13946. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13947. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13948. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13949. (
  13950. (
  13951. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13952. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13953. { r/esp cannot be an index }
  13954. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13955. ) or (
  13956. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13957. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13958. )
  13959. ) and (
  13960. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13961. (
  13962. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13963. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13964. MemRegisterNotUsedLater
  13965. )
  13966. ) then
  13967. begin
  13968. if (
  13969. { Instructions are guaranteed to be adjacent on -O2 and under }
  13970. (cs_opt_level3 in current_settings.optimizerswitches) and
  13971. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13972. ) then
  13973. begin
  13974. { If the other register is used in between, move the MOV
  13975. instruction to right after the ADD instruction so a
  13976. saving can still be made }
  13977. Asml.Remove(hp1);
  13978. Asml.InsertAfter(hp1, p);
  13979. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13980. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13981. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13982. RemoveCurrentp(p, hp1);
  13983. end
  13984. else
  13985. begin
  13986. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13987. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13988. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13989. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13990. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13991. { hp1 may not be the immediate next instruction under -O3 }
  13992. RemoveCurrentp(p)
  13993. else
  13994. RemoveCurrentp(p, hp1);
  13995. end;
  13996. Result := True;
  13997. Exit;
  13998. end;
  13999. { Change:
  14000. addl/q $x,%reg1
  14001. movl/q %reg1,%reg2
  14002. To:
  14003. leal/q $x(%reg1),%reg2
  14004. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14005. Breaks the dependency chain.
  14006. }
  14007. if (taicpu(p).oper[0]^.typ = top_const) and
  14008. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14009. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14010. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14011. (
  14012. { Instructions are guaranteed to be adjacent on -O2 and under }
  14013. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14014. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14015. ) then
  14016. begin
  14017. TransferUsedRegs(TmpUsedRegs);
  14018. hp2 := p;
  14019. repeat
  14020. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14021. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14022. if (
  14023. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14024. not (cs_opt_size in current_settings.optimizerswitches) or
  14025. (
  14026. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14027. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14028. )
  14029. ) then
  14030. begin
  14031. { Change the MOV instruction to a LEA instruction, and update the
  14032. first operand }
  14033. reference_reset(NewRef, 1, []);
  14034. NewRef.base := taicpu(p).oper[1]^.reg;
  14035. NewRef.scalefactor := 1;
  14036. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14037. taicpu(hp1).opcode := A_LEA;
  14038. taicpu(hp1).loadref(0, NewRef);
  14039. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14040. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14041. begin
  14042. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14043. { Move what is now the LEA instruction to before the ADD instruction }
  14044. Asml.Remove(hp1);
  14045. Asml.InsertBefore(hp1, p);
  14046. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14047. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14048. p := hp1;
  14049. end
  14050. else
  14051. begin
  14052. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14053. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14054. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14055. { hp1 may not be the immediate next instruction under -O3 }
  14056. RemoveCurrentp(p)
  14057. else
  14058. RemoveCurrentp(p, hp1);
  14059. end;
  14060. Result := True;
  14061. end;
  14062. end;
  14063. end;
  14064. end;
  14065. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14066. var
  14067. SubReg: TSubRegister;
  14068. hp1, hp2: tai;
  14069. CallJmp: Boolean;
  14070. begin
  14071. Result := False;
  14072. CallJmp := False;
  14073. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14074. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14075. with taicpu(p).oper[0]^.ref^ do
  14076. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14077. if (offset = 0) then
  14078. begin
  14079. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14080. begin
  14081. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14082. taicpu(p).opcode := A_ADD;
  14083. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14084. Result := True;
  14085. end
  14086. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14087. begin
  14088. if (base <> NR_NO) then
  14089. begin
  14090. if (scalefactor <= 1) then
  14091. begin
  14092. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14093. taicpu(p).opcode := A_ADD;
  14094. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14095. Result := True;
  14096. end;
  14097. end
  14098. else
  14099. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14100. if (scalefactor in [2, 4, 8]) then
  14101. begin
  14102. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14103. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14104. taicpu(p).opcode := A_SHL;
  14105. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14106. Result := True;
  14107. end;
  14108. end;
  14109. end
  14110. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14111. lot of latency, so break off the offset if %reg3 is used soon
  14112. afterwards }
  14113. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14114. { If 3-component addresses don't have additional latency, don't
  14115. perform this optimisation }
  14116. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14117. GetNextInstruction(p, hp1) and
  14118. (hp1.typ = ait_instruction) and
  14119. (
  14120. (
  14121. { Permit jumps and calls since they have a larger degree of overhead }
  14122. (
  14123. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14124. (
  14125. { ... unless the register specifies the location }
  14126. (taicpu(hp1).ops > 0) and
  14127. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14128. )
  14129. ) and
  14130. (
  14131. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14132. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14133. )
  14134. )
  14135. or
  14136. (
  14137. { Check up to two instructions ahead }
  14138. GetNextInstruction(hp1, hp2) and
  14139. (hp2.typ = ait_instruction) and
  14140. (
  14141. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14142. (
  14143. { Same as above }
  14144. (taicpu(hp2).ops > 0) and
  14145. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14146. )
  14147. ) and
  14148. (
  14149. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14150. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14151. )
  14152. )
  14153. ) then
  14154. begin
  14155. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14156. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14157. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14158. offset := 0;
  14159. if Assigned(symbol) or Assigned(relsymbol) then
  14160. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14161. else
  14162. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14163. { Inserting before the next instruction rather than after the
  14164. current instruction gives more accurate register tracking }
  14165. asml.InsertBefore(hp2, hp1);
  14166. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14167. Result := True;
  14168. end;
  14169. end;
  14170. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14171. var
  14172. hp1, hp2: tai;
  14173. NewRef: TReference;
  14174. Distance: Cardinal;
  14175. TempTracking: TAllUsedRegs;
  14176. begin
  14177. Result := False;
  14178. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14179. MatchOpType(taicpu(p),top_const,top_reg) then
  14180. begin
  14181. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14182. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14183. (hp1.typ <> ait_instruction) or
  14184. not
  14185. (
  14186. (cs_opt_level3 in current_settings.optimizerswitches) or
  14187. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14188. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14189. ) then
  14190. Exit;
  14191. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14192. subq $x, %rax
  14193. movq %rax, %rdx
  14194. sarq $63, %rdx
  14195. (%rax still in use)
  14196. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14197. leaq $-x(%rax),%rdx
  14198. movq $x, %rax
  14199. sarq $63, %rdx
  14200. ...which is okay since it breaks the dependency chain between
  14201. subq and movq, but if OptPass2MOV is called first:
  14202. subq $x, %rax
  14203. cqto
  14204. ...which is better in all ways, taking only 2 cycles to execute
  14205. and much smaller in code size.
  14206. }
  14207. { The extra register tracking is quite strenuous }
  14208. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14209. MatchInstruction(hp1, A_MOV, []) then
  14210. begin
  14211. { Update the register tracking to the MOV instruction }
  14212. CopyUsedRegs(TempTracking);
  14213. hp2 := p;
  14214. repeat
  14215. UpdateUsedRegs(tai(hp2.Next));
  14216. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14217. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14218. OptPass2SUB get called again }
  14219. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14220. begin
  14221. { Reset the tracking to the current instruction }
  14222. RestoreUsedRegs(TempTracking);
  14223. ReleaseUsedRegs(TempTracking);
  14224. Result := True;
  14225. Exit;
  14226. end;
  14227. { Reset the tracking to the current instruction }
  14228. RestoreUsedRegs(TempTracking);
  14229. ReleaseUsedRegs(TempTracking);
  14230. { If OptPass2MOV returned True, we don't need to set Result to
  14231. True if hp1 didn't change because the SUB instruction didn't
  14232. get modified and we'll be evaluating hp1 again when the
  14233. peephole optimizer reaches it }
  14234. end;
  14235. { Change:
  14236. subl/q $x,%reg1
  14237. movl/q %reg1,%reg2
  14238. To:
  14239. leal/q $-x(%reg1),%reg2
  14240. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14241. Breaks the dependency chain and potentially permits the removal of
  14242. a CMP instruction if one follows.
  14243. }
  14244. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14245. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14246. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14247. (
  14248. { Instructions are guaranteed to be adjacent on -O2 and under }
  14249. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14250. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14251. ) then
  14252. begin
  14253. TransferUsedRegs(TmpUsedRegs);
  14254. hp2 := p;
  14255. repeat
  14256. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14257. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14258. if (
  14259. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14260. not (cs_opt_size in current_settings.optimizerswitches) or
  14261. (
  14262. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14263. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14264. )
  14265. ) then
  14266. begin
  14267. { Change the MOV instruction to a LEA instruction, and update the
  14268. first operand }
  14269. reference_reset(NewRef, 1, []);
  14270. NewRef.base := taicpu(p).oper[1]^.reg;
  14271. NewRef.scalefactor := 1;
  14272. NewRef.offset := -taicpu(p).oper[0]^.val;
  14273. taicpu(hp1).opcode := A_LEA;
  14274. taicpu(hp1).loadref(0, NewRef);
  14275. TransferUsedRegs(TmpUsedRegs);
  14276. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14277. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14278. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14279. begin
  14280. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14281. { Move what is now the LEA instruction to before the SUB instruction }
  14282. Asml.Remove(hp1);
  14283. Asml.InsertBefore(hp1, p);
  14284. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14285. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14286. p := hp1;
  14287. end
  14288. else
  14289. begin
  14290. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14291. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14292. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14293. { hp1 may not be the immediate next instruction under -O3 }
  14294. RemoveCurrentp(p)
  14295. else
  14296. RemoveCurrentp(p, hp1);
  14297. end;
  14298. Result := True;
  14299. end;
  14300. end;
  14301. end;
  14302. end;
  14303. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14304. begin
  14305. { we can skip all instructions not messing with the stack pointer }
  14306. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14307. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14308. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14309. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14310. ({(taicpu(hp1).ops=0) or }
  14311. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14312. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14313. ) and }
  14314. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14315. )
  14316. ) do
  14317. GetNextInstruction(hp1,hp1);
  14318. Result:=assigned(hp1);
  14319. end;
  14320. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14321. var
  14322. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14323. begin
  14324. Result:=false;
  14325. hp5:=nil;
  14326. hp6:=nil;
  14327. hp7:=nil;
  14328. hp8:=nil;
  14329. { replace
  14330. leal(q) x(<stackpointer>),<stackpointer>
  14331. <optional .seh_stackalloc ...>
  14332. <optional .seh_endprologue ...>
  14333. call procname
  14334. <optional NOP>
  14335. leal(q) -x(<stackpointer>),<stackpointer>
  14336. <optional VZEROUPPER>
  14337. ret
  14338. by
  14339. jmp procname
  14340. but do it only on level 4 because it destroys stack back traces
  14341. }
  14342. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14343. MatchOpType(taicpu(p),top_ref,top_reg) and
  14344. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14345. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14346. { the -8, -24, -40 are not required, but bail out early if possible,
  14347. higher values are unlikely }
  14348. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14349. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14350. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14351. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14352. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14353. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14354. GetNextInstruction(p, hp1) and
  14355. { Take a copy of hp1 }
  14356. SetAndTest(hp1, hp4) and
  14357. { trick to skip label }
  14358. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14359. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14360. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14361. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14362. SkipSimpleInstructions(hp1) and
  14363. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14364. GetNextInstruction(hp1, hp2) and
  14365. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14366. { skip nop instruction on win64 }
  14367. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14368. SetAndTest(hp2,hp6) and
  14369. GetNextInstruction(hp2,hp2) and
  14370. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14371. ) and
  14372. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14373. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14374. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14375. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14376. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14377. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14378. { Segment register will be NR_NO }
  14379. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14380. GetNextInstruction(hp2, hp3) and
  14381. { trick to skip label }
  14382. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14383. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14384. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14385. SetAndTest(hp3,hp5) and
  14386. GetNextInstruction(hp3,hp3) and
  14387. MatchInstruction(hp3,A_RET,[S_NO])
  14388. )
  14389. ) and
  14390. (taicpu(hp3).ops=0) then
  14391. begin
  14392. taicpu(hp1).opcode := A_JMP;
  14393. taicpu(hp1).is_jmp := true;
  14394. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14395. { search for the stackalloc directive and remove it }
  14396. hp7:=tai(p.next);
  14397. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14398. begin
  14399. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14400. begin
  14401. { sanity check }
  14402. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14403. Internalerror(2024012201);
  14404. hp8:=tai(hp7.next);
  14405. RemoveInstruction(tai(hp7));
  14406. hp7:=hp8;
  14407. break;
  14408. end
  14409. else
  14410. hp7:=tai(hp7.next);
  14411. end;
  14412. RemoveCurrentP(p, hp4);
  14413. RemoveInstruction(hp2);
  14414. RemoveInstruction(hp3);
  14415. { if there is a vzeroupper instruction then move it before the jmp }
  14416. if Assigned(hp5) then
  14417. begin
  14418. AsmL.Remove(hp5);
  14419. ASmL.InsertBefore(hp5,hp1)
  14420. end;
  14421. { remove nop on win64 }
  14422. if Assigned(hp6) then
  14423. RemoveInstruction(hp6);
  14424. Result:=true;
  14425. end;
  14426. end;
  14427. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14428. {$ifdef x86_64}
  14429. var
  14430. hp1, hp2, hp3, hp4, hp5: tai;
  14431. {$endif x86_64}
  14432. begin
  14433. Result:=false;
  14434. {$ifdef x86_64}
  14435. hp5:=nil;
  14436. { replace
  14437. push %rax
  14438. call procname
  14439. pop %rcx
  14440. ret
  14441. by
  14442. jmp procname
  14443. but do it only on level 4 because it destroys stack back traces
  14444. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14445. for all supported calling conventions
  14446. }
  14447. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14448. MatchOpType(taicpu(p),top_reg) and
  14449. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14450. GetNextInstruction(p, hp1) and
  14451. { Take a copy of hp1 }
  14452. SetAndTest(hp1, hp4) and
  14453. { trick to skip label }
  14454. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14455. SkipSimpleInstructions(hp1) and
  14456. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14457. GetNextInstruction(hp1, hp2) and
  14458. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14459. MatchOpType(taicpu(hp2),top_reg) and
  14460. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14461. GetNextInstruction(hp2, hp3) and
  14462. { trick to skip label }
  14463. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14464. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14465. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14466. SetAndTest(hp3,hp5) and
  14467. GetNextInstruction(hp3,hp3) and
  14468. MatchInstruction(hp3,A_RET,[S_NO])
  14469. )
  14470. ) and
  14471. (taicpu(hp3).ops=0) then
  14472. begin
  14473. taicpu(hp1).opcode := A_JMP;
  14474. taicpu(hp1).is_jmp := true;
  14475. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14476. RemoveCurrentP(p, hp4);
  14477. RemoveInstruction(hp2);
  14478. RemoveInstruction(hp3);
  14479. if Assigned(hp5) then
  14480. begin
  14481. AsmL.Remove(hp5);
  14482. ASmL.InsertBefore(hp5,hp1)
  14483. end;
  14484. Result:=true;
  14485. end;
  14486. {$endif x86_64}
  14487. end;
  14488. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14489. var
  14490. Value, RegName: string;
  14491. hp1: tai;
  14492. begin
  14493. Result:=false;
  14494. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14495. begin
  14496. case taicpu(p).oper[0]^.val of
  14497. 0:
  14498. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14499. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14500. (
  14501. { See if we can still convert the instruction }
  14502. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14503. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14504. ) then
  14505. begin
  14506. { change "mov $0,%reg" into "xor %reg,%reg" }
  14507. taicpu(p).opcode := A_XOR;
  14508. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14509. Result := True;
  14510. {$ifdef x86_64}
  14511. end
  14512. else if (taicpu(p).opsize = S_Q) then
  14513. begin
  14514. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14515. { The actual optimization }
  14516. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14517. taicpu(p).changeopsize(S_L);
  14518. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14519. Result := True;
  14520. end;
  14521. $1..$FFFFFFFF:
  14522. begin
  14523. { Code size reduction by J. Gareth "Kit" Moreton }
  14524. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14525. case taicpu(p).opsize of
  14526. S_Q:
  14527. begin
  14528. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14529. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14530. { The actual optimization }
  14531. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14532. taicpu(p).changeopsize(S_L);
  14533. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14534. Result := True;
  14535. end;
  14536. else
  14537. { Do nothing };
  14538. end;
  14539. {$endif x86_64}
  14540. end;
  14541. -1:
  14542. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14543. if (cs_opt_size in current_settings.optimizerswitches) and
  14544. (taicpu(p).opsize <> S_B) and
  14545. (
  14546. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14547. (
  14548. { See if we can still convert the instruction }
  14549. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14550. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14551. )
  14552. ) then
  14553. begin
  14554. { change "mov $-1,%reg" into "or $-1,%reg" }
  14555. { NOTES:
  14556. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14557. - This operation creates a false dependency on the register, so only do it when optimising for size
  14558. - 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
  14559. }
  14560. taicpu(p).opcode := A_OR;
  14561. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14562. Result := True;
  14563. end;
  14564. else
  14565. { Do nothing };
  14566. end;
  14567. end;
  14568. end;
  14569. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14570. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14571. begin
  14572. Result := False;
  14573. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14574. Exit;
  14575. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14576. so don't bother optimising }
  14577. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14578. Exit;
  14579. if (taicpu(p).oper[0]^.typ <> top_const) or
  14580. { If the value can fit into an 8-bit signed integer, a smaller
  14581. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14582. falls within this range }
  14583. (
  14584. (taicpu(p).oper[0]^.val > -128) and
  14585. (taicpu(p).oper[0]^.val <= 127)
  14586. ) then
  14587. Exit;
  14588. { If we're optimising for size, this is acceptable }
  14589. if (cs_opt_size in current_settings.optimizerswitches) then
  14590. Exit(True);
  14591. if (taicpu(p).oper[1]^.typ = top_reg) and
  14592. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14593. Exit(True);
  14594. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14595. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14596. Exit(True);
  14597. end;
  14598. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14599. var
  14600. hp1: tai;
  14601. Value: TCGInt;
  14602. begin
  14603. Result := False;
  14604. if MatchOpType(taicpu(p), top_const, top_reg) then
  14605. begin
  14606. { Detect:
  14607. andw x, %ax (0 <= x < $8000)
  14608. ...
  14609. movzwl %ax,%eax
  14610. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14611. }
  14612. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14613. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14614. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14615. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14616. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14617. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14618. begin
  14619. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14620. taicpu(hp1).opcode := A_CWDE;
  14621. taicpu(hp1).clearop(0);
  14622. taicpu(hp1).clearop(1);
  14623. taicpu(hp1).ops := 0;
  14624. { A change was made, but not with p, so don't set Result, but
  14625. notify the compiler that a change was made }
  14626. Include(OptsToCheck, aoc_ForceNewIteration);
  14627. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14628. end;
  14629. end;
  14630. { If "not x" is a power of 2 (popcnt = 1), change:
  14631. and $x, %reg/ref
  14632. To:
  14633. btr lb(x), %reg/ref
  14634. }
  14635. if IsBTXAcceptable(p) and
  14636. (
  14637. { Make sure a TEST doesn't follow that plays with the register }
  14638. not GetNextInstruction(p, hp1) or
  14639. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14640. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14641. ) then
  14642. begin
  14643. {$push}{$R-}{$Q-}
  14644. { Value is a sign-extended 32-bit integer - just correct it
  14645. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14646. checks to see if this operand is an immediate. }
  14647. Value := not taicpu(p).oper[0]^.val;
  14648. {$pop}
  14649. {$ifdef x86_64}
  14650. if taicpu(p).opsize = S_L then
  14651. {$endif x86_64}
  14652. Value := Value and $FFFFFFFF;
  14653. if (PopCnt(QWord(Value)) = 1) then
  14654. begin
  14655. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14656. taicpu(p).opcode := A_BTR;
  14657. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14658. Result := True;
  14659. Exit;
  14660. end;
  14661. end;
  14662. end;
  14663. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14664. begin
  14665. Result := False;
  14666. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14667. Exit;
  14668. { Convert:
  14669. movswl %ax,%eax -> cwtl
  14670. movslq %eax,%rax -> cdqe
  14671. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14672. refer to the same opcode and depends only on the assembler's
  14673. current operand-size attribute. [Kit]
  14674. }
  14675. with taicpu(p) do
  14676. case opsize of
  14677. S_WL:
  14678. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14679. begin
  14680. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14681. opcode := A_CWDE;
  14682. clearop(0);
  14683. clearop(1);
  14684. ops := 0;
  14685. Result := True;
  14686. end;
  14687. {$ifdef x86_64}
  14688. S_LQ:
  14689. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14690. begin
  14691. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14692. opcode := A_CDQE;
  14693. clearop(0);
  14694. clearop(1);
  14695. ops := 0;
  14696. Result := True;
  14697. end;
  14698. {$endif x86_64}
  14699. else
  14700. ;
  14701. end;
  14702. end;
  14703. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14704. var
  14705. hp1, hp2: tai;
  14706. IdentityMask, Shift: TCGInt;
  14707. LimitSize: Topsize;
  14708. DoNotMerge: Boolean;
  14709. begin
  14710. Result := False;
  14711. { All these optimisations work on "shr const,%reg" }
  14712. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14713. Exit;
  14714. DoNotMerge := False;
  14715. Shift := taicpu(p).oper[0]^.val;
  14716. LimitSize := taicpu(p).opsize;
  14717. hp1 := p;
  14718. repeat
  14719. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14720. Break;
  14721. { Detect:
  14722. shr x, %reg
  14723. and y, %reg
  14724. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14725. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14726. }
  14727. case taicpu(hp1).opcode of
  14728. A_AND:
  14729. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14730. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14731. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14732. begin
  14733. { Make sure the FLAGS register isn't in use }
  14734. TransferUsedRegs(TmpUsedRegs);
  14735. hp2 := p;
  14736. repeat
  14737. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14738. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14739. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14740. begin
  14741. { Generate the identity mask }
  14742. case taicpu(p).opsize of
  14743. S_B:
  14744. IdentityMask := $FF shr Shift;
  14745. S_W:
  14746. IdentityMask := $FFFF shr Shift;
  14747. S_L:
  14748. IdentityMask := $FFFFFFFF shr Shift;
  14749. {$ifdef x86_64}
  14750. S_Q:
  14751. { We need to force the operands to be unsigned 64-bit
  14752. integers otherwise the wrong value is generated }
  14753. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14754. {$endif x86_64}
  14755. else
  14756. InternalError(2022081501);
  14757. end;
  14758. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14759. begin
  14760. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14761. { All the possible 1 bits are covered, so we can remove the AND }
  14762. hp2 := tai(hp1.Previous);
  14763. RemoveInstruction(hp1);
  14764. { p wasn't actually changed, so don't set Result to True,
  14765. but a change was nonetheless made elsewhere }
  14766. Include(OptsToCheck, aoc_ForceNewIteration);
  14767. { Do another pass in case other AND or MOVZX instructions
  14768. follow }
  14769. hp1 := hp2;
  14770. Continue;
  14771. end;
  14772. end;
  14773. end;
  14774. A_TEST, A_CMP, A_Jcc:
  14775. { Skip over conditional jumps and relevant comparisons }
  14776. Continue;
  14777. A_MOVZX:
  14778. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14779. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14780. begin
  14781. { Since the original register is being read as is, subsequent
  14782. SHRs must not be merged at this point }
  14783. DoNotMerge := True;
  14784. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14785. begin
  14786. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14787. begin
  14788. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14789. { All the possible 1 bits are covered, so we can remove the AND }
  14790. hp2 := tai(hp1.Previous);
  14791. RemoveInstruction(hp1);
  14792. hp1 := hp2;
  14793. end
  14794. else { Different register target }
  14795. begin
  14796. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14797. taicpu(hp1).opcode := A_MOV;
  14798. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14799. case taicpu(hp1).opsize of
  14800. S_BW:
  14801. taicpu(hp1).opsize := S_W;
  14802. S_BL, S_WL:
  14803. taicpu(hp1).opsize := S_L;
  14804. else
  14805. InternalError(2022081503);
  14806. end;
  14807. end;
  14808. end
  14809. else if (Shift > 0) and
  14810. (taicpu(p).opsize = S_W) and
  14811. (taicpu(hp1).opsize = S_WL) and
  14812. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14813. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14814. begin
  14815. { Detect:
  14816. shr x, %ax (x > 0)
  14817. ...
  14818. movzwl %ax,%eax
  14819. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14820. }
  14821. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14822. taicpu(hp1).opcode := A_CWDE;
  14823. taicpu(hp1).clearop(0);
  14824. taicpu(hp1).clearop(1);
  14825. taicpu(hp1).ops := 0;
  14826. end;
  14827. { Move onto the next instruction }
  14828. Continue;
  14829. end;
  14830. A_SHL, A_SAL, A_SHR:
  14831. if (taicpu(hp1).opsize <= LimitSize) and
  14832. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14833. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14834. begin
  14835. { Make sure the sizes don't exceed the register size limit
  14836. (measured by the shift value falling below the limit) }
  14837. if taicpu(hp1).opsize < LimitSize then
  14838. LimitSize := taicpu(hp1).opsize;
  14839. if taicpu(hp1).opcode = A_SHR then
  14840. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14841. else
  14842. begin
  14843. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14844. DoNotMerge := True;
  14845. end;
  14846. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14847. Break;
  14848. { Since we've established that the combined shift is within
  14849. limits, we can actually combine the adjacent SHR
  14850. instructions even if they're different sizes }
  14851. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14852. begin
  14853. hp2 := tai(hp1.Previous);
  14854. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14855. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14856. RemoveInstruction(hp1);
  14857. hp1 := hp2;
  14858. end;
  14859. { Move onto the next instruction }
  14860. Continue;
  14861. end;
  14862. else
  14863. ;
  14864. end;
  14865. Break;
  14866. until False;
  14867. { Detect the following (looking backwards):
  14868. shr %cl,%reg
  14869. shr x, %reg
  14870. Swap the two SHR instructions to minimise a pipeline stall.
  14871. }
  14872. if GetLastInstruction(p, hp1) and
  14873. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14874. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14875. { First operand will be %cl }
  14876. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14877. { Just to be sure }
  14878. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14879. begin
  14880. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14881. { Moving the entries this way ensures the register tracking remains correct }
  14882. Asml.Remove(p);
  14883. Asml.InsertBefore(p, hp1);
  14884. p := hp1;
  14885. { Don't set Result to True because the current instruction is now
  14886. "shr %cl,%reg" and there's nothing more we can do with it }
  14887. end;
  14888. end;
  14889. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14890. var
  14891. hp1, hp2: tai;
  14892. Opposite, SecondOpposite: TAsmOp;
  14893. NewCond: TAsmCond;
  14894. begin
  14895. Result := False;
  14896. { Change:
  14897. add/sub 128,(dest)
  14898. To:
  14899. sub/add -128,(dest)
  14900. This generaally takes fewer bytes to encode because -128 can be stored
  14901. in a signed byte, whereas +128 cannot.
  14902. }
  14903. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14904. begin
  14905. if taicpu(p).opcode = A_ADD then
  14906. Opposite := A_SUB
  14907. else
  14908. Opposite := A_ADD;
  14909. { Be careful if the flags are in use, because the CF flag inverts
  14910. when changing from ADD to SUB and vice versa }
  14911. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14912. GetNextInstruction(p, hp1) then
  14913. begin
  14914. TransferUsedRegs(TmpUsedRegs);
  14915. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14916. hp2 := hp1;
  14917. { Scan ahead to check if everything's safe }
  14918. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14919. begin
  14920. if (hp1.typ <> ait_instruction) then
  14921. { Probably unsafe since the flags are still in use }
  14922. Exit;
  14923. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14924. { Stop searching at an unconditional jump }
  14925. Break;
  14926. if not
  14927. (
  14928. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14929. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14930. ) and
  14931. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14932. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14933. Exit;
  14934. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14935. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14936. { Move to the next instruction }
  14937. GetNextInstruction(hp1, hp1);
  14938. end;
  14939. while Assigned(hp2) and (hp2 <> hp1) do
  14940. begin
  14941. NewCond := C_None;
  14942. case taicpu(hp2).condition of
  14943. C_A, C_NBE:
  14944. NewCond := C_BE;
  14945. C_B, C_C, C_NAE:
  14946. NewCond := C_AE;
  14947. C_AE, C_NB, C_NC:
  14948. NewCond := C_B;
  14949. C_BE, C_NA:
  14950. NewCond := C_A;
  14951. else
  14952. { No change needed };
  14953. end;
  14954. if NewCond <> C_None then
  14955. begin
  14956. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14957. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14958. taicpu(hp2).condition := NewCond;
  14959. end
  14960. else
  14961. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14962. begin
  14963. { Because of the flipping of the carry bit, to ensure
  14964. the operation remains equivalent, ADC becomes SBB
  14965. and vice versa, and the constant is not-inverted.
  14966. If multiple ADCs or SBBs appear in a row, each one
  14967. changed causes the carry bit to invert, so they all
  14968. need to be flipped }
  14969. if taicpu(hp2).opcode = A_ADC then
  14970. SecondOpposite := A_SBB
  14971. else
  14972. SecondOpposite := A_ADC;
  14973. if taicpu(hp2).oper[0]^.typ <> top_const then
  14974. { Should have broken out of this optimisation already }
  14975. InternalError(2021112901);
  14976. 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]^) + ' -> ' +
  14977. 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);
  14978. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14979. taicpu(hp2).opcode := SecondOpposite;
  14980. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14981. end;
  14982. { Move to the next instruction }
  14983. GetNextInstruction(hp2, hp2);
  14984. end;
  14985. if (hp2 <> hp1) then
  14986. InternalError(2021111501);
  14987. end;
  14988. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14989. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14990. taicpu(p).opcode := Opposite;
  14991. taicpu(p).oper[0]^.val := -128;
  14992. { No further optimisations can be made on this instruction, so move
  14993. onto the next one to save time }
  14994. p := tai(p.Next);
  14995. UpdateUsedRegs(p);
  14996. Result := True;
  14997. Exit;
  14998. end;
  14999. { Detect:
  15000. add/sub %reg2,(dest)
  15001. add/sub x, (dest)
  15002. (dest can be a register or a reference)
  15003. Swap the instructions to minimise a pipeline stall. This reverses the
  15004. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15005. optimisations could be made.
  15006. }
  15007. if (taicpu(p).oper[0]^.typ = top_reg) and
  15008. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15009. (
  15010. (
  15011. (taicpu(p).oper[1]^.typ = top_reg) and
  15012. { We can try searching further ahead if we're writing to a register }
  15013. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15014. ) or
  15015. (
  15016. (taicpu(p).oper[1]^.typ = top_ref) and
  15017. GetNextInstruction(p, hp1)
  15018. )
  15019. ) and
  15020. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15021. (taicpu(hp1).oper[0]^.typ = top_const) and
  15022. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15023. begin
  15024. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15025. TransferUsedRegs(TmpUsedRegs);
  15026. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15027. hp2 := p;
  15028. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15029. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15030. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15031. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15032. begin
  15033. asml.remove(hp1);
  15034. asml.InsertBefore(hp1, p);
  15035. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15036. Result := True;
  15037. end;
  15038. end;
  15039. end;
  15040. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15041. var
  15042. hp1: tai;
  15043. begin
  15044. Result:=false;
  15045. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15046. while GetNextInstruction(p, hp1) and
  15047. TrySwapMovCmp(p, hp1) do
  15048. begin
  15049. if MatchInstruction(hp1, A_MOV, []) then
  15050. begin
  15051. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15052. begin
  15053. { A little hacky, but since CMP doesn't read the flags, only
  15054. modify them, it's safe if they get scrambled by MOV -> XOR }
  15055. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15056. Result := PostPeepholeOptMov(hp1);
  15057. {$ifdef x86_64}
  15058. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15059. { Used to shrink instruction size }
  15060. PostPeepholeOptXor(hp1);
  15061. {$endif x86_64}
  15062. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15063. end
  15064. else
  15065. begin
  15066. Result := PostPeepholeOptMov(hp1);
  15067. {$ifdef x86_64}
  15068. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15069. { Used to shrink instruction size }
  15070. PostPeepholeOptXor(hp1);
  15071. {$endif x86_64}
  15072. end;
  15073. end;
  15074. { Enabling this flag is actually a null operation, but it marks
  15075. the code as 'modified' during this pass }
  15076. Include(OptsToCheck, aoc_ForceNewIteration);
  15077. end;
  15078. { change "cmp $0, %reg" to "test %reg, %reg" }
  15079. if MatchOpType(taicpu(p),top_const,top_reg) and
  15080. (taicpu(p).oper[0]^.val = 0) then
  15081. begin
  15082. taicpu(p).opcode := A_TEST;
  15083. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15084. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15085. Result:=true;
  15086. end;
  15087. end;
  15088. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15089. var
  15090. IsTestConstX, IsValid : Boolean;
  15091. hp1,hp2 : tai;
  15092. begin
  15093. Result:=false;
  15094. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15095. if (taicpu(p).opcode = A_TEST) then
  15096. while GetNextInstruction(p, hp1) and
  15097. TrySwapMovCmp(p, hp1) do
  15098. begin
  15099. if MatchInstruction(hp1, A_MOV, []) then
  15100. begin
  15101. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15102. begin
  15103. { A little hacky, but since TEST doesn't read the flags, only
  15104. modify them, it's safe if they get scrambled by MOV -> XOR }
  15105. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15106. Result := PostPeepholeOptMov(hp1);
  15107. {$ifdef x86_64}
  15108. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15109. { Used to shrink instruction size }
  15110. PostPeepholeOptXor(hp1);
  15111. {$endif x86_64}
  15112. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15113. end
  15114. else
  15115. begin
  15116. Result := PostPeepholeOptMov(hp1);
  15117. {$ifdef x86_64}
  15118. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15119. { Used to shrink instruction size }
  15120. PostPeepholeOptXor(hp1);
  15121. {$endif x86_64}
  15122. end;
  15123. end;
  15124. { Enabling this flag is actually a null operation, but it marks
  15125. the code as 'modified' during this pass }
  15126. Include(OptsToCheck, aoc_ForceNewIteration);
  15127. end;
  15128. { If x is a power of 2 (popcnt = 1), change:
  15129. or $x, %reg/ref
  15130. To:
  15131. bts lb(x), %reg/ref
  15132. }
  15133. if (taicpu(p).opcode = A_OR) and
  15134. IsBTXAcceptable(p) and
  15135. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15136. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15137. (
  15138. { Don't optimise if a test instruction follows }
  15139. not GetNextInstruction(p, hp1) or
  15140. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15141. ) then
  15142. begin
  15143. 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);
  15144. taicpu(p).opcode := A_BTS;
  15145. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15146. Result := True;
  15147. Exit;
  15148. end;
  15149. { If x is a power of 2 (popcnt = 1), change:
  15150. test $x, %reg/ref
  15151. je / sete / cmove (or jne / setne)
  15152. To:
  15153. bt lb(x), %reg/ref
  15154. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15155. }
  15156. if (taicpu(p).opcode = A_TEST) and
  15157. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15158. (taicpu(p).oper[0]^.typ = top_const) and
  15159. (
  15160. (cs_opt_size in current_settings.optimizerswitches) or
  15161. (
  15162. (taicpu(p).oper[1]^.typ = top_reg) and
  15163. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15164. ) or
  15165. (
  15166. (taicpu(p).oper[1]^.typ <> top_reg) and
  15167. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15168. )
  15169. ) and
  15170. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15171. { For sizes less than S_L, the byte size is equal or larger with BT,
  15172. so don't bother optimising }
  15173. (taicpu(p).opsize >= S_L) then
  15174. begin
  15175. IsValid := True;
  15176. { Check the next set of instructions, watching the FLAGS register
  15177. and the conditions used }
  15178. TransferUsedRegs(TmpUsedRegs);
  15179. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15180. hp1 := p;
  15181. hp2 := nil;
  15182. while GetNextInstruction(hp1, hp1) do
  15183. begin
  15184. if not Assigned(hp2) then
  15185. { The first instruction after TEST }
  15186. hp2 := hp1;
  15187. if (hp1.typ <> ait_instruction) then
  15188. begin
  15189. { If the flags are no longer in use, everything is fine }
  15190. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15191. IsValid := False;
  15192. Break;
  15193. end;
  15194. case taicpu(hp1).condition of
  15195. C_None:
  15196. begin
  15197. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15198. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15199. { Something is not quite normal, so play safe and don't change }
  15200. IsValid := False;
  15201. Break;
  15202. end;
  15203. C_E, C_Z, C_NE, C_NZ:
  15204. { This is fine };
  15205. else
  15206. begin
  15207. { Unsupported condition }
  15208. IsValid := False;
  15209. Break;
  15210. end;
  15211. end;
  15212. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15213. end;
  15214. if IsValid then
  15215. begin
  15216. while hp2 <> hp1 do
  15217. begin
  15218. case taicpu(hp2).condition of
  15219. C_Z, C_E:
  15220. taicpu(hp2).condition := C_NC;
  15221. C_NZ, C_NE:
  15222. taicpu(hp2).condition := C_C;
  15223. else
  15224. { Should not get this by this point }
  15225. InternalError(2022110701);
  15226. end;
  15227. GetNextInstruction(hp2, hp2);
  15228. end;
  15229. 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);
  15230. taicpu(p).opcode := A_BT;
  15231. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15232. Result := True;
  15233. Exit;
  15234. end;
  15235. end;
  15236. { removes the line marked with (x) from the sequence
  15237. and/or/xor/add/sub/... $x, %y
  15238. test/or %y, %y | test $-1, %y (x)
  15239. j(n)z _Label
  15240. as the first instruction already adjusts the ZF
  15241. %y operand may also be a reference }
  15242. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15243. MatchOperand(taicpu(p).oper[0]^,-1);
  15244. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15245. GetLastInstruction(p, hp1) and
  15246. (tai(hp1).typ = ait_instruction) and
  15247. GetNextInstruction(p,hp2) and
  15248. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15249. case taicpu(hp1).opcode Of
  15250. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15251. { These two instructions set the zero flag if the result is zero }
  15252. A_POPCNT, A_LZCNT:
  15253. begin
  15254. if (
  15255. { With POPCNT, an input of zero will set the zero flag
  15256. because the population count of zero is zero }
  15257. (taicpu(hp1).opcode = A_POPCNT) and
  15258. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15259. (
  15260. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15261. { Faster than going through the second half of the 'or'
  15262. condition below }
  15263. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15264. )
  15265. ) or (
  15266. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15267. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15268. { and in case of carry for A(E)/B(E)/C/NC }
  15269. (
  15270. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15271. (
  15272. (taicpu(hp1).opcode <> A_ADD) and
  15273. (taicpu(hp1).opcode <> A_SUB) and
  15274. (taicpu(hp1).opcode <> A_LZCNT)
  15275. )
  15276. )
  15277. ) then
  15278. begin
  15279. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15280. RemoveCurrentP(p, hp2);
  15281. Result:=true;
  15282. Exit;
  15283. end;
  15284. end;
  15285. A_SHL, A_SAL, A_SHR, A_SAR:
  15286. begin
  15287. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15288. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15289. { therefore, it's only safe to do this optimization for }
  15290. { shifts by a (nonzero) constant }
  15291. (taicpu(hp1).oper[0]^.typ = top_const) and
  15292. (taicpu(hp1).oper[0]^.val <> 0) and
  15293. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15294. { and in case of carry for A(E)/B(E)/C/NC }
  15295. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15296. begin
  15297. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15298. RemoveCurrentP(p, hp2);
  15299. Result:=true;
  15300. Exit;
  15301. end;
  15302. end;
  15303. A_DEC, A_INC, A_NEG:
  15304. begin
  15305. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15306. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15307. { and in case of carry for A(E)/B(E)/C/NC }
  15308. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15309. begin
  15310. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15311. RemoveCurrentP(p, hp2);
  15312. Result:=true;
  15313. Exit;
  15314. end;
  15315. end;
  15316. A_ANDN, A_BZHI:
  15317. begin
  15318. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15319. { Only the zero and sign flags are consistent with what the result is }
  15320. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15321. begin
  15322. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15323. RemoveCurrentP(p, hp2);
  15324. Result:=true;
  15325. Exit;
  15326. end;
  15327. end;
  15328. A_BEXTR:
  15329. begin
  15330. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15331. { Only the zero flag is set }
  15332. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15333. begin
  15334. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15335. RemoveCurrentP(p, hp2);
  15336. Result:=true;
  15337. Exit;
  15338. end;
  15339. end;
  15340. else
  15341. ;
  15342. end; { case }
  15343. { change "test $-1,%reg" into "test %reg,%reg" }
  15344. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15345. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15346. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15347. if MatchInstruction(p, A_OR, []) and
  15348. { Can only match if they're both registers }
  15349. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15350. begin
  15351. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15352. taicpu(p).opcode := A_TEST;
  15353. { No need to set Result to True, as we've done all the optimisations we can }
  15354. end;
  15355. end;
  15356. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15357. var
  15358. hp1,hp3 : tai;
  15359. {$ifndef x86_64}
  15360. hp2 : taicpu;
  15361. {$endif x86_64}
  15362. begin
  15363. Result:=false;
  15364. hp3:=nil;
  15365. {$ifndef x86_64}
  15366. { don't do this on modern CPUs, this really hurts them due to
  15367. broken call/ret pairing }
  15368. if (current_settings.optimizecputype < cpu_Pentium2) and
  15369. not(cs_create_pic in current_settings.moduleswitches) and
  15370. GetNextInstruction(p, hp1) and
  15371. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15372. MatchOpType(taicpu(hp1),top_ref) and
  15373. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15374. begin
  15375. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15376. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15377. InsertLLItem(p.previous, p, hp2);
  15378. taicpu(p).opcode := A_JMP;
  15379. taicpu(p).is_jmp := true;
  15380. RemoveInstruction(hp1);
  15381. Result:=true;
  15382. end
  15383. else
  15384. {$endif x86_64}
  15385. { replace
  15386. call procname
  15387. ret
  15388. by
  15389. jmp procname
  15390. but do it only on level 4 because it destroys stack back traces
  15391. else if the subroutine is marked as no return, remove the ret
  15392. }
  15393. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15394. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15395. GetNextInstruction(p, hp1) and
  15396. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15397. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15398. SetAndTest(hp1,hp3) and
  15399. GetNextInstruction(hp1,hp1) and
  15400. MatchInstruction(hp1,A_RET,[S_NO])
  15401. )
  15402. ) and
  15403. (taicpu(hp1).ops=0) then
  15404. begin
  15405. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15406. { we might destroy stack alignment here if we do not do a call }
  15407. (target_info.stackalign<=sizeof(SizeUInt)) then
  15408. begin
  15409. taicpu(p).opcode := A_JMP;
  15410. taicpu(p).is_jmp := true;
  15411. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15412. end
  15413. else
  15414. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15415. RemoveInstruction(hp1);
  15416. if Assigned(hp3) then
  15417. begin
  15418. AsmL.Remove(hp3);
  15419. AsmL.InsertBefore(hp3,p)
  15420. end;
  15421. Result:=true;
  15422. end;
  15423. end;
  15424. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15425. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15426. begin
  15427. case OpSize of
  15428. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15429. Result := (Val <= $FF) and (Val >= -128);
  15430. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15431. Result := (Val <= $FFFF) and (Val >= -32768);
  15432. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15433. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15434. else
  15435. Result := True;
  15436. end;
  15437. end;
  15438. var
  15439. hp1, hp2 : tai;
  15440. SizeChange: Boolean;
  15441. PreMessage: string;
  15442. begin
  15443. Result := False;
  15444. if (taicpu(p).oper[0]^.typ = top_reg) and
  15445. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15446. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15447. begin
  15448. { Change (using movzbl %al,%eax as an example):
  15449. movzbl %al, %eax movzbl %al, %eax
  15450. cmpl x, %eax testl %eax,%eax
  15451. To:
  15452. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15453. movzbl %al, %eax movzbl %al, %eax
  15454. Smaller instruction and minimises pipeline stall as the CPU
  15455. doesn't have to wait for the register to get zero-extended. [Kit]
  15456. Also allow if the smaller of the two registers is being checked,
  15457. as this still removes the false dependency.
  15458. }
  15459. if
  15460. (
  15461. (
  15462. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15463. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15464. ) or (
  15465. { If MatchOperand returns True, they must both be registers }
  15466. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15467. )
  15468. ) and
  15469. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15470. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15471. begin
  15472. 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);
  15473. asml.Remove(hp1);
  15474. asml.InsertBefore(hp1, p);
  15475. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15476. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15477. begin
  15478. taicpu(hp1).opcode := A_TEST;
  15479. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15480. end;
  15481. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15482. case taicpu(p).opsize of
  15483. S_BW, S_BL:
  15484. begin
  15485. SizeChange := taicpu(hp1).opsize <> S_B;
  15486. taicpu(hp1).changeopsize(S_B);
  15487. end;
  15488. S_WL:
  15489. begin
  15490. SizeChange := taicpu(hp1).opsize <> S_W;
  15491. taicpu(hp1).changeopsize(S_W);
  15492. end
  15493. else
  15494. InternalError(2020112701);
  15495. end;
  15496. UpdateUsedRegs(tai(p.Next));
  15497. { Check if the register is used aferwards - if not, we can
  15498. remove the movzx instruction completely }
  15499. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15500. begin
  15501. { Hp1 is a better position than p for debugging purposes }
  15502. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15503. RemoveCurrentp(p, hp1);
  15504. Result := True;
  15505. end;
  15506. if SizeChange then
  15507. DebugMsg(SPeepholeOptimization + PreMessage +
  15508. 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)
  15509. else
  15510. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15511. Exit;
  15512. end;
  15513. { Change (using movzwl %ax,%eax as an example):
  15514. movzwl %ax, %eax
  15515. movb %al, (dest) (Register is smaller than read register in movz)
  15516. To:
  15517. movb %al, (dest) (Move one back to avoid a false dependency)
  15518. movzwl %ax, %eax
  15519. }
  15520. if (taicpu(hp1).opcode = A_MOV) and
  15521. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15522. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15523. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15524. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15525. begin
  15526. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15527. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15528. asml.Remove(hp1);
  15529. asml.InsertBefore(hp1, p);
  15530. if taicpu(hp1).oper[1]^.typ = top_reg then
  15531. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15532. { Check if the register is used aferwards - if not, we can
  15533. remove the movzx instruction completely }
  15534. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15535. begin
  15536. { Hp1 is a better position than p for debugging purposes }
  15537. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15538. RemoveCurrentp(p, hp1);
  15539. Result := True;
  15540. end;
  15541. Exit;
  15542. end;
  15543. end;
  15544. end;
  15545. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15546. var
  15547. hp1: tai;
  15548. {$ifdef x86_64}
  15549. PreMessage, RegName: string;
  15550. {$endif x86_64}
  15551. begin
  15552. Result := False;
  15553. { If x is a power of 2 (popcnt = 1), change:
  15554. xor $x, %reg/ref
  15555. To:
  15556. btc lb(x), %reg/ref
  15557. }
  15558. if IsBTXAcceptable(p) and
  15559. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15560. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15561. (
  15562. { Don't optimise if a test instruction follows }
  15563. not GetNextInstruction(p, hp1) or
  15564. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15565. ) then
  15566. begin
  15567. 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);
  15568. taicpu(p).opcode := A_BTC;
  15569. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15570. Result := True;
  15571. Exit;
  15572. end;
  15573. {$ifdef x86_64}
  15574. { Code size reduction by J. Gareth "Kit" Moreton }
  15575. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15576. as this removes the REX prefix }
  15577. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15578. Exit;
  15579. if taicpu(p).oper[0]^.typ <> top_reg then
  15580. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15581. InternalError(2018011500);
  15582. case taicpu(p).opsize of
  15583. S_Q:
  15584. begin
  15585. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15586. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15587. { The actual optimization }
  15588. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15589. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15590. taicpu(p).changeopsize(S_L);
  15591. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15592. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15593. end;
  15594. else
  15595. ;
  15596. end;
  15597. {$endif x86_64}
  15598. end;
  15599. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15600. var
  15601. XReg: TRegister;
  15602. begin
  15603. Result := False;
  15604. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15605. Smaller encoding and slightly faster on some platforms (also works for
  15606. ZMM-sized registers) }
  15607. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15608. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15609. begin
  15610. XReg := taicpu(p).oper[0]^.reg;
  15611. if (taicpu(p).oper[1]^.reg = XReg) then
  15612. begin
  15613. taicpu(p).changeopsize(S_XMM);
  15614. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15615. if (cs_opt_size in current_settings.optimizerswitches) then
  15616. begin
  15617. { Change input registers to %xmm0 to reduce size. Note that
  15618. there's a risk of a false dependency doing this, so only
  15619. optimise for size here }
  15620. XReg := NR_XMM0;
  15621. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15622. end
  15623. else
  15624. begin
  15625. setsubreg(XReg, R_SUBMMX);
  15626. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15627. end;
  15628. taicpu(p).oper[0]^.reg := XReg;
  15629. taicpu(p).oper[1]^.reg := XReg;
  15630. Result := True;
  15631. end;
  15632. end;
  15633. end;
  15634. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15635. var
  15636. OperIdx: Integer;
  15637. begin
  15638. for OperIdx := 0 to p.ops - 1 do
  15639. if p.oper[OperIdx]^.typ = top_ref then
  15640. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15641. end;
  15642. end.