aoptx86.pas 780 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. {$ifdef x86_64}
  118. { If a "mov %reg1d,%reg2d; and %reg1d,%reg1d" is found, we can possibly
  119. replace %reg2q with %reg1q in later instructions }
  120. function DoZeroUpper32Opt(var mov_p: tai; var and_p: tai): Boolean;
  121. {$endif x86_64}
  122. procedure DebugMsg(const s : string; p : tai);inline;
  123. class function IsExitCode(p : tai) : boolean; static;
  124. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  125. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  126. procedure RemoveLastDeallocForFuncRes(p : tai);
  127. function DoArithCombineOpt(var p : tai) : Boolean;
  128. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  129. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  130. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  131. function PrePeepholeOptSxx(var p : tai) : boolean;
  132. function PrePeepholeOptIMUL(var p : tai) : boolean;
  133. function PrePeepholeOptAND(var p : tai) : boolean;
  134. function OptPass1Test(var p: tai): boolean;
  135. function OptPass1Add(var p: tai): boolean;
  136. function OptPass1AND(var p : tai) : boolean;
  137. function OptPass1CMOVcc(var p: tai): Boolean;
  138. function OptPass1_V_MOVAP(var p : tai) : boolean;
  139. function OptPass1VOP(var p : tai) : boolean;
  140. function OptPass1MOV(var p : tai) : boolean;
  141. function OptPass1MOVD(var p : tai) : boolean;
  142. function OptPass1Movx(var p : tai) : boolean;
  143. function OptPass1MOVXX(var p : tai) : boolean;
  144. {$ifndef i8086}
  145. function OptPass1NOT(var p : tai) : boolean;
  146. {$endif not i8086}
  147. function OptPass1OP(var p : tai) : boolean;
  148. function OptPass1LEA(var p : tai) : boolean;
  149. function OptPass1Sub(var p : tai) : boolean;
  150. function OptPass1SHLSAL(var p : tai) : boolean;
  151. function OptPass1SHR(var p : tai) : boolean;
  152. function OptPass1FSTP(var p : tai) : boolean;
  153. function OptPass1FLD(var p : tai) : boolean;
  154. function OptPass1Cmp(var p : tai) : boolean;
  155. function OptPass1PXor(var p : tai) : boolean;
  156. function OptPass1VPXor(var p: tai): boolean;
  157. function OptPass1Imul(var p : tai) : boolean;
  158. function OptPass1Jcc(var p : tai) : boolean;
  159. function OptPass1SHXX(var p: tai): boolean;
  160. function OptPass1VMOVDQ(var p: tai): Boolean;
  161. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  162. function OptPass1STCCLC(var p: tai): Boolean;
  163. function OptPass2STCCLC(var p: tai): Boolean;
  164. function OptPass2CMOVcc(var p: tai): Boolean;
  165. function OptPass2Movx(var p : tai): Boolean;
  166. function OptPass2MOV(var p : tai) : boolean;
  167. function OptPass2Imul(var p : tai) : boolean;
  168. function OptPass2Jmp(var p : tai) : boolean;
  169. function OptPass2Jcc(var p : tai) : boolean;
  170. function OptPass2Lea(var p: tai): Boolean;
  171. function OptPass2SUB(var p: tai): Boolean;
  172. function OptPass2ADD(var p : tai): Boolean;
  173. function OptPass2SETcc(var p : tai) : boolean;
  174. function OptPass2Cmp(var p: tai): Boolean;
  175. function OptPass2Test(var p: tai): Boolean;
  176. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  177. function PostPeepholeOptMov(var p : tai) : Boolean;
  178. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  179. function PostPeepholeOptXor(var p : tai) : Boolean;
  180. function PostPeepholeOptAnd(var p : tai) : boolean;
  181. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  182. function PostPeepholeOptCmp(var p : tai) : Boolean;
  183. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  184. function PostPeepholeOptCall(var p : tai) : Boolean;
  185. function PostPeepholeOptLea(var p : tai) : Boolean;
  186. function PostPeepholeOptPush(var p: tai): Boolean;
  187. function PostPeepholeOptShr(var p : tai) : boolean;
  188. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  189. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  190. function PostPeepholeOptRET(var p: tai): Boolean;
  191. function PostPeepholeOptRORX(var p: tai): Boolean;
  192. function PostPeepholeOptSARXSHLXSHRX(var p: tai): Boolean;
  193. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  194. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  195. function TrySwapMovOp(var p, hp1: tai): Boolean;
  196. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  197. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  198. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  199. { Processor-dependent reference optimisation }
  200. class procedure OptimizeRefs(var p: taicpu); static;
  201. end;
  202. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  203. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  204. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  205. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  206. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  207. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  208. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  209. {$if max_operands>2}
  210. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  211. {$endif max_operands>2}
  212. function RefsEqual(const r1, r2: treference): boolean;
  213. { Like RefsEqual, but doesn't compare the offsets }
  214. function RefsAlmostEqual(const r1, r2: treference): boolean;
  215. { Note that Result is set to True if the references COULD overlap but the
  216. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  217. might still overlap because %reg2 could be equal to %reg1-4 }
  218. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  219. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  220. { returns true, if ref is a reference using only the registers passed as base and index
  221. and having an offset }
  222. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  223. implementation
  224. uses
  225. cutils,verbose,
  226. systems,
  227. globals,
  228. cpuinfo,
  229. procinfo,
  230. paramgr,
  231. aasmbase,
  232. aoptbase,aoptutils,
  233. symconst,symsym,
  234. cgx86,
  235. itcpugas;
  236. {$ifndef 8086}
  237. const
  238. MAX_CMOV_INSTRUCTIONS = 4;
  239. MAX_CMOV_REGISTERS = 8;
  240. type
  241. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  242. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  243. tsProcessed);
  244. { For OptPass2Jcc }
  245. TCMOVTracking = object
  246. private
  247. CMOVScore, ConstCount: LongInt;
  248. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  249. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  250. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  251. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  252. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  253. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  254. fOptimizer: TX86AsmOptimizer;
  255. fLabel: TAsmSymbol;
  256. fInsertionPoint,
  257. fCondition,
  258. fInitialJump,
  259. fFirstMovBlock,
  260. fFirstMovBlockStop,
  261. fSecondJump,
  262. fThirdJump,
  263. fSecondMovBlock,
  264. fSecondMovBlockStop,
  265. fMidLabel,
  266. fEndLabel,
  267. fAllocationRange: tai;
  268. fState: TCMovTrackingState;
  269. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  270. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  271. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  272. public
  273. RegisterTracking: TAllUsedRegs;
  274. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  275. destructor Done;
  276. procedure Process(out new_p: tai);
  277. property State: TCMovTrackingState read fState;
  278. end;
  279. PCMOVTracking = ^TCMOVTracking;
  280. {$endif 8086}
  281. {$ifdef DEBUG_AOPTCPU}
  282. const
  283. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  284. {$else DEBUG_AOPTCPU}
  285. { Empty strings help the optimizer to remove string concatenations that won't
  286. ever appear to the user on release builds. [Kit] }
  287. const
  288. SPeepholeOptimization = '';
  289. {$endif DEBUG_AOPTCPU}
  290. LIST_STEP_SIZE = 4;
  291. type
  292. TJumpTrackingItem = class(TLinkedListItem)
  293. private
  294. FSymbol: TAsmSymbol;
  295. FRefs: LongInt;
  296. public
  297. constructor Create(ASymbol: TAsmSymbol);
  298. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  299. property Symbol: TAsmSymbol read FSymbol;
  300. property Refs: LongInt read FRefs;
  301. end;
  302. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  303. begin
  304. inherited Create;
  305. FSymbol := ASymbol;
  306. FRefs := 0;
  307. end;
  308. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  309. begin
  310. Inc(FRefs);
  311. end;
  312. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  313. begin
  314. result :=
  315. (instr.typ = ait_instruction) and
  316. (taicpu(instr).opcode = op) and
  317. ((opsize = []) or (taicpu(instr).opsize in opsize));
  318. end;
  319. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  320. begin
  321. result :=
  322. (instr.typ = ait_instruction) and
  323. ((taicpu(instr).opcode = op1) or
  324. (taicpu(instr).opcode = op2)
  325. ) and
  326. ((opsize = []) or (taicpu(instr).opsize in opsize));
  327. end;
  328. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  329. begin
  330. result :=
  331. (instr.typ = ait_instruction) and
  332. ((taicpu(instr).opcode = op1) or
  333. (taicpu(instr).opcode = op2) or
  334. (taicpu(instr).opcode = op3)
  335. ) and
  336. ((opsize = []) or (taicpu(instr).opsize in opsize));
  337. end;
  338. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  339. const opsize : topsizes) : boolean;
  340. var
  341. op : TAsmOp;
  342. begin
  343. result:=false;
  344. if (instr.typ <> ait_instruction) or
  345. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  346. exit;
  347. for op in ops do
  348. begin
  349. if taicpu(instr).opcode = op then
  350. begin
  351. result:=true;
  352. exit;
  353. end;
  354. end;
  355. end;
  356. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  357. begin
  358. result := (oper.typ = top_reg) and (oper.reg = reg);
  359. end;
  360. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  361. begin
  362. result := (oper.typ = top_const) and (oper.val = a);
  363. end;
  364. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  365. begin
  366. result := oper1.typ = oper2.typ;
  367. if result then
  368. case oper1.typ of
  369. top_const:
  370. Result:=oper1.val = oper2.val;
  371. top_reg:
  372. Result:=oper1.reg = oper2.reg;
  373. top_ref:
  374. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  375. else
  376. internalerror(2013102801);
  377. end
  378. end;
  379. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  380. begin
  381. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  382. if result then
  383. case oper1.typ of
  384. top_const:
  385. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  386. top_reg:
  387. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  388. top_ref:
  389. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  390. else
  391. internalerror(2020052401);
  392. end
  393. end;
  394. function RefsEqual(const r1, r2: treference): boolean;
  395. begin
  396. RefsEqual :=
  397. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  398. (r1.relsymbol = r2.relsymbol) and
  399. (r1.segment = r2.segment) and (r1.base = r2.base) and
  400. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  401. (r1.offset = r2.offset) and
  402. (r1.volatility + r2.volatility = []);
  403. end;
  404. function RefsAlmostEqual(const r1, r2: treference): boolean;
  405. begin
  406. RefsAlmostEqual :=
  407. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  408. (r1.relsymbol = r2.relsymbol) and
  409. (r1.segment = r2.segment) and (r1.base = r2.base) and
  410. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  411. { Don't compare the offsets }
  412. (r1.volatility + r2.volatility = []);
  413. end;
  414. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  415. begin
  416. if (r1.symbol<>r2.symbol) then
  417. { If the index registers are different, there's a chance one could
  418. be set so it equals the other symbol }
  419. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  420. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  421. (r1.relsymbol = r2.relsymbol) and
  422. (r1.segment = r2.segment) and (r1.base = r2.base) and
  423. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  424. (r1.volatility + r2.volatility = []) then
  425. { In this case, it all depends on the offsets }
  426. Exit(abs(r1.offset - r2.offset) < Range);
  427. { There's a chance things MIGHT overlap, so take no chances }
  428. Result := True;
  429. end;
  430. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  431. begin
  432. Result:=(ref.offset=0) and
  433. (ref.scalefactor in [0,1]) and
  434. (ref.segment=NR_NO) and
  435. (ref.symbol=nil) and
  436. (ref.relsymbol=nil) and
  437. ((base=NR_INVALID) or
  438. (ref.base=base)) and
  439. ((index=NR_INVALID) or
  440. (ref.index=index)) and
  441. (ref.volatility=[]);
  442. end;
  443. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  444. begin
  445. Result:=(ref.scalefactor in [0,1]) and
  446. (ref.segment=NR_NO) and
  447. (ref.symbol=nil) and
  448. (ref.relsymbol=nil) and
  449. ((base=NR_INVALID) or
  450. (ref.base=base)) and
  451. ((index=NR_INVALID) or
  452. (ref.index=index)) and
  453. (ref.volatility=[]);
  454. end;
  455. function InstrReadsFlags(p: tai): boolean;
  456. begin
  457. InstrReadsFlags := true;
  458. case p.typ of
  459. ait_instruction:
  460. if InsProp[taicpu(p).opcode].Ch*
  461. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  462. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  463. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  464. exit;
  465. ait_label:
  466. exit;
  467. else
  468. ;
  469. end;
  470. InstrReadsFlags := false;
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  473. begin
  474. Next:=Current;
  475. repeat
  476. Result:=GetNextInstruction(Next,Next);
  477. until not (Result) or
  478. not(cs_opt_level3 in current_settings.optimizerswitches) or
  479. (Next.typ<>ait_instruction) or
  480. RegInInstruction(reg,Next) or
  481. is_calljmp(taicpu(Next).opcode);
  482. end;
  483. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  484. var
  485. GetNextResult: Boolean;
  486. begin
  487. Result:=0;
  488. Next:=Current;
  489. repeat
  490. GetNextResult := GetNextInstruction(Next,Next);
  491. if GetNextResult then
  492. Inc(Result)
  493. else
  494. { Must return zero upon hitting the end of the linked list without a match }
  495. Result := 0;
  496. until not (GetNextResult) or
  497. not(cs_opt_level3 in current_settings.optimizerswitches) or
  498. (Next.typ<>ait_instruction) or
  499. RegInInstruction(reg,Next) or
  500. is_calljmp(taicpu(Next).opcode);
  501. end;
  502. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  503. procedure TrackJump(Symbol: TAsmSymbol);
  504. var
  505. Search: TJumpTrackingItem;
  506. begin
  507. { See if an entry already exists in our jump tracking list
  508. (faster to search backwards due to the higher chance of
  509. matching destinations) }
  510. Search := TJumpTrackingItem(JumpTracking.Last);
  511. while Assigned(Search) do
  512. begin
  513. if Search.Symbol = Symbol then
  514. begin
  515. { Found it - remove it so it can be pushed to the front }
  516. JumpTracking.Remove(Search);
  517. Break;
  518. end;
  519. Search := TJumpTrackingItem(Search.Previous);
  520. end;
  521. if not Assigned(Search) then
  522. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  523. JumpTracking.Concat(Search);
  524. Search.IncRefs;
  525. end;
  526. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  527. var
  528. Search: TJumpTrackingItem;
  529. begin
  530. Result := False;
  531. { See if this label appears in the tracking list }
  532. Search := TJumpTrackingItem(JumpTracking.Last);
  533. while Assigned(Search) do
  534. begin
  535. if Search.Symbol = Symbol then
  536. begin
  537. { Found it - let's see what we can discover }
  538. if Search.Symbol.getrefs = Search.Refs then
  539. begin
  540. { Success - all the references are accounted for }
  541. JumpTracking.Remove(Search);
  542. Search.Free;
  543. { It is logically impossible for CrossJump to be false here
  544. because we must have run into a conditional jump for
  545. this label at some point }
  546. if not CrossJump then
  547. InternalError(2022041710);
  548. if JumpTracking.First = nil then
  549. { Tracking list is now empty - no more cross jumps }
  550. CrossJump := False;
  551. Result := True;
  552. Exit;
  553. end;
  554. { If the references don't match, it's possible to enter
  555. this label through other means, so drop out }
  556. Exit;
  557. end;
  558. Search := TJumpTrackingItem(Search.Previous);
  559. end;
  560. end;
  561. var
  562. Next_Label: tai;
  563. begin
  564. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  565. Next := Current;
  566. repeat
  567. Result := GetNextInstruction(Next,Next);
  568. if not Result then
  569. Break;
  570. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  571. if is_calljmpuncondret(taicpu(Next).opcode) then
  572. begin
  573. if (taicpu(Next).opcode = A_JMP) and
  574. { Remove dead code now to save time }
  575. RemoveDeadCodeAfterJump(taicpu(Next)) then
  576. { A jump was removed, but not the current instruction, and
  577. Result doesn't necessarily translate into an optimisation
  578. routine's Result, so use the "Force New Iteration" flag so
  579. mark a new pass }
  580. Include(OptsToCheck, aoc_ForceNewIteration);
  581. if not Assigned(JumpTracking) then
  582. begin
  583. { Cross-label optimisations often causes other optimisations
  584. to perform worse because they're not given the chance to
  585. optimise locally. In this case, don't do the cross-label
  586. optimisations yet, but flag them as a potential possibility
  587. for the next iteration of Pass 1 }
  588. if not NotFirstIteration then
  589. Include(OptsToCheck, aoc_ForceNewIteration);
  590. end
  591. else if IsJumpToLabel(taicpu(Next)) and
  592. GetNextInstruction(Next, Next_Label) then
  593. begin
  594. { If we have JMP .lbl, and the label after it has all of its
  595. references tracked, then this is probably an if-else style of
  596. block and we can keep tracking. If the label for this jump
  597. then appears later and is fully tracked, then it's the end
  598. of the if-else blocks and the code paths converge (thus
  599. marking the end of the cross-jump) }
  600. if (Next_Label.typ = ait_label) then
  601. begin
  602. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  603. begin
  604. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  605. Next := Next_Label;
  606. { CrossJump gets set to false by LabelAccountedFor if the
  607. list is completely emptied (as it indicates that all
  608. code paths have converged). We could avoid this nuance
  609. by moving the TrackJump call to before the
  610. LabelAccountedFor call, but this is slower in situations
  611. where LabelAccountedFor would return False due to the
  612. creation of a new object that is not used and destroyed
  613. soon after. }
  614. CrossJump := True;
  615. Continue;
  616. end;
  617. end
  618. else if (Next_Label.typ <> ait_marker) then
  619. { We just did a RemoveDeadCodeAfterJump, so either we find
  620. a label, the end of the procedure or some kind of marker}
  621. InternalError(2022041720);
  622. end;
  623. Result := False;
  624. Exit;
  625. end
  626. else
  627. begin
  628. if not Assigned(JumpTracking) then
  629. begin
  630. { Cross-label optimisations often causes other optimisations
  631. to perform worse because they're not given the chance to
  632. optimise locally. In this case, don't do the cross-label
  633. optimisations yet, but flag them as a potential possibility
  634. for the next iteration of Pass 1 }
  635. if not NotFirstIteration then
  636. Include(OptsToCheck, aoc_ForceNewIteration);
  637. end
  638. else if IsJumpToLabel(taicpu(Next)) then
  639. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  640. else
  641. { Conditional jumps should always be a jump to label }
  642. InternalError(2022041701);
  643. CrossJump := True;
  644. Continue;
  645. end;
  646. if Next.typ = ait_label then
  647. begin
  648. if not Assigned(JumpTracking) then
  649. begin
  650. { Cross-label optimisations often causes other optimisations
  651. to perform worse because they're not given the chance to
  652. optimise locally. In this case, don't do the cross-label
  653. optimisations yet, but flag them as a potential possibility
  654. for the next iteration of Pass 1 }
  655. if not NotFirstIteration then
  656. Include(OptsToCheck, aoc_ForceNewIteration);
  657. end
  658. else if LabelAccountedFor(tai_label(Next).labsym) then
  659. Continue;
  660. { If we reach here, we're at a label that hasn't been seen before
  661. (or JumpTracking was nil) }
  662. Break;
  663. end;
  664. until not Result or
  665. not (cs_opt_level3 in current_settings.optimizerswitches) or
  666. not (Next.typ in [ait_label, ait_instruction]) or
  667. RegInInstruction(reg,Next);
  668. end;
  669. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  670. begin
  671. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  672. begin
  673. Result:=GetNextInstruction(Current,Next);
  674. exit;
  675. end;
  676. Next:=tai(Current.Next);
  677. Result:=false;
  678. while assigned(Next) do
  679. begin
  680. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  681. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  682. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  683. exit
  684. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  685. begin
  686. Result:=true;
  687. exit;
  688. end;
  689. Next:=tai(Next.Next);
  690. end;
  691. end;
  692. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  693. begin
  694. Result:=RegReadByInstruction(reg,hp);
  695. end;
  696. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  697. var
  698. p: taicpu;
  699. opcount: longint;
  700. begin
  701. RegReadByInstruction := false;
  702. if hp.typ <> ait_instruction then
  703. exit;
  704. p := taicpu(hp);
  705. case p.opcode of
  706. A_CALL:
  707. regreadbyinstruction := true;
  708. A_IMUL:
  709. case p.ops of
  710. 1:
  711. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  712. (
  713. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  714. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  715. );
  716. 2,3:
  717. regReadByInstruction :=
  718. reginop(reg,p.oper[0]^) or
  719. reginop(reg,p.oper[1]^);
  720. else
  721. InternalError(2019112801);
  722. end;
  723. A_MUL:
  724. begin
  725. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  726. (
  727. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  728. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  729. );
  730. end;
  731. A_IDIV,A_DIV:
  732. begin
  733. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  734. (
  735. (getregtype(reg)=R_INTREGISTER) and
  736. (
  737. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  738. )
  739. );
  740. end;
  741. else
  742. begin
  743. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  744. begin
  745. RegReadByInstruction := false;
  746. exit;
  747. end;
  748. for opcount := 0 to p.ops-1 do
  749. if (p.oper[opCount]^.typ = top_ref) and
  750. RegInRef(reg,p.oper[opcount]^.ref^) then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. { special handling for SSE MOVSD }
  756. if (p.opcode=A_MOVSD) and (p.ops>0) then
  757. begin
  758. if p.ops<>2 then
  759. internalerror(2017042702);
  760. regReadByInstruction := reginop(reg,p.oper[0]^) or
  761. (
  762. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  763. );
  764. exit;
  765. end;
  766. with insprop[p.opcode] do
  767. begin
  768. case getregtype(reg) of
  769. R_INTREGISTER:
  770. begin
  771. case getsupreg(reg) of
  772. RS_EAX:
  773. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  774. begin
  775. RegReadByInstruction := true;
  776. exit
  777. end;
  778. RS_ECX:
  779. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  780. begin
  781. RegReadByInstruction := true;
  782. exit
  783. end;
  784. RS_EDX:
  785. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  786. begin
  787. RegReadByInstruction := true;
  788. exit
  789. end;
  790. RS_EBX:
  791. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  792. begin
  793. RegReadByInstruction := true;
  794. exit
  795. end;
  796. RS_ESP:
  797. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. RS_EBP:
  803. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  804. begin
  805. RegReadByInstruction := true;
  806. exit
  807. end;
  808. RS_ESI:
  809. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  810. begin
  811. RegReadByInstruction := true;
  812. exit
  813. end;
  814. RS_EDI:
  815. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  816. begin
  817. RegReadByInstruction := true;
  818. exit
  819. end;
  820. end;
  821. end;
  822. R_MMREGISTER:
  823. begin
  824. case getsupreg(reg) of
  825. RS_XMM0:
  826. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  827. begin
  828. RegReadByInstruction := true;
  829. exit
  830. end;
  831. end;
  832. end;
  833. else
  834. ;
  835. end;
  836. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  837. begin
  838. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  839. begin
  840. case p.condition of
  841. C_A,C_NBE, { CF=0 and ZF=0 }
  842. C_BE,C_NA: { CF=1 or ZF=1 }
  843. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  844. C_AE,C_NB,C_NC, { CF=0 }
  845. C_B,C_NAE,C_C: { CF=1 }
  846. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  847. C_NE,C_NZ, { ZF=0 }
  848. C_E,C_Z: { ZF=1 }
  849. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  850. C_G,C_NLE, { ZF=0 and SF=OF }
  851. C_LE,C_NG: { ZF=1 or SF<>OF }
  852. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  853. C_GE,C_NL, { SF=OF }
  854. C_L,C_NGE: { SF<>OF }
  855. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  856. C_NO, { OF=0 }
  857. C_O: { OF=1 }
  858. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  859. C_NP,C_PO, { PF=0 }
  860. C_P,C_PE: { PF=1 }
  861. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  862. C_NS, { SF=0 }
  863. C_S: { SF=1 }
  864. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  865. else
  866. internalerror(2017042701);
  867. end;
  868. if RegReadByInstruction then
  869. exit;
  870. end;
  871. case getsubreg(reg) of
  872. R_SUBW,R_SUBD,R_SUBQ:
  873. RegReadByInstruction :=
  874. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  875. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  876. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  877. R_SUBFLAGCARRY:
  878. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  879. R_SUBFLAGPARITY:
  880. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  881. R_SUBFLAGAUXILIARY:
  882. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  883. R_SUBFLAGZERO:
  884. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  885. R_SUBFLAGSIGN:
  886. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  887. R_SUBFLAGOVERFLOW:
  888. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  889. R_SUBFLAGINTERRUPT:
  890. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  891. R_SUBFLAGDIRECTION:
  892. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  893. else
  894. internalerror(2017042601);
  895. end;
  896. exit;
  897. end;
  898. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  899. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  900. (p.oper[0]^.reg=p.oper[1]^.reg) then
  901. exit;
  902. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  903. begin
  904. RegReadByInstruction := true;
  905. exit
  906. end;
  907. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  908. begin
  909. RegReadByInstruction := true;
  910. exit
  911. end;
  912. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  913. begin
  914. RegReadByInstruction := true;
  915. exit
  916. end;
  917. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  918. begin
  919. RegReadByInstruction := true;
  920. exit
  921. end;
  922. end;
  923. end;
  924. end;
  925. end;
  926. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  927. begin
  928. result:=false;
  929. if p1.typ<>ait_instruction then
  930. exit;
  931. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  932. exit(true);
  933. if (getregtype(reg)=R_INTREGISTER) and
  934. { change information for xmm movsd are not correct }
  935. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  936. begin
  937. { Handle instructions that behave differently depending on the size and operand count }
  938. case taicpu(p1).opcode of
  939. A_MUL, A_DIV, A_IDIV:
  940. if taicpu(p1).opsize = S_B then
  941. Result := (getsupreg(Reg) = RS_EAX)
  942. else
  943. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  944. A_IMUL:
  945. if taicpu(p1).ops = 1 then
  946. begin
  947. if taicpu(p1).opsize = S_B then
  948. Result := (getsupreg(Reg) = RS_EAX)
  949. else
  950. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  951. end;
  952. { If ops are greater than 1, call inherited method }
  953. else
  954. case getsupreg(reg) of
  955. { RS_EAX = RS_RAX on x86-64 }
  956. RS_EAX:
  957. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  958. RS_ECX:
  959. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  960. RS_EDX:
  961. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  962. RS_EBX:
  963. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  964. RS_ESP:
  965. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  966. RS_EBP:
  967. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. RS_ESI:
  969. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. RS_EDI:
  971. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. else
  973. ;
  974. end;
  975. end;
  976. if result then
  977. exit;
  978. end
  979. else if getregtype(reg)=R_MMREGISTER then
  980. begin
  981. case getsupreg(reg) of
  982. RS_XMM0:
  983. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  984. else
  985. ;
  986. end;
  987. if result then
  988. exit;
  989. end
  990. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  991. begin
  992. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  993. exit(true);
  994. case getsubreg(reg) of
  995. R_SUBFLAGCARRY:
  996. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  997. R_SUBFLAGPARITY:
  998. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  999. R_SUBFLAGAUXILIARY:
  1000. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1001. R_SUBFLAGZERO:
  1002. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1003. R_SUBFLAGSIGN:
  1004. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1005. R_SUBFLAGOVERFLOW:
  1006. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  1007. R_SUBFLAGINTERRUPT:
  1008. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1009. R_SUBFLAGDIRECTION:
  1010. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1011. R_SUBW,R_SUBD,R_SUBQ:
  1012. { Everything except the direction bits }
  1013. Result:=
  1014. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1015. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1016. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1017. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1018. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1019. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1020. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1021. else
  1022. ;
  1023. end;
  1024. if result then
  1025. exit;
  1026. end
  1027. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1028. exit(true);
  1029. Result:=inherited RegInInstruction(Reg, p1);
  1030. end;
  1031. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1032. const
  1033. WriteOps: array[0..3] of set of TInsChange =
  1034. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1035. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1036. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1037. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1038. var
  1039. OperIdx: Integer;
  1040. begin
  1041. Result := False;
  1042. if p1.typ <> ait_instruction then
  1043. exit;
  1044. with insprop[taicpu(p1).opcode] do
  1045. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1046. begin
  1047. case getsubreg(reg) of
  1048. R_SUBW,R_SUBD,R_SUBQ:
  1049. Result :=
  1050. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1051. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1052. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1053. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1054. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1055. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1056. R_SUBFLAGCARRY:
  1057. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1058. R_SUBFLAGPARITY:
  1059. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1060. R_SUBFLAGAUXILIARY:
  1061. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1062. R_SUBFLAGZERO:
  1063. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1064. R_SUBFLAGSIGN:
  1065. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1066. R_SUBFLAGOVERFLOW:
  1067. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1068. R_SUBFLAGINTERRUPT:
  1069. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1070. R_SUBFLAGDIRECTION:
  1071. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1072. else
  1073. internalerror(2017042602);
  1074. end;
  1075. exit;
  1076. end;
  1077. case taicpu(p1).opcode of
  1078. A_CALL:
  1079. { We could potentially set Result to False if the register in
  1080. question is non-volatile for the subroutine's calling convention,
  1081. but this would require detecting the calling convention in use and
  1082. also assuming that the routine doesn't contain malformed assembly
  1083. language, for example... so it could only be done under -O4 as it
  1084. would be considered a side-effect. [Kit] }
  1085. Result := True;
  1086. A_MOVSD:
  1087. { special handling for SSE MOVSD }
  1088. if (taicpu(p1).ops>0) then
  1089. begin
  1090. if taicpu(p1).ops<>2 then
  1091. internalerror(2017042703);
  1092. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1093. end;
  1094. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1095. so fix it here (FK)
  1096. }
  1097. A_VMOVSS,
  1098. A_VMOVSD:
  1099. begin
  1100. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1101. exit;
  1102. end;
  1103. A_MUL, A_DIV, A_IDIV:
  1104. begin
  1105. if taicpu(p1).opsize = S_B then
  1106. Result := (getsupreg(Reg) = RS_EAX)
  1107. else
  1108. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1109. end;
  1110. A_IMUL:
  1111. begin
  1112. if taicpu(p1).ops = 1 then
  1113. begin
  1114. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1115. end
  1116. else
  1117. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1118. Exit;
  1119. end;
  1120. else
  1121. ;
  1122. end;
  1123. if Result then
  1124. exit;
  1125. with insprop[taicpu(p1).opcode] do
  1126. begin
  1127. if getregtype(reg)=R_INTREGISTER then
  1128. begin
  1129. case getsupreg(reg) of
  1130. RS_EAX:
  1131. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1132. begin
  1133. Result := True;
  1134. exit
  1135. end;
  1136. RS_ECX:
  1137. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1138. begin
  1139. Result := True;
  1140. exit
  1141. end;
  1142. RS_EDX:
  1143. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1144. begin
  1145. Result := True;
  1146. exit
  1147. end;
  1148. RS_EBX:
  1149. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1150. begin
  1151. Result := True;
  1152. exit
  1153. end;
  1154. RS_ESP:
  1155. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1156. begin
  1157. Result := True;
  1158. exit
  1159. end;
  1160. RS_EBP:
  1161. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1162. begin
  1163. Result := True;
  1164. exit
  1165. end;
  1166. RS_ESI:
  1167. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1168. begin
  1169. Result := True;
  1170. exit
  1171. end;
  1172. RS_EDI:
  1173. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1174. begin
  1175. Result := True;
  1176. exit
  1177. end;
  1178. end;
  1179. end;
  1180. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1181. if (WriteOps[OperIdx]*Ch<>[]) and
  1182. { The register doesn't get modified inside a reference }
  1183. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1184. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1185. begin
  1186. Result := true;
  1187. exit
  1188. end;
  1189. end;
  1190. end;
  1191. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1192. const
  1193. WriteOps: array[0..3] of set of TInsChange =
  1194. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1195. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1196. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1197. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1198. var
  1199. X: Integer;
  1200. CurrentP1Size: asizeint;
  1201. begin
  1202. Result := (
  1203. (Ref.base <> NR_NO) and
  1204. {$ifdef x86_64}
  1205. (Ref.base <> NR_RIP) and
  1206. {$endif x86_64}
  1207. RegModifiedBetween(Ref.base, p1, p2)
  1208. ) or
  1209. (
  1210. (Ref.index <> NR_NO) and
  1211. (Ref.index <> Ref.base) and
  1212. RegModifiedBetween(Ref.index, p1, p2)
  1213. );
  1214. { Now check to see if the memory itself is written to }
  1215. if not Result then
  1216. begin
  1217. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1218. if p1.typ = ait_instruction then
  1219. begin
  1220. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1221. with insprop[taicpu(p1).opcode] do
  1222. for X := 0 to taicpu(p1).ops - 1 do
  1223. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1224. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1225. { Catch any potential overlaps }
  1226. (
  1227. (RefSize = 0) or
  1228. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1229. ) and
  1230. (
  1231. (CurrentP1Size = 0) or
  1232. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1233. ) and
  1234. { Reference is used, but does the instruction write to it? }
  1235. (
  1236. (Ch_All in Ch) or
  1237. ((WriteOps[X] * Ch) <> [])
  1238. ) then
  1239. begin
  1240. Result := True;
  1241. Break;
  1242. end;
  1243. end;
  1244. end;
  1245. end;
  1246. {$ifdef DEBUG_AOPTCPU}
  1247. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1248. begin
  1249. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1250. end;
  1251. function debug_tostr(i: tcgint): string; inline;
  1252. begin
  1253. Result := tostr(i);
  1254. end;
  1255. function debug_hexstr(i: tcgint): string;
  1256. begin
  1257. Result := '0x';
  1258. case i of
  1259. 0..$FF:
  1260. Result := Result + hexstr(i, 2);
  1261. $100..$FFFF:
  1262. Result := Result + hexstr(i, 4);
  1263. $10000..$FFFFFF:
  1264. Result := Result + hexstr(i, 6);
  1265. $1000000..$FFFFFFFF:
  1266. Result := Result + hexstr(i, 8);
  1267. else
  1268. Result := Result + hexstr(i, 16);
  1269. end;
  1270. end;
  1271. function debug_regname(r: TRegister): string; inline;
  1272. begin
  1273. Result := '%' + std_regname(r);
  1274. end;
  1275. { Debug output function - creates a string representation of an operator }
  1276. function debug_operstr(oper: TOper): string;
  1277. begin
  1278. case oper.typ of
  1279. top_const:
  1280. Result := '$' + debug_tostr(oper.val);
  1281. top_reg:
  1282. Result := debug_regname(oper.reg);
  1283. top_ref:
  1284. begin
  1285. if oper.ref^.offset <> 0 then
  1286. Result := debug_tostr(oper.ref^.offset) + '('
  1287. else
  1288. Result := '(';
  1289. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1290. begin
  1291. Result := Result + debug_regname(oper.ref^.base);
  1292. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1293. Result := Result + ',' + debug_regname(oper.ref^.index);
  1294. end
  1295. else
  1296. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1297. Result := Result + debug_regname(oper.ref^.index);
  1298. if (oper.ref^.scalefactor > 1) then
  1299. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1300. else
  1301. Result := Result + ')';
  1302. end;
  1303. else
  1304. Result := '[UNKNOWN]';
  1305. end;
  1306. end;
  1307. function debug_op2str(opcode: tasmop): string; inline;
  1308. begin
  1309. Result := std_op2str[opcode];
  1310. end;
  1311. function debug_opsize2str(opsize: topsize): string; inline;
  1312. begin
  1313. Result := gas_opsize2str[opsize];
  1314. end;
  1315. {$else DEBUG_AOPTCPU}
  1316. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1317. begin
  1318. end;
  1319. function debug_tostr(i: tcgint): string; inline;
  1320. begin
  1321. Result := '';
  1322. end;
  1323. function debug_hexstr(i: tcgint): string; inline;
  1324. begin
  1325. Result := '';
  1326. end;
  1327. function debug_regname(r: TRegister): string; inline;
  1328. begin
  1329. Result := '';
  1330. end;
  1331. function debug_operstr(oper: TOper): string; inline;
  1332. begin
  1333. Result := '';
  1334. end;
  1335. function debug_op2str(opcode: tasmop): string; inline;
  1336. begin
  1337. Result := '';
  1338. end;
  1339. function debug_opsize2str(opsize: topsize): string; inline;
  1340. begin
  1341. Result := '';
  1342. end;
  1343. {$endif DEBUG_AOPTCPU}
  1344. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1345. begin
  1346. {$ifdef x86_64}
  1347. { Always fine on x86-64 }
  1348. Result := True;
  1349. {$else x86_64}
  1350. Result :=
  1351. {$ifdef i8086}
  1352. (current_settings.cputype >= cpu_386) and
  1353. {$endif i8086}
  1354. (
  1355. { Always accept if optimising for size }
  1356. (cs_opt_size in current_settings.optimizerswitches) or
  1357. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1358. (current_settings.optimizecputype >= cpu_Pentium2)
  1359. );
  1360. {$endif x86_64}
  1361. end;
  1362. { Attempts to allocate a volatile integer register for use between p and hp,
  1363. using AUsedRegs for the current register usage information. Returns NR_NO
  1364. if no free register could be found }
  1365. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1366. var
  1367. RegSet: TCPURegisterSet;
  1368. CurrentSuperReg: Integer;
  1369. CurrentReg: TRegister;
  1370. Currentp: tai;
  1371. Breakout: Boolean;
  1372. begin
  1373. Result := NR_NO;
  1374. RegSet :=
  1375. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1376. current_procinfo.saved_regs_int;
  1377. (*
  1378. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1379. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1380. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1381. *)
  1382. for CurrentSuperReg in RegSet do
  1383. begin
  1384. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1385. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1386. {$if defined(i386) or defined(i8086)}
  1387. { If the target size is 8-bit, make sure we can actually encode it }
  1388. and (
  1389. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1390. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1391. )
  1392. {$endif i386 or i8086}
  1393. then
  1394. begin
  1395. Currentp := p;
  1396. Breakout := False;
  1397. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1398. begin
  1399. case Currentp.typ of
  1400. ait_instruction:
  1401. begin
  1402. if RegInInstruction(CurrentReg, Currentp) then
  1403. begin
  1404. Breakout := True;
  1405. Break;
  1406. end;
  1407. { Cannot allocate across an unconditional jump }
  1408. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1409. Exit;
  1410. end;
  1411. ait_marker:
  1412. { Don't try anything more if a marker is hit }
  1413. Exit;
  1414. ait_regalloc:
  1415. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1416. begin
  1417. Breakout := True;
  1418. Break;
  1419. end;
  1420. else
  1421. ;
  1422. end;
  1423. end;
  1424. if Breakout then
  1425. { Try the next register }
  1426. Continue;
  1427. { We have a free register available }
  1428. Result := CurrentReg;
  1429. if not DontAlloc then
  1430. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1431. Exit;
  1432. end;
  1433. end;
  1434. end;
  1435. { Attempts to allocate a volatile MM register for use between p and hp,
  1436. using AUsedRegs for the current register usage information. Returns NR_NO
  1437. if no free register could be found }
  1438. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1439. var
  1440. RegSet: TCPURegisterSet;
  1441. CurrentSuperReg: Integer;
  1442. CurrentReg: TRegister;
  1443. Currentp: tai;
  1444. Breakout: Boolean;
  1445. begin
  1446. Result := NR_NO;
  1447. RegSet :=
  1448. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1449. current_procinfo.saved_regs_mm;
  1450. for CurrentSuperReg in RegSet do
  1451. begin
  1452. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1453. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1454. begin
  1455. Currentp := p;
  1456. Breakout := False;
  1457. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1458. begin
  1459. case Currentp.typ of
  1460. ait_instruction:
  1461. begin
  1462. if RegInInstruction(CurrentReg, Currentp) then
  1463. begin
  1464. Breakout := True;
  1465. Break;
  1466. end;
  1467. { Cannot allocate across an unconditional jump }
  1468. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1469. Exit;
  1470. end;
  1471. ait_marker:
  1472. { Don't try anything more if a marker is hit }
  1473. Exit;
  1474. ait_regalloc:
  1475. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1476. begin
  1477. Breakout := True;
  1478. Break;
  1479. end;
  1480. else
  1481. ;
  1482. end;
  1483. end;
  1484. if Breakout then
  1485. { Try the next register }
  1486. Continue;
  1487. { We have a free register available }
  1488. Result := CurrentReg;
  1489. if not DontAlloc then
  1490. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1491. Exit;
  1492. end;
  1493. end;
  1494. end;
  1495. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1496. begin
  1497. if not SuperRegistersEqual(reg1,reg2) then
  1498. exit(false);
  1499. if getregtype(reg1)<>R_INTREGISTER then
  1500. exit(true); {because SuperRegisterEqual is true}
  1501. case getsubreg(reg1) of
  1502. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1503. higher, it preserves the high bits, so the new value depends on
  1504. reg2's previous value. In other words, it is equivalent to doing:
  1505. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1506. R_SUBL:
  1507. exit(getsubreg(reg2)=R_SUBL);
  1508. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1509. higher, it actually does a:
  1510. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1511. R_SUBH:
  1512. exit(getsubreg(reg2)=R_SUBH);
  1513. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1514. bits of reg2:
  1515. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1516. R_SUBW:
  1517. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1518. { a write to R_SUBD always overwrites every other subregister,
  1519. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1520. R_SUBD,
  1521. R_SUBQ:
  1522. exit(true);
  1523. else
  1524. internalerror(2017042801);
  1525. end;
  1526. end;
  1527. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1528. begin
  1529. if not SuperRegistersEqual(reg1,reg2) then
  1530. exit(false);
  1531. if getregtype(reg1)<>R_INTREGISTER then
  1532. exit(true); {because SuperRegisterEqual is true}
  1533. case getsubreg(reg1) of
  1534. R_SUBL:
  1535. exit(getsubreg(reg2)<>R_SUBH);
  1536. R_SUBH:
  1537. exit(getsubreg(reg2)<>R_SUBL);
  1538. R_SUBW,
  1539. R_SUBD,
  1540. R_SUBQ:
  1541. exit(true);
  1542. else
  1543. internalerror(2017042802);
  1544. end;
  1545. end;
  1546. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1547. var
  1548. hp1 : tai;
  1549. l : TCGInt;
  1550. begin
  1551. result:=false;
  1552. if not(GetNextInstruction(p, hp1)) then
  1553. exit;
  1554. { changes the code sequence
  1555. shr/sar const1, x
  1556. shl const2, x
  1557. to
  1558. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1559. if (taicpu(p).oper[0]^.typ = top_const) and
  1560. MatchInstruction(hp1,A_SHL,[]) and
  1561. (taicpu(hp1).oper[0]^.typ = top_const) and
  1562. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1563. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1564. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1565. begin
  1566. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1567. not(cs_opt_size in current_settings.optimizerswitches)
  1568. {$ifdef x86_64}
  1569. and (
  1570. (taicpu(p).opsize <> S_Q) or
  1571. { 64-bit AND can only store signed 32-bit immediates }
  1572. (taicpu(p).oper[0]^.val < 32)
  1573. )
  1574. {$endif x86_64}
  1575. then
  1576. begin
  1577. { shr/sar const1, %reg
  1578. shl const2, %reg
  1579. with const1 > const2 }
  1580. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1581. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1582. taicpu(hp1).opcode := A_AND;
  1583. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1584. case taicpu(p).opsize Of
  1585. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1586. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1587. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1588. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1589. else
  1590. Internalerror(2017050703)
  1591. end;
  1592. end
  1593. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1594. not(cs_opt_size in current_settings.optimizerswitches)
  1595. {$ifdef x86_64}
  1596. and (
  1597. (taicpu(p).opsize <> S_Q) or
  1598. { 64-bit AND can only store signed 32-bit immediates }
  1599. (taicpu(p).oper[0]^.val < 32)
  1600. )
  1601. {$endif x86_64}
  1602. then
  1603. begin
  1604. { shr/sar const1, %reg
  1605. shl const2, %reg
  1606. with const1 < const2 }
  1607. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1608. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1609. taicpu(p).opcode := A_AND;
  1610. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1611. case taicpu(p).opsize Of
  1612. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1613. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1614. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1615. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1616. else
  1617. Internalerror(2017050702)
  1618. end;
  1619. end
  1620. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1621. {$ifdef x86_64}
  1622. and (
  1623. (taicpu(p).opsize <> S_Q) or
  1624. { 64-bit AND can only store signed 32-bit immediates }
  1625. (taicpu(p).oper[0]^.val < 32)
  1626. )
  1627. {$endif x86_64}
  1628. then
  1629. begin
  1630. { shr/sar const1, %reg
  1631. shl const2, %reg
  1632. with const1 = const2 }
  1633. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1634. taicpu(p).opcode := A_AND;
  1635. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1636. case taicpu(p).opsize Of
  1637. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1638. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1639. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1640. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1641. else
  1642. Internalerror(2017050701)
  1643. end;
  1644. RemoveInstruction(hp1);
  1645. end;
  1646. end;
  1647. end;
  1648. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1649. var
  1650. opsize : topsize;
  1651. hp1, hp2 : tai;
  1652. tmpref : treference;
  1653. ShiftValue : Cardinal;
  1654. BaseValue : TCGInt;
  1655. begin
  1656. result:=false;
  1657. opsize:=taicpu(p).opsize;
  1658. { changes certain "imul const, %reg"'s to lea sequences }
  1659. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1660. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1661. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1662. if (taicpu(p).oper[0]^.val = 1) then
  1663. if (taicpu(p).ops = 2) then
  1664. { remove "imul $1, reg" }
  1665. begin
  1666. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1667. Result := RemoveCurrentP(p);
  1668. end
  1669. else
  1670. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1671. begin
  1672. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1673. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1674. asml.InsertAfter(hp1, p);
  1675. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1676. RemoveCurrentP(p, hp1);
  1677. Result := True;
  1678. end
  1679. else if ((taicpu(p).ops <= 2) or
  1680. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1681. not(cs_opt_size in current_settings.optimizerswitches) and
  1682. (not(GetNextInstruction(p, hp1)) or
  1683. not((tai(hp1).typ = ait_instruction) and
  1684. ((taicpu(hp1).opcode=A_Jcc) and
  1685. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1686. begin
  1687. {
  1688. imul X, reg1, reg2 to
  1689. lea (reg1,reg1,Y), reg2
  1690. shl ZZ,reg2
  1691. imul XX, reg1 to
  1692. lea (reg1,reg1,YY), reg1
  1693. shl ZZ,reg2
  1694. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1695. it does not exist as a separate optimization target in FPC though.
  1696. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1697. at most two zeros
  1698. }
  1699. reference_reset(tmpref,1,[]);
  1700. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1701. begin
  1702. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1703. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1704. TmpRef.base := taicpu(p).oper[1]^.reg;
  1705. TmpRef.index := taicpu(p).oper[1]^.reg;
  1706. if not(BaseValue in [3,5,9]) then
  1707. Internalerror(2018110101);
  1708. TmpRef.ScaleFactor := BaseValue-1;
  1709. if (taicpu(p).ops = 2) then
  1710. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1711. else
  1712. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1713. AsmL.InsertAfter(hp1,p);
  1714. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1715. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1716. RemoveCurrentP(p, hp1);
  1717. if ShiftValue>0 then
  1718. begin
  1719. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1720. AsmL.InsertAfter(hp2,hp1);
  1721. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1722. end;
  1723. Result := True;
  1724. end;
  1725. end;
  1726. end;
  1727. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1728. begin
  1729. Result := False;
  1730. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1731. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1732. begin
  1733. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1734. taicpu(p).opcode := A_MOV;
  1735. Result := True;
  1736. end;
  1737. end;
  1738. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1739. var
  1740. p: taicpu absolute hp; { Implicit typecast }
  1741. i: Integer;
  1742. begin
  1743. Result := False;
  1744. if not assigned(hp) or
  1745. (hp.typ <> ait_instruction) then
  1746. Exit;
  1747. Prefetch(insprop[p.opcode]);
  1748. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1749. with insprop[p.opcode] do
  1750. begin
  1751. case getsubreg(reg) of
  1752. R_SUBW,R_SUBD,R_SUBQ:
  1753. Result:=
  1754. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1755. uncommon flags are checked first }
  1756. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1757. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1758. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1759. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1760. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1761. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1762. R_SUBFLAGCARRY:
  1763. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1764. R_SUBFLAGPARITY:
  1765. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1766. R_SUBFLAGAUXILIARY:
  1767. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1768. R_SUBFLAGZERO:
  1769. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1770. R_SUBFLAGSIGN:
  1771. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1772. R_SUBFLAGOVERFLOW:
  1773. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1774. R_SUBFLAGINTERRUPT:
  1775. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1776. R_SUBFLAGDIRECTION:
  1777. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1778. else
  1779. internalerror(2017050501);
  1780. end;
  1781. exit;
  1782. end;
  1783. { Handle special cases first }
  1784. case p.opcode of
  1785. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1786. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1787. begin
  1788. Result :=
  1789. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1790. (p.oper[1]^.typ = top_reg) and
  1791. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1792. (
  1793. (p.oper[0]^.typ = top_const) or
  1794. (
  1795. (p.oper[0]^.typ = top_reg) and
  1796. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1797. ) or (
  1798. (p.oper[0]^.typ = top_ref) and
  1799. not RegInRef(reg,p.oper[0]^.ref^)
  1800. )
  1801. );
  1802. end;
  1803. A_MUL, A_IMUL:
  1804. Result :=
  1805. (
  1806. (p.ops=3) and { IMUL only }
  1807. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1808. (
  1809. (
  1810. (p.oper[1]^.typ=top_reg) and
  1811. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1812. ) or (
  1813. (p.oper[1]^.typ=top_ref) and
  1814. not RegInRef(reg,p.oper[1]^.ref^)
  1815. )
  1816. )
  1817. ) or (
  1818. (
  1819. (p.ops=1) and
  1820. (
  1821. (
  1822. (
  1823. (p.oper[0]^.typ=top_reg) and
  1824. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1825. )
  1826. ) or (
  1827. (p.oper[0]^.typ=top_ref) and
  1828. not RegInRef(reg,p.oper[0]^.ref^)
  1829. )
  1830. ) and (
  1831. (
  1832. (p.opsize=S_B) and
  1833. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1834. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1835. ) or (
  1836. (p.opsize=S_W) and
  1837. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1838. ) or (
  1839. (p.opsize=S_L) and
  1840. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1841. {$ifdef x86_64}
  1842. ) or (
  1843. (p.opsize=S_Q) and
  1844. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1845. {$endif x86_64}
  1846. )
  1847. )
  1848. )
  1849. );
  1850. A_CBW:
  1851. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1852. {$ifndef x86_64}
  1853. A_LDS:
  1854. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1855. A_LES:
  1856. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1857. {$endif not x86_64}
  1858. A_LFS:
  1859. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1860. A_LGS:
  1861. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1862. A_LSS:
  1863. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1864. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1865. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1866. A_LODSB:
  1867. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1868. A_LODSW:
  1869. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1870. {$ifdef x86_64}
  1871. A_LODSQ:
  1872. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1873. {$endif x86_64}
  1874. A_LODSD:
  1875. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1876. A_FSTSW, A_FNSTSW:
  1877. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1878. else
  1879. begin
  1880. with insprop[p.opcode] do
  1881. begin
  1882. if (
  1883. { xor %reg,%reg etc. is classed as a new value }
  1884. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1885. MatchOpType(p, top_reg, top_reg) and
  1886. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1887. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1888. ) then
  1889. begin
  1890. Result := True;
  1891. Exit;
  1892. end;
  1893. { Make sure the entire register is overwritten }
  1894. if (getregtype(reg) = R_INTREGISTER) then
  1895. begin
  1896. if (p.ops > 0) then
  1897. begin
  1898. if RegInOp(reg, p.oper[0]^) then
  1899. begin
  1900. if (p.oper[0]^.typ = top_ref) then
  1901. begin
  1902. if RegInRef(reg, p.oper[0]^.ref^) then
  1903. begin
  1904. Result := False;
  1905. Exit;
  1906. end;
  1907. end
  1908. else if (p.oper[0]^.typ = top_reg) then
  1909. begin
  1910. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1911. begin
  1912. Result := False;
  1913. Exit;
  1914. end
  1915. else if ([Ch_WOp1]*Ch<>[]) then
  1916. begin
  1917. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1918. Result := True
  1919. else
  1920. begin
  1921. Result := False;
  1922. Exit;
  1923. end;
  1924. end;
  1925. end;
  1926. end;
  1927. if (p.ops > 1) then
  1928. begin
  1929. if RegInOp(reg, p.oper[1]^) then
  1930. begin
  1931. if (p.oper[1]^.typ = top_ref) then
  1932. begin
  1933. if RegInRef(reg, p.oper[1]^.ref^) then
  1934. begin
  1935. Result := False;
  1936. Exit;
  1937. end;
  1938. end
  1939. else if (p.oper[1]^.typ = top_reg) then
  1940. begin
  1941. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1942. begin
  1943. Result := False;
  1944. Exit;
  1945. end
  1946. else if ([Ch_WOp2]*Ch<>[]) then
  1947. begin
  1948. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1949. Result := True
  1950. else
  1951. begin
  1952. Result := False;
  1953. Exit;
  1954. end;
  1955. end;
  1956. end;
  1957. end;
  1958. if (p.ops > 2) then
  1959. begin
  1960. if RegInOp(reg, p.oper[2]^) then
  1961. begin
  1962. if (p.oper[2]^.typ = top_ref) then
  1963. begin
  1964. if RegInRef(reg, p.oper[2]^.ref^) then
  1965. begin
  1966. Result := False;
  1967. Exit;
  1968. end;
  1969. end
  1970. else if (p.oper[2]^.typ = top_reg) then
  1971. begin
  1972. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1973. begin
  1974. Result := False;
  1975. Exit;
  1976. end
  1977. else if ([Ch_WOp3]*Ch<>[]) then
  1978. begin
  1979. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1980. Result := True
  1981. else
  1982. begin
  1983. Result := False;
  1984. Exit;
  1985. end;
  1986. end;
  1987. end;
  1988. end;
  1989. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1990. begin
  1991. if (p.oper[3]^.typ = top_ref) then
  1992. begin
  1993. if RegInRef(reg, p.oper[3]^.ref^) then
  1994. begin
  1995. Result := False;
  1996. Exit;
  1997. end;
  1998. end
  1999. else if (p.oper[3]^.typ = top_reg) then
  2000. begin
  2001. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  2002. begin
  2003. Result := False;
  2004. Exit;
  2005. end
  2006. else if ([Ch_WOp4]*Ch<>[]) then
  2007. begin
  2008. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  2009. Result := True
  2010. else
  2011. begin
  2012. Result := False;
  2013. Exit;
  2014. end;
  2015. end;
  2016. end;
  2017. end;
  2018. end;
  2019. end;
  2020. end;
  2021. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2022. case getsupreg(reg) of
  2023. RS_EAX:
  2024. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2025. begin
  2026. Result := True;
  2027. Exit;
  2028. end;
  2029. RS_ECX:
  2030. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2031. begin
  2032. Result := True;
  2033. Exit;
  2034. end;
  2035. RS_EDX:
  2036. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2037. begin
  2038. Result := True;
  2039. Exit;
  2040. end;
  2041. RS_EBX:
  2042. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2043. begin
  2044. Result := True;
  2045. Exit;
  2046. end;
  2047. RS_ESP:
  2048. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2049. begin
  2050. Result := True;
  2051. Exit;
  2052. end;
  2053. RS_EBP:
  2054. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2055. begin
  2056. Result := True;
  2057. Exit;
  2058. end;
  2059. RS_ESI:
  2060. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2061. begin
  2062. Result := True;
  2063. Exit;
  2064. end;
  2065. RS_EDI:
  2066. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2067. begin
  2068. Result := True;
  2069. Exit;
  2070. end;
  2071. else
  2072. ;
  2073. end;
  2074. end;
  2075. end;
  2076. end;
  2077. end;
  2078. end;
  2079. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2080. var
  2081. hp2,hp3 : tai;
  2082. begin
  2083. { some x86-64 issue a NOP before the real exit code }
  2084. if MatchInstruction(p,A_NOP,[]) then
  2085. GetNextInstruction(p,p);
  2086. result:=assigned(p) and (p.typ=ait_instruction) and
  2087. ((taicpu(p).opcode = A_RET) or
  2088. ((taicpu(p).opcode=A_LEAVE) and
  2089. GetNextInstruction(p,hp2) and
  2090. MatchInstruction(hp2,A_RET,[S_NO])
  2091. ) or
  2092. (((taicpu(p).opcode=A_LEA) and
  2093. MatchOpType(taicpu(p),top_ref,top_reg) and
  2094. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2095. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2096. ) and
  2097. GetNextInstruction(p,hp2) and
  2098. MatchInstruction(hp2,A_RET,[S_NO])
  2099. ) or
  2100. ((((taicpu(p).opcode=A_MOV) and
  2101. MatchOpType(taicpu(p),top_reg,top_reg) and
  2102. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2103. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2104. ((taicpu(p).opcode=A_LEA) and
  2105. MatchOpType(taicpu(p),top_ref,top_reg) and
  2106. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2107. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2108. )
  2109. ) and
  2110. GetNextInstruction(p,hp2) and
  2111. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2112. MatchOpType(taicpu(hp2),top_reg) and
  2113. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2114. GetNextInstruction(hp2,hp3) and
  2115. MatchInstruction(hp3,A_RET,[S_NO])
  2116. )
  2117. );
  2118. end;
  2119. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2120. begin
  2121. isFoldableArithOp := False;
  2122. case hp1.opcode of
  2123. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2124. isFoldableArithOp :=
  2125. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2126. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2127. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2128. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2129. (taicpu(hp1).oper[1]^.reg = reg);
  2130. A_INC,A_DEC,A_NEG,A_NOT:
  2131. isFoldableArithOp :=
  2132. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2133. (taicpu(hp1).oper[0]^.reg = reg);
  2134. else
  2135. ;
  2136. end;
  2137. end;
  2138. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2139. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2140. var
  2141. hp2: tai;
  2142. begin
  2143. hp2 := p;
  2144. repeat
  2145. hp2 := tai(hp2.previous);
  2146. if assigned(hp2) and
  2147. (hp2.typ = ait_regalloc) and
  2148. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2149. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2150. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2151. begin
  2152. RemoveInstruction(hp2);
  2153. break;
  2154. end;
  2155. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2156. end;
  2157. begin
  2158. case current_procinfo.procdef.returndef.typ of
  2159. arraydef,recorddef,pointerdef,
  2160. stringdef,enumdef,procdef,objectdef,errordef,
  2161. filedef,setdef,procvardef,
  2162. classrefdef,forwarddef:
  2163. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2164. orddef:
  2165. if current_procinfo.procdef.returndef.size <> 0 then
  2166. begin
  2167. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2168. { for int64/qword }
  2169. if current_procinfo.procdef.returndef.size = 8 then
  2170. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2171. end;
  2172. else
  2173. ;
  2174. end;
  2175. end;
  2176. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2177. var
  2178. hp1: tai;
  2179. operswap: poper;
  2180. begin
  2181. Result := False;
  2182. { Optimise:
  2183. cmov(c) %reg1,%reg2
  2184. mov %reg2,%reg1
  2185. (%reg2 dealloc.)
  2186. To:
  2187. cmov(~c) %reg2,%reg1
  2188. }
  2189. if (taicpu(p).oper[0]^.typ = top_reg) then
  2190. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2191. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2192. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2193. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2194. begin
  2195. TransferUsedRegs(TmpUsedRegs);
  2196. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2197. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2198. begin
  2199. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2200. { Save time by swapping the pointers (they're both registers, so
  2201. we don't need to worry about reference counts) }
  2202. operswap := taicpu(p).oper[0];
  2203. taicpu(p).oper[0] := taicpu(p).oper[1];
  2204. taicpu(p).oper[1] := operswap;
  2205. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2206. RemoveInstruction(hp1);
  2207. { It's still a CMOV, so we can look further ahead }
  2208. Include(OptsToCheck, aoc_ForceNewIteration);
  2209. { But first, let's see if this will get optimised again
  2210. (probably won't happen, but best to be sure) }
  2211. Continue;
  2212. end;
  2213. Break;
  2214. end;
  2215. end;
  2216. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2217. var
  2218. hp1,hp2 : tai;
  2219. begin
  2220. result:=false;
  2221. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2222. begin
  2223. { vmova* reg1,reg1
  2224. =>
  2225. <nop> }
  2226. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2227. begin
  2228. RemoveCurrentP(p);
  2229. result:=true;
  2230. exit;
  2231. end;
  2232. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2233. (hp1.typ = ait_instruction) and
  2234. (
  2235. { Under -O2 and below, the instructions are always adjacent }
  2236. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2237. (taicpu(hp1).ops <= 1) or
  2238. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2239. { If reg1 = reg3, reg1 must not be modified in between }
  2240. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2241. ) then
  2242. begin
  2243. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2244. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2245. begin
  2246. { vmova* reg1,reg2
  2247. ...
  2248. vmova* reg2,reg3
  2249. dealloc reg2
  2250. =>
  2251. vmova* reg1,reg3 }
  2252. TransferUsedRegs(TmpUsedRegs);
  2253. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2254. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2255. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2256. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2257. begin
  2258. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2259. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2260. TransferUsedRegs(TmpUsedRegs);
  2261. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2262. RemoveInstruction(hp1);
  2263. result:=true;
  2264. exit;
  2265. end;
  2266. { special case:
  2267. vmova* reg1,<op>
  2268. ...
  2269. vmova* <op>,reg1
  2270. =>
  2271. vmova* reg1,<op> }
  2272. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2273. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2274. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2275. ) then
  2276. begin
  2277. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2278. RemoveInstruction(hp1);
  2279. result:=true;
  2280. exit;
  2281. end
  2282. end
  2283. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2284. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2285. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2286. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2287. ) and
  2288. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2289. begin
  2290. { vmova* reg1,reg2
  2291. ...
  2292. vmovs* reg2,<op>
  2293. dealloc reg2
  2294. =>
  2295. vmovs* reg1,<op> }
  2296. TransferUsedRegs(TmpUsedRegs);
  2297. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2298. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2299. begin
  2300. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2301. taicpu(p).opcode:=taicpu(hp1).opcode;
  2302. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2303. TransferUsedRegs(TmpUsedRegs);
  2304. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2305. RemoveInstruction(hp1);
  2306. result:=true;
  2307. exit;
  2308. end
  2309. end;
  2310. if MatchInstruction(hp1,[A_VFMADDPD,
  2311. A_VFMADD132PD,
  2312. A_VFMADD132PS,
  2313. A_VFMADD132SD,
  2314. A_VFMADD132SS,
  2315. A_VFMADD213PD,
  2316. A_VFMADD213PS,
  2317. A_VFMADD213SD,
  2318. A_VFMADD213SS,
  2319. A_VFMADD231PD,
  2320. A_VFMADD231PS,
  2321. A_VFMADD231SD,
  2322. A_VFMADD231SS,
  2323. A_VFMADDSUB132PD,
  2324. A_VFMADDSUB132PS,
  2325. A_VFMADDSUB213PD,
  2326. A_VFMADDSUB213PS,
  2327. A_VFMADDSUB231PD,
  2328. A_VFMADDSUB231PS,
  2329. A_VFMSUB132PD,
  2330. A_VFMSUB132PS,
  2331. A_VFMSUB132SD,
  2332. A_VFMSUB132SS,
  2333. A_VFMSUB213PD,
  2334. A_VFMSUB213PS,
  2335. A_VFMSUB213SD,
  2336. A_VFMSUB213SS,
  2337. A_VFMSUB231PD,
  2338. A_VFMSUB231PS,
  2339. A_VFMSUB231SD,
  2340. A_VFMSUB231SS,
  2341. A_VFMSUBADD132PD,
  2342. A_VFMSUBADD132PS,
  2343. A_VFMSUBADD213PD,
  2344. A_VFMSUBADD213PS,
  2345. A_VFMSUBADD231PD,
  2346. A_VFMSUBADD231PS,
  2347. A_VFNMADD132PD,
  2348. A_VFNMADD132PS,
  2349. A_VFNMADD132SD,
  2350. A_VFNMADD132SS,
  2351. A_VFNMADD213PD,
  2352. A_VFNMADD213PS,
  2353. A_VFNMADD213SD,
  2354. A_VFNMADD213SS,
  2355. A_VFNMADD231PD,
  2356. A_VFNMADD231PS,
  2357. A_VFNMADD231SD,
  2358. A_VFNMADD231SS,
  2359. A_VFNMSUB132PD,
  2360. A_VFNMSUB132PS,
  2361. A_VFNMSUB132SD,
  2362. A_VFNMSUB132SS,
  2363. A_VFNMSUB213PD,
  2364. A_VFNMSUB213PS,
  2365. A_VFNMSUB213SD,
  2366. A_VFNMSUB213SS,
  2367. A_VFNMSUB231PD,
  2368. A_VFNMSUB231PS,
  2369. A_VFNMSUB231SD,
  2370. A_VFNMSUB231SS],[S_NO]) and
  2371. { we mix single and double opperations here because we assume that the compiler
  2372. generates vmovapd only after double operations and vmovaps only after single operations }
  2373. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2374. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2375. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2376. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2377. begin
  2378. TransferUsedRegs(TmpUsedRegs);
  2379. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2380. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2381. begin
  2382. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2383. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2384. RemoveCurrentP(p)
  2385. else
  2386. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2387. RemoveInstruction(hp2);
  2388. end;
  2389. end
  2390. else if (hp1.typ = ait_instruction) and
  2391. (((taicpu(p).opcode=A_MOVAPS) and
  2392. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2393. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2394. ((taicpu(p).opcode=A_MOVAPD) and
  2395. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2396. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2397. ) and
  2398. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2399. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2400. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2401. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2402. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2403. { change
  2404. movapX reg,reg2
  2405. addsX/subsX/... reg3, reg2
  2406. movapX reg2,reg
  2407. to
  2408. addsX/subsX/... reg3,reg
  2409. }
  2410. begin
  2411. TransferUsedRegs(TmpUsedRegs);
  2412. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2413. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2414. begin
  2415. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2416. debug_op2str(taicpu(p).opcode)+' '+
  2417. debug_op2str(taicpu(hp1).opcode)+' '+
  2418. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2419. { we cannot eliminate the first move if
  2420. the operations uses the same register for source and dest }
  2421. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2422. { Remember that hp1 is not necessarily the immediate
  2423. next instruction }
  2424. RemoveCurrentP(p);
  2425. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2426. RemoveInstruction(hp2);
  2427. result:=true;
  2428. end;
  2429. end
  2430. else if (hp1.typ = ait_instruction) and
  2431. (((taicpu(p).opcode=A_VMOVAPD) and
  2432. (taicpu(hp1).opcode=A_VCOMISD)) or
  2433. ((taicpu(p).opcode=A_VMOVAPS) and
  2434. ((taicpu(hp1).opcode=A_VCOMISS))
  2435. )
  2436. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2437. { change
  2438. movapX reg,reg1
  2439. vcomisX reg1,reg1
  2440. to
  2441. vcomisX reg,reg
  2442. }
  2443. begin
  2444. TransferUsedRegs(TmpUsedRegs);
  2445. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2446. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2447. begin
  2448. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2449. debug_op2str(taicpu(p).opcode)+' '+
  2450. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2451. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2452. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2453. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2454. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2455. RemoveCurrentP(p);
  2456. result:=true;
  2457. exit;
  2458. end;
  2459. end
  2460. end;
  2461. end;
  2462. end;
  2463. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2464. var
  2465. hp1 : tai;
  2466. begin
  2467. result:=false;
  2468. { replace
  2469. V<Op>X %mreg1,%mreg2,%mreg3
  2470. VMovX %mreg3,%mreg4
  2471. dealloc %mreg3
  2472. by
  2473. V<Op>X %mreg1,%mreg2,%mreg4
  2474. ?
  2475. }
  2476. if GetNextInstruction(p,hp1) and
  2477. { we mix single and double operations here because we assume that the compiler
  2478. generates vmovapd only after double operations and vmovaps only after single operations }
  2479. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2480. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2481. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2482. begin
  2483. TransferUsedRegs(TmpUsedRegs);
  2484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2485. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2486. begin
  2487. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2488. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2489. RemoveInstruction(hp1);
  2490. result:=true;
  2491. end;
  2492. end;
  2493. end;
  2494. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2495. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2496. begin
  2497. Result := False;
  2498. { For safety reasons, only check for exact register matches }
  2499. { Check base register }
  2500. if (ref.base = AOldReg) then
  2501. begin
  2502. ref.base := ANewReg;
  2503. Result := True;
  2504. end;
  2505. { Check index register }
  2506. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2507. begin
  2508. ref.index := ANewReg;
  2509. Result := True;
  2510. end;
  2511. end;
  2512. { Replaces all references to AOldReg in an operand to ANewReg }
  2513. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2514. var
  2515. OldSupReg, NewSupReg: TSuperRegister;
  2516. OldSubReg, NewSubReg: TSubRegister;
  2517. OldRegType: TRegisterType;
  2518. ThisOper: POper;
  2519. begin
  2520. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2521. Result := False;
  2522. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2523. InternalError(2020011801);
  2524. OldSupReg := getsupreg(AOldReg);
  2525. OldSubReg := getsubreg(AOldReg);
  2526. OldRegType := getregtype(AOldReg);
  2527. NewSupReg := getsupreg(ANewReg);
  2528. NewSubReg := getsubreg(ANewReg);
  2529. if OldRegType <> getregtype(ANewReg) then
  2530. InternalError(2020011802);
  2531. if OldSubReg <> NewSubReg then
  2532. InternalError(2020011803);
  2533. case ThisOper^.typ of
  2534. top_reg:
  2535. if (
  2536. (ThisOper^.reg = AOldReg) or
  2537. (
  2538. (OldRegType = R_INTREGISTER) and
  2539. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2540. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2541. (
  2542. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2543. {$ifndef x86_64}
  2544. and (
  2545. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2546. don't have an 8-bit representation }
  2547. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2548. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2549. )
  2550. {$endif x86_64}
  2551. )
  2552. )
  2553. ) then
  2554. begin
  2555. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2556. Result := True;
  2557. end;
  2558. top_ref:
  2559. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2560. Result := True;
  2561. else
  2562. ;
  2563. end;
  2564. end;
  2565. { Replaces all references to AOldReg in an instruction to ANewReg }
  2566. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2567. const
  2568. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2569. var
  2570. OperIdx: Integer;
  2571. begin
  2572. Result := False;
  2573. for OperIdx := 0 to p.ops - 1 do
  2574. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2575. begin
  2576. { The shift and rotate instructions can only use CL }
  2577. if not (
  2578. (OperIdx = 0) and
  2579. { This second condition just helps to avoid unnecessarily
  2580. calling MatchInstruction for 10 different opcodes }
  2581. (p.oper[0]^.reg = NR_CL) and
  2582. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2583. ) then
  2584. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2585. end
  2586. else if p.oper[OperIdx]^.typ = top_ref then
  2587. { It's okay to replace registers in references that get written to }
  2588. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2589. end;
  2590. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2591. begin
  2592. Result :=
  2593. (ref^.index = NR_NO) and
  2594. (
  2595. {$ifdef x86_64}
  2596. (
  2597. (ref^.base = NR_RIP) and
  2598. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2599. ) or
  2600. {$endif x86_64}
  2601. (ref^.refaddr = addr_full) or
  2602. (ref^.base = NR_STACK_POINTER_REG) or
  2603. (ref^.base = current_procinfo.framepointer)
  2604. );
  2605. end;
  2606. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2607. var
  2608. l: asizeint;
  2609. begin
  2610. Result := False;
  2611. { Should have been checked previously }
  2612. if p.opcode <> A_LEA then
  2613. InternalError(2020072501);
  2614. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2615. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2616. not(cs_opt_size in current_settings.optimizerswitches) then
  2617. exit;
  2618. with p.oper[0]^.ref^ do
  2619. begin
  2620. if (base <> p.oper[1]^.reg) or
  2621. (index <> NR_NO) or
  2622. assigned(symbol) then
  2623. exit;
  2624. l:=offset;
  2625. if (l=1) and UseIncDec then
  2626. begin
  2627. p.opcode:=A_INC;
  2628. p.loadreg(0,p.oper[1]^.reg);
  2629. p.ops:=1;
  2630. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2631. end
  2632. else if (l=-1) and UseIncDec then
  2633. begin
  2634. p.opcode:=A_DEC;
  2635. p.loadreg(0,p.oper[1]^.reg);
  2636. p.ops:=1;
  2637. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2638. end
  2639. else
  2640. begin
  2641. if (l<0) and (l<>-2147483648) then
  2642. begin
  2643. p.opcode:=A_SUB;
  2644. p.loadConst(0,-l);
  2645. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2646. end
  2647. else
  2648. begin
  2649. p.opcode:=A_ADD;
  2650. p.loadConst(0,l);
  2651. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2652. end;
  2653. end;
  2654. end;
  2655. Result := True;
  2656. end;
  2657. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2658. var
  2659. CurrentReg, ReplaceReg: TRegister;
  2660. begin
  2661. Result := False;
  2662. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2663. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2664. case hp.opcode of
  2665. A_FSTSW, A_FNSTSW,
  2666. A_IN, A_INS, A_OUT, A_OUTS,
  2667. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2668. { These routines have explicit operands, but they are restricted in
  2669. what they can be (e.g. IN and OUT can only read from AL, AX or
  2670. EAX. }
  2671. Exit;
  2672. A_IMUL:
  2673. begin
  2674. { The 1-operand version writes to implicit registers
  2675. The 2-operand version reads from the first operator, and reads
  2676. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2677. the 3-operand version reads from a register that it doesn't write to
  2678. }
  2679. case hp.ops of
  2680. 1:
  2681. if (
  2682. (
  2683. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2684. ) or
  2685. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2686. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2687. begin
  2688. Result := True;
  2689. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2690. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2691. end;
  2692. 2:
  2693. { Only modify the first parameter }
  2694. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2695. begin
  2696. Result := True;
  2697. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2698. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2699. end;
  2700. 3:
  2701. { Only modify the second parameter }
  2702. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2703. begin
  2704. Result := True;
  2705. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2706. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2707. end;
  2708. else
  2709. InternalError(2020012901);
  2710. end;
  2711. end;
  2712. else
  2713. if (hp.ops > 0) and
  2714. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2715. begin
  2716. Result := True;
  2717. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2718. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2719. end;
  2720. end;
  2721. end;
  2722. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2723. var
  2724. hp2, hp_regalloc: tai;
  2725. p_SourceReg, p_TargetReg: TRegister;
  2726. begin
  2727. Result := False;
  2728. { Backward optimisation. If we have:
  2729. func. %reg1,%reg2
  2730. mov %reg2,%reg3
  2731. (dealloc %reg2)
  2732. Change to:
  2733. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2734. Perform similar optimisations with 1, 3 and 4-operand instructions
  2735. that only have one output.
  2736. }
  2737. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2738. begin
  2739. p_SourceReg := taicpu(p).oper[0]^.reg;
  2740. p_TargetReg := taicpu(p).oper[1]^.reg;
  2741. TransferUsedRegs(TmpUsedRegs);
  2742. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2743. GetLastInstruction(p, hp2) and
  2744. (hp2.typ = ait_instruction) and
  2745. { Have to make sure it's an instruction that only reads from
  2746. the first operands and only writes (not reads or modifies) to
  2747. the last one; in essence, a pure function such as BSR, POPCNT
  2748. or ANDN }
  2749. (
  2750. (
  2751. (taicpu(hp2).ops = 1) and
  2752. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2753. ) or
  2754. (
  2755. (taicpu(hp2).ops = 2) and
  2756. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2757. ) or
  2758. (
  2759. (taicpu(hp2).ops = 3) and
  2760. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2761. ) or
  2762. (
  2763. (taicpu(hp2).ops = 4) and
  2764. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2765. )
  2766. ) and
  2767. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2768. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2769. begin
  2770. case taicpu(hp2).opcode of
  2771. A_FSTSW, A_FNSTSW,
  2772. A_IN, A_INS, A_OUT, A_OUTS,
  2773. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2774. { These routines have explicit operands, but they are restricted in
  2775. what they can be (e.g. IN and OUT can only read from AL, AX or
  2776. EAX. }
  2777. ;
  2778. else
  2779. begin
  2780. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2781. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2782. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2783. if Assigned(hp_regalloc) then
  2784. begin
  2785. Asml.Remove(hp_regalloc);
  2786. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2787. begin
  2788. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2789. hp_regalloc.Free;
  2790. end
  2791. else
  2792. { If the register is not explicitly deallocated, it's
  2793. being reused, so move the allocation to after func. }
  2794. AsmL.InsertAfter(hp_regalloc, hp2);
  2795. end;
  2796. if not RegInInstruction(p_TargetReg, hp2) then
  2797. begin
  2798. TransferUsedRegs(TmpUsedRegs);
  2799. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2800. end;
  2801. { Actually make the changes }
  2802. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2803. RemoveCurrentp(p, hp1);
  2804. { If the Func was another MOV instruction, we might get
  2805. "mov %reg,%reg" that doesn't get removed in Pass 2
  2806. otherwise, so deal with it here (also do something
  2807. similar with lea (%reg),%reg}
  2808. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2809. begin
  2810. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2811. if p = hp2 then
  2812. RemoveCurrentp(p)
  2813. else
  2814. RemoveInstruction(hp2);
  2815. end;
  2816. Result := True;
  2817. Exit;
  2818. end;
  2819. end;
  2820. end;
  2821. end;
  2822. end;
  2823. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2824. begin
  2825. Result := False;
  2826. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2827. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2828. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2829. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2830. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2831. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2832. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2833. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2834. begin
  2835. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2836. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2837. Result := True;
  2838. Include(OptsToCheck, aoc_ForceNewIteration);
  2839. end;
  2840. end;
  2841. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2842. var
  2843. hp1, hp2, hp3, hp4, last_hp1: tai;
  2844. GetNextInstruction_p, DoOptimisation, TempBool: Boolean;
  2845. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2846. {$ifdef x86_64}
  2847. NewConst: TCGInt;
  2848. {$endif x86_64}
  2849. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2850. begin
  2851. if taicpu(hp1).opcode = signed_movop then
  2852. begin
  2853. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2854. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2855. end
  2856. else
  2857. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2858. end;
  2859. function GetNextHp1(const in_p: tai): Boolean;
  2860. begin
  2861. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2862. GetNextInstruction_p := GetNextInstructionUsingReg(in_p, hp1, p_TargetReg)
  2863. else
  2864. GetNextInstruction_p := GetNextInstruction(in_p, hp1);
  2865. Result := GetNextInstruction_p and (hp1.typ = ait_instruction);
  2866. end;
  2867. function TryConstMerge(var p1, p2: tai): Boolean;
  2868. var
  2869. ThisRef: TReference;
  2870. begin
  2871. Result := False;
  2872. ThisRef := taicpu(p2).oper[1]^.ref^;
  2873. { Only permit writes to the stack, since we can guarantee alignment with that }
  2874. if (ThisRef.index = NR_NO) and
  2875. (
  2876. (ThisRef.base = NR_STACK_POINTER_REG) or
  2877. (ThisRef.base = current_procinfo.framepointer)
  2878. ) then
  2879. begin
  2880. case taicpu(p).opsize of
  2881. S_B:
  2882. begin
  2883. { Word writes must be on a 2-byte boundary }
  2884. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2885. begin
  2886. { Reduce offset of second reference to see if it is sequential with the first }
  2887. Dec(ThisRef.offset, 1);
  2888. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2889. begin
  2890. { Make sure the constants aren't represented as a
  2891. negative number, as these won't merge properly }
  2892. taicpu(p1).opsize := S_W;
  2893. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2894. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2895. RemoveInstruction(p2);
  2896. Result := True;
  2897. end;
  2898. end;
  2899. end;
  2900. S_W:
  2901. begin
  2902. { Longword writes must be on a 4-byte boundary }
  2903. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2904. begin
  2905. { Reduce offset of second reference to see if it is sequential with the first }
  2906. Dec(ThisRef.offset, 2);
  2907. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2908. begin
  2909. { Make sure the constants aren't represented as a
  2910. negative number, as these won't merge properly }
  2911. taicpu(p1).opsize := S_L;
  2912. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2913. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2914. RemoveInstruction(p2);
  2915. Result := True;
  2916. end;
  2917. end;
  2918. end;
  2919. {$ifdef x86_64}
  2920. S_L:
  2921. begin
  2922. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2923. see if the constants can be encoded this way. }
  2924. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2925. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2926. { Quadword writes must be on an 8-byte boundary }
  2927. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2928. begin
  2929. { Reduce offset of second reference to see if it is sequential with the first }
  2930. Dec(ThisRef.offset, 4);
  2931. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2932. begin
  2933. { Make sure the constants aren't represented as a
  2934. negative number, as these won't merge properly }
  2935. taicpu(p1).opsize := S_Q;
  2936. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2937. taicpu(p1).oper[0]^.val := NewConst;
  2938. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2939. RemoveInstruction(p2);
  2940. Result := True;
  2941. end;
  2942. end;
  2943. end;
  2944. {$endif x86_64}
  2945. else
  2946. ;
  2947. end;
  2948. end;
  2949. end;
  2950. var
  2951. TempRegUsed, CrossJump: Boolean;
  2952. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2953. NewSize: topsize; NewOffset: asizeint;
  2954. SourceRef, TargetRef: TReference;
  2955. MovAligned, MovUnaligned: TAsmOp;
  2956. JumpTracking: TLinkedList;
  2957. begin
  2958. Result:=false;
  2959. { remove mov reg1,reg1? }
  2960. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2961. then
  2962. begin
  2963. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2964. { take care of the register (de)allocs following p }
  2965. RemoveCurrentP(p);
  2966. Result := True;
  2967. exit;
  2968. end;
  2969. { Prevent compiler warnings }
  2970. p_SourceReg := NR_NO;
  2971. p_TargetReg := NR_NO;
  2972. hp1 := nil;
  2973. if taicpu(p).oper[1]^.typ = top_reg then
  2974. begin
  2975. { Saves on a large number of dereferences }
  2976. p_TargetReg := taicpu(p).oper[1]^.reg;
  2977. TransferUsedRegs(TmpUsedRegs);
  2978. last_hp1 := p;
  2979. if GetNextHp1(p) then
  2980. while True do
  2981. begin
  2982. if (taicpu(hp1).opcode = A_AND) and
  2983. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2984. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[1]^.reg) then
  2985. begin
  2986. UpdateUsedRegsBetween(TmpUsedRegs, last_hp1, hp1);
  2987. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2988. (taicpu(hp1).oper[0]^.typ = top_const) and
  2989. (taicpu(p).opsize = taicpu(hp1).opsize) then
  2990. begin
  2991. case taicpu(p).opsize of
  2992. S_L:
  2993. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2994. begin
  2995. { Optimize out:
  2996. mov x, %reg
  2997. and ffffffffh, %reg
  2998. }
  2999. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3000. hp2 := tai(hp1.Previous);
  3001. RemoveInstruction(hp1);
  3002. //Include(OptsToCheck, aoc_ForceNewIteration);
  3003. if GetNextHp1(hp2) then
  3004. Continue
  3005. else
  3006. Exit;
  3007. end;
  3008. S_Q: { TODO: Confirm if this is even possible }
  3009. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3010. begin
  3011. { Optimize out:
  3012. mov x, %reg
  3013. and ffffffffffffffffh, %reg
  3014. }
  3015. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3016. hp2 := tai(hp1.Previous);
  3017. RemoveInstruction(hp1);
  3018. //Include(OptsToCheck, aoc_ForceNewIteration);
  3019. if GetNextHp1(hp2) then
  3020. Continue
  3021. else
  3022. Exit;
  3023. end;
  3024. else
  3025. ;
  3026. end;
  3027. if (
  3028. { Make sure that if a reference is used, its registers
  3029. are not modified in between }
  3030. (
  3031. (taicpu(p).oper[0]^.typ = top_reg) and
  3032. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3033. ) or
  3034. (
  3035. (taicpu(p).oper[0]^.typ = top_ref) and
  3036. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3037. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3038. )
  3039. ) and
  3040. GetNextInstruction(hp1,hp2) and
  3041. MatchInstruction(hp2,A_TEST,[]) and
  3042. (
  3043. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3044. (
  3045. { If the register being tested is smaller than the one
  3046. that received a bitwise AND, permit it if the constant
  3047. fits into the smaller size }
  3048. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3049. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3050. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3051. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3052. (
  3053. (
  3054. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3055. (taicpu(hp1).oper[0]^.val <= $FF)
  3056. ) or
  3057. (
  3058. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3059. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3060. {$ifdef x86_64}
  3061. ) or
  3062. (
  3063. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3064. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3065. {$endif x86_64}
  3066. )
  3067. )
  3068. )
  3069. ) and
  3070. (
  3071. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3072. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3073. ) and
  3074. GetNextInstruction(hp2,hp3) and
  3075. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3076. (taicpu(hp3).condition in [C_E,C_NE]) then
  3077. begin
  3078. TransferUsedRegs(TmpUsedRegs);
  3079. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3080. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3081. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3082. begin
  3083. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3084. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3085. taicpu(hp1).opcode:=A_TEST;
  3086. { Shrink the TEST instruction down to the smallest possible size }
  3087. case taicpu(hp1).oper[0]^.val of
  3088. 0..255:
  3089. if (taicpu(hp1).opsize <> S_B)
  3090. {$ifndef x86_64}
  3091. and (
  3092. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3093. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3094. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3095. )
  3096. {$endif x86_64}
  3097. then
  3098. begin
  3099. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3100. { Only print debug message if the TEST instruction
  3101. is a different size before and after }
  3102. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3103. taicpu(hp1).opsize := S_B;
  3104. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3105. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3106. end;
  3107. 256..65535:
  3108. if (taicpu(hp1).opsize <> S_W) then
  3109. begin
  3110. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3111. { Only print debug message if the TEST instruction
  3112. is a different size before and after }
  3113. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3114. taicpu(hp1).opsize := S_W;
  3115. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3116. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3117. end;
  3118. {$ifdef x86_64}
  3119. 65536..$7FFFFFFF:
  3120. if (taicpu(hp1).opsize <> S_L) then
  3121. begin
  3122. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3123. { Only print debug message if the TEST instruction
  3124. is a different size before and after }
  3125. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3126. taicpu(hp1).opsize := S_L;
  3127. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3128. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3129. end;
  3130. {$endif x86_64}
  3131. else
  3132. ;
  3133. end;
  3134. RemoveInstruction(hp2);
  3135. RemoveCurrentP(p);
  3136. Result:=true;
  3137. exit;
  3138. end;
  3139. end;
  3140. end;
  3141. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3142. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3143. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3144. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^) and
  3145. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) and
  3146. (
  3147. not (cs_opt_level3 in current_settings.optimizerswitches) or
  3148. (taicpu(hp1).oper[0]^.typ = top_const) or
  3149. not RegModifiedBetween(taicpu(hp1).oper[0]^.reg, p, hp1)
  3150. ) then
  3151. begin
  3152. { With:
  3153. mov %reg1,%reg2
  3154. ...
  3155. and %reg1,%reg2
  3156. Or:
  3157. mov $x,%reg2
  3158. ...
  3159. and $x,%reg2
  3160. Remove the 'and' instruction
  3161. }
  3162. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 4 done',hp1);
  3163. hp2 := tai(hp1.Previous);
  3164. RemoveInstruction(hp1);
  3165. //Include(OptsToCheck, aoc_ForceNewIteration);
  3166. if GetNextHp1(hp2) then
  3167. Continue
  3168. else
  3169. Exit;
  3170. end;
  3171. if IsMOVZXAcceptable and
  3172. (taicpu(p).oper[0]^.typ <> top_const) then { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3173. begin
  3174. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3175. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3176. case taicpu(p).opsize of
  3177. S_B:
  3178. if (taicpu(hp1).oper[0]^.val = $ff) then
  3179. begin
  3180. { Convert:
  3181. movb x, %regl movb x, %regl
  3182. andw ffh, %regw andl ffh, %regd
  3183. To:
  3184. movzbw x, %regd movzbl x, %regd
  3185. (Identical registers, just different sizes)
  3186. }
  3187. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3188. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3189. case taicpu(hp1).opsize of
  3190. S_W: NewSize := S_BW;
  3191. S_L: NewSize := S_BL;
  3192. {$ifdef x86_64}
  3193. S_Q: NewSize := S_BQ;
  3194. {$endif x86_64}
  3195. else
  3196. InternalError(2018011510);
  3197. end;
  3198. end
  3199. else
  3200. NewSize := S_NO;
  3201. S_W:
  3202. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3203. begin
  3204. { Convert:
  3205. movw x, %regw
  3206. andl ffffh, %regd
  3207. To:
  3208. movzwl x, %regd
  3209. (Identical registers, just different sizes)
  3210. }
  3211. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3212. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3213. case taicpu(hp1).opsize of
  3214. S_L: NewSize := S_WL;
  3215. {$ifdef x86_64}
  3216. S_Q: NewSize := S_WQ;
  3217. {$endif x86_64}
  3218. else
  3219. InternalError(2018011511);
  3220. end;
  3221. end
  3222. else
  3223. NewSize := S_NO;
  3224. else
  3225. NewSize := S_NO;
  3226. end;
  3227. if NewSize <> S_NO then
  3228. begin
  3229. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3230. { The actual optimization }
  3231. taicpu(p).opcode := A_MOVZX;
  3232. taicpu(p).changeopsize(NewSize);
  3233. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3234. { Make sure we deal with any reference counts that were increased }
  3235. if taicpu(hp1).oper[1]^.typ = top_ref then
  3236. begin
  3237. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3238. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3239. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3240. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3241. end;
  3242. { Safeguard if "and" is followed by a conditional command }
  3243. TransferUsedRegs(TmpUsedRegs);
  3244. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3245. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3246. begin
  3247. { At this point, the "and" command is effectively equivalent to
  3248. "test %reg,%reg". This will be handled separately by the
  3249. Peephole Optimizer. [Kit] }
  3250. DebugMsg(SPeepholeOptimization + PreMessage +
  3251. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3252. end
  3253. else
  3254. begin
  3255. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3256. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3257. RemoveInstruction(hp1);
  3258. end;
  3259. Result := True;
  3260. Exit;
  3261. { Go through DeepMOVOpt again (jump to "while True do") }
  3262. Continue;
  3263. end;
  3264. end;
  3265. end;
  3266. if taicpu(p).oper[0]^.typ = top_reg then
  3267. begin
  3268. p_SourceReg := taicpu(p).oper[0]^.reg;
  3269. { Look for:
  3270. mov %reg1,%reg2
  3271. ??? %reg2,r/m
  3272. Change to:
  3273. mov %reg1,%reg2
  3274. ??? %reg1,r/m
  3275. }
  3276. if RegReadByInstruction(p_TargetReg, hp1) and
  3277. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3278. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3279. begin
  3280. { A change has occurred, just not in p }
  3281. Include(OptsToCheck, aoc_ForceNewIteration);
  3282. TransferUsedRegs(TmpUsedRegs);
  3283. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3284. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3285. { Just in case something didn't get modified (e.g. an
  3286. implicit register) }
  3287. not RegReadByInstruction(p_TargetReg, hp1) then
  3288. begin
  3289. { We can remove the original MOV }
  3290. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3291. RemoveCurrentP(p);
  3292. { UsedRegs got updated by RemoveCurrentp }
  3293. Result := True;
  3294. Exit;
  3295. end;
  3296. { If we know a MOV instruction has become a null operation, we might as well
  3297. get rid of it now to save time. }
  3298. if (taicpu(hp1).opcode = A_MOV) and
  3299. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3300. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3301. { Just being a register is enough to confirm it's a null operation }
  3302. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3303. begin
  3304. Result := True;
  3305. { Speed-up to reduce a pipeline stall... if we had something like...
  3306. movl %eax,%edx
  3307. movw %dx,%ax
  3308. ... the second instruction would change to movw %ax,%ax, but
  3309. given that it is now %ax that's active rather than %eax,
  3310. penalties might occur due to a partial register write, so instead,
  3311. change it to a MOVZX instruction when optimising for speed.
  3312. }
  3313. if not (cs_opt_size in current_settings.optimizerswitches) and
  3314. IsMOVZXAcceptable and
  3315. (taicpu(hp1).opsize < taicpu(p).opsize)
  3316. {$ifdef x86_64}
  3317. { operations already implicitly set the upper 64 bits to zero }
  3318. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3319. {$endif x86_64}
  3320. then
  3321. begin
  3322. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3323. case taicpu(p).opsize of
  3324. S_W:
  3325. if taicpu(hp1).opsize = S_B then
  3326. taicpu(hp1).opsize := S_BL
  3327. else
  3328. InternalError(2020012911);
  3329. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3330. case taicpu(hp1).opsize of
  3331. S_B:
  3332. taicpu(hp1).opsize := S_BL;
  3333. S_W:
  3334. taicpu(hp1).opsize := S_WL;
  3335. else
  3336. InternalError(2020012912);
  3337. end;
  3338. else
  3339. InternalError(2020012910);
  3340. end;
  3341. taicpu(hp1).opcode := A_MOVZX;
  3342. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3343. end
  3344. else
  3345. begin
  3346. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3347. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3348. RemoveInstruction(hp1);
  3349. { The instruction after what was hp1 is now the immediate next instruction,
  3350. so we can continue to make optimisations if it's present }
  3351. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3352. Exit;
  3353. hp1 := hp2;
  3354. end;
  3355. end;
  3356. end;
  3357. {$ifdef x86_64}
  3358. { Change:
  3359. movl %reg1l,%reg2l
  3360. movq %reg2q,%reg1q
  3361. To:
  3362. movl %reg1l,%reg2l
  3363. andl %reg1l,%reg1l
  3364. }
  3365. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3366. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3367. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3368. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) and
  3369. SuperRegistersEqual(p_SourceReg, taicpu(hp1).oper[1]^.reg) then
  3370. begin
  3371. TransferUsedRegs(TmpUsedRegs);
  3372. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3373. taicpu(hp1).opsize := S_L;
  3374. taicpu(hp1).loadreg(0, p_SourceReg);
  3375. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3376. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3377. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3378. taicpu(hp1).opcode := A_AND;
  3379. { We may be able to do more and replace references
  3380. to %reg2q with %reg1q etc. }
  3381. if (cs_opt_level3 in current_settings.optimizerswitches) and
  3382. { p_TargetReg is not used between, otherwise the earlier
  3383. GetNextInstructionUsingReg would have stopped sooner }
  3384. DoZeroUpper32Opt(p,hp1) then
  3385. begin
  3386. Result := True;
  3387. Exit;
  3388. end;
  3389. end;
  3390. {
  3391. If we have the following already in the code...
  3392. movl %reg1l,%reg2l
  3393. andl %reg1l,%reg1l
  3394. ...we may be able to do more and replace references to
  3395. %reg2q with %reg1q etc. (program flow won't reach this
  3396. point if the second instruction was originally a MOV
  3397. and just got changed to AND)
  3398. }
  3399. if (cs_opt_level3 in current_settings.optimizerswitches) and
  3400. (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_AND,[S_L]) and
  3401. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3402. { p_TargetReg is not used between, otherwise the earlier
  3403. GetNextInstructionUsingReg would have stopped sooner }
  3404. MatchOperand(taicpu(hp1).oper[1]^, p_SourceReg) and
  3405. (
  3406. MatchOperand(taicpu(hp1).oper[0]^, p_SourceReg) or
  3407. MatchOperand(taicpu(hp1).oper[0]^, $ffffffff)
  3408. ) and
  3409. DoZeroUpper32Opt(p,hp1) then
  3410. begin
  3411. Result := True;
  3412. Exit;
  3413. end;
  3414. {$endif x86_64}
  3415. end
  3416. else if taicpu(p).oper[0]^.typ = top_const then
  3417. begin
  3418. if (taicpu(hp1).opcode = A_OR) and
  3419. (taicpu(p).oper[1]^.typ = top_reg) and
  3420. MatchOperand(taicpu(p).oper[0]^, 0) and
  3421. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3422. begin
  3423. { mov 0, %reg
  3424. or ###,%reg
  3425. Change to (only if the flags are not used):
  3426. mov ###,%reg
  3427. }
  3428. TransferUsedRegs(TmpUsedRegs);
  3429. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3430. DoOptimisation := True;
  3431. { Even if the flags are used, we might be able to do the optimisation
  3432. if the conditions are predictable }
  3433. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3434. begin
  3435. { Only perform if ### = %reg (the same register) or equal to 0,
  3436. so %reg is guaranteed to still have a value of zero }
  3437. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3438. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3439. begin
  3440. hp2 := hp1;
  3441. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3442. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3443. GetNextInstruction(hp2, hp3) do
  3444. begin
  3445. { Don't continue modifying if the flags state is getting changed }
  3446. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3447. Break;
  3448. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3449. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3450. begin
  3451. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3452. begin
  3453. { Condition is always true }
  3454. case taicpu(hp3).opcode of
  3455. A_Jcc:
  3456. begin
  3457. { Check for jump shortcuts before we destroy the condition }
  3458. hp4 := hp3;
  3459. DoJumpOptimizations(hp3, TempBool);
  3460. { Make sure hp3 hasn't changed }
  3461. if (hp4 = hp3) then
  3462. begin
  3463. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3464. MakeUnconditional(taicpu(hp3));
  3465. end;
  3466. Result := True;
  3467. end;
  3468. A_CMOVcc:
  3469. begin
  3470. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3471. taicpu(hp3).opcode := A_MOV;
  3472. taicpu(hp3).condition := C_None;
  3473. Result := True;
  3474. end;
  3475. A_SETcc:
  3476. begin
  3477. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3478. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3479. taicpu(hp3).opcode := A_MOV;
  3480. taicpu(hp3).ops := 2;
  3481. taicpu(hp3).condition := C_None;
  3482. taicpu(hp3).opsize := S_B;
  3483. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3484. taicpu(hp3).loadconst(0, 1);
  3485. Result := True;
  3486. end;
  3487. else
  3488. InternalError(2021090701);
  3489. end;
  3490. end
  3491. 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
  3492. begin
  3493. { Condition is always false }
  3494. case taicpu(hp3).opcode of
  3495. A_Jcc:
  3496. begin
  3497. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3498. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3499. RemoveInstruction(hp3);
  3500. Result := True;
  3501. { Since hp3 was deleted, hp2 must not be updated }
  3502. Continue;
  3503. end;
  3504. A_CMOVcc:
  3505. begin
  3506. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3507. RemoveInstruction(hp3);
  3508. Result := True;
  3509. { Since hp3 was deleted, hp2 must not be updated }
  3510. Continue;
  3511. end;
  3512. A_SETcc:
  3513. begin
  3514. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3515. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3516. taicpu(hp3).opcode := A_MOV;
  3517. taicpu(hp3).ops := 2;
  3518. taicpu(hp3).condition := C_None;
  3519. taicpu(hp3).opsize := S_B;
  3520. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3521. taicpu(hp3).loadconst(0, 0);
  3522. Result := True;
  3523. end;
  3524. else
  3525. InternalError(2021090702);
  3526. end;
  3527. end
  3528. else
  3529. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3530. DoOptimisation := False;
  3531. end;
  3532. hp2 := hp3;
  3533. end;
  3534. if DoOptimisation then
  3535. begin
  3536. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3537. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3538. { Flags are still in use - don't optimise }
  3539. DoOptimisation := False;
  3540. end;
  3541. end
  3542. else
  3543. DoOptimisation := False;
  3544. end;
  3545. if DoOptimisation then
  3546. begin
  3547. {$ifdef x86_64}
  3548. { OR only supports 32-bit sign-extended constants for 64-bit
  3549. instructions, so compensate for this if the constant is
  3550. encoded as a value greater than or equal to 2^31 }
  3551. if (taicpu(hp1).opsize = S_Q) and
  3552. (taicpu(hp1).oper[0]^.typ = top_const) and
  3553. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3554. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3555. {$endif x86_64}
  3556. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3557. taicpu(hp1).opcode := A_MOV;
  3558. RemoveCurrentP(p);
  3559. Result := True;
  3560. Exit;
  3561. end;
  3562. end;
  3563. end
  3564. else if
  3565. { oper[0] is a reference }
  3566. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3567. begin
  3568. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3569. begin
  3570. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3571. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3572. ) or
  3573. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3574. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3575. )
  3576. ) and
  3577. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3578. { mov ref,reg1
  3579. lea (reg1,reg2),reg2
  3580. to
  3581. add ref,reg2 }
  3582. begin
  3583. TransferUsedRegs(TmpUsedRegs);
  3584. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3585. { If the flags register is in use, don't change the instruction to an
  3586. ADD otherwise this will scramble the flags. [Kit] }
  3587. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3588. { reg1 may not be used afterwards }
  3589. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3590. begin
  3591. Taicpu(hp1).opcode:=A_ADD;
  3592. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3593. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3594. RemoveCurrentp(p);
  3595. result:=true;
  3596. exit;
  3597. end;
  3598. end;
  3599. { If the LEA instruction can be converted into an arithmetic instruction,
  3600. it may be possible to then fold it in the next optimisation. }
  3601. if ConvertLEA(taicpu(hp1)) then
  3602. Include(OptsToCheck, aoc_ForceNewIteration);
  3603. end;
  3604. {
  3605. mov ref,reg0
  3606. <op> reg0,reg1
  3607. dealloc reg0
  3608. to
  3609. <op> ref,reg1
  3610. }
  3611. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3612. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3613. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3614. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3615. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3616. begin
  3617. TransferUsedRegs(TmpUsedRegs);
  3618. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3619. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3620. begin
  3621. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3622. { loadref increases the reference count, so decrement it again }
  3623. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3624. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3625. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3626. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3627. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3628. { See if we can remove the allocation of reg0 }
  3629. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3630. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3631. RemoveCurrentp(p);
  3632. Result:=true;
  3633. exit;
  3634. end;
  3635. end;
  3636. end;
  3637. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3638. overwrites the original destination register. e.g.
  3639. movl ###,%reg2d
  3640. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3641. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3642. }
  3643. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3644. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3645. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3646. begin
  3647. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3648. begin
  3649. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3650. case taicpu(p).oper[0]^.typ of
  3651. top_const:
  3652. { We have something like:
  3653. movb $x, %regb
  3654. movzbl %regb,%regd
  3655. Change to:
  3656. movl $x, %regd
  3657. }
  3658. begin
  3659. case taicpu(hp1).opsize of
  3660. S_BW:
  3661. begin
  3662. convert_mov_value(A_MOVSX, $FF);
  3663. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3664. taicpu(p).opsize := S_W;
  3665. end;
  3666. S_BL:
  3667. begin
  3668. convert_mov_value(A_MOVSX, $FF);
  3669. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3670. taicpu(p).opsize := S_L;
  3671. end;
  3672. S_WL:
  3673. begin
  3674. convert_mov_value(A_MOVSX, $FFFF);
  3675. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3676. taicpu(p).opsize := S_L;
  3677. end;
  3678. {$ifdef x86_64}
  3679. S_BQ:
  3680. begin
  3681. convert_mov_value(A_MOVSX, $FF);
  3682. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3683. taicpu(p).opsize := S_Q;
  3684. end;
  3685. S_WQ:
  3686. begin
  3687. convert_mov_value(A_MOVSX, $FFFF);
  3688. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3689. taicpu(p).opsize := S_Q;
  3690. end;
  3691. S_LQ:
  3692. begin
  3693. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3694. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3695. taicpu(p).opsize := S_Q;
  3696. end;
  3697. {$endif x86_64}
  3698. else
  3699. { If hp1 was a MOV instruction, it should have been
  3700. optimised already }
  3701. InternalError(2020021001);
  3702. end;
  3703. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3704. RemoveInstruction(hp1);
  3705. Result := True;
  3706. Exit;
  3707. end;
  3708. top_ref:
  3709. begin
  3710. { We have something like:
  3711. movb mem, %regb
  3712. movzbl %regb,%regd
  3713. Change to:
  3714. movzbl mem, %regd
  3715. }
  3716. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3717. begin
  3718. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3719. taicpu(p).opcode := taicpu(hp1).opcode;
  3720. taicpu(p).opsize := taicpu(hp1).opsize;
  3721. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3722. RemoveInstruction(hp1);
  3723. Result := True;
  3724. Exit;
  3725. end;
  3726. end;
  3727. else
  3728. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3729. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3730. Exit;
  3731. end;
  3732. end
  3733. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3734. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3735. optimised }
  3736. else
  3737. begin
  3738. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3739. RemoveCurrentP(p);
  3740. Result := True;
  3741. Exit;
  3742. end;
  3743. end;
  3744. if (taicpu(hp1).opcode = A_MOV) and
  3745. (
  3746. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3747. {$ifdef x86_64}
  3748. or (
  3749. { Permit zero extension from 32- to 64-bit when writing
  3750. a constant (it will be checked to see if it fits into
  3751. a signed 32-bit integer) }
  3752. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3753. (
  3754. { Valid situations... writing an unsigned 32-bit
  3755. immediate, or the destination is a 64-bit register }
  3756. (taicpu(p).oper[0]^.typ = top_const) or
  3757. (taicpu(hp1).oper[1]^.typ = top_reg)
  3758. ) and
  3759. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3760. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3761. )
  3762. {$endif x86_64}
  3763. ) then
  3764. begin
  3765. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3766. TransferUsedRegs(TmpUsedRegs);
  3767. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3768. { we have
  3769. mov x, %treg
  3770. mov %treg, y
  3771. }
  3772. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3773. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3774. begin
  3775. { we've got
  3776. mov x, %treg
  3777. mov %treg, y
  3778. with %treg is not used after }
  3779. case taicpu(p).oper[0]^.typ Of
  3780. { top_reg is covered by DeepMOVOpt }
  3781. top_const:
  3782. begin
  3783. { change
  3784. mov const, %treg
  3785. mov %treg, y
  3786. to
  3787. mov const, y
  3788. }
  3789. {$ifdef x86_64}
  3790. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3791. (
  3792. { For 32-to-64-bit zero-extension, the immediate
  3793. must be between 0 and 2^31 - 1}
  3794. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3795. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3796. ) or
  3797. (
  3798. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3799. (
  3800. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3801. )
  3802. ) then
  3803. {$endif x86_64}
  3804. begin
  3805. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3806. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3807. RemoveCurrentP(p);
  3808. Result := True;
  3809. Exit;
  3810. end;
  3811. end;
  3812. top_ref:
  3813. case taicpu(hp1).oper[1]^.typ of
  3814. top_reg:
  3815. { change
  3816. mov mem, %treg
  3817. mov %treg, %reg
  3818. to
  3819. mov mem, %reg"
  3820. }
  3821. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3822. begin
  3823. {$ifdef x86_64}
  3824. { If zero extending from 32-bit to 64-bit,
  3825. we have to make sure the replaced
  3826. register is the right size }
  3827. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3828. {$else}
  3829. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3830. {$endif x86_64}
  3831. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3832. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3833. RemoveInstruction(hp1);
  3834. Result := True;
  3835. Exit;
  3836. end
  3837. else if
  3838. { Make sure that if a reference is used, its
  3839. registers are not modified in between }
  3840. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3841. begin
  3842. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3843. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3844. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3845. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3846. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3847. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3848. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3849. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3850. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3851. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3852. RemoveCurrentP(p);
  3853. Result := True;
  3854. Exit;
  3855. end;
  3856. top_ref:
  3857. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3858. begin
  3859. {$ifdef x86_64}
  3860. { Look for the following to simplify:
  3861. mov x(mem1), %reg
  3862. mov %reg, y(mem2)
  3863. mov x+8(mem1), %reg
  3864. mov %reg, y+8(mem2)
  3865. Change to:
  3866. movdqu x(mem1), %xmmreg
  3867. movdqu %xmmreg, y(mem2)
  3868. ...but only as long as the memory blocks don't overlap
  3869. }
  3870. SourceRef := taicpu(p).oper[0]^.ref^;
  3871. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3872. if (taicpu(p).opsize = S_Q) and
  3873. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3874. GetNextInstruction(hp1, hp2) and
  3875. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3876. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3877. begin
  3878. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3879. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3880. Inc(SourceRef.offset, 8);
  3881. if UseAVX then
  3882. begin
  3883. MovAligned := A_VMOVDQA;
  3884. MovUnaligned := A_VMOVDQU;
  3885. end
  3886. else
  3887. begin
  3888. MovAligned := A_MOVDQA;
  3889. MovUnaligned := A_MOVDQU;
  3890. end;
  3891. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3892. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3893. begin
  3894. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3895. Inc(TargetRef.offset, 8);
  3896. if GetNextInstruction(hp2, hp3) and
  3897. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3898. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3899. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3900. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3901. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3902. begin
  3903. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3904. if NewMMReg <> NR_NO then
  3905. begin
  3906. { Remember that the offsets are 8 ahead }
  3907. if ((SourceRef.offset mod 16) = 8) and
  3908. (
  3909. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3910. (SourceRef.base = current_procinfo.framepointer) or
  3911. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3912. ) then
  3913. taicpu(p).opcode := MovAligned
  3914. else
  3915. taicpu(p).opcode := MovUnaligned;
  3916. taicpu(p).opsize := S_XMM;
  3917. taicpu(p).oper[1]^.reg := NewMMReg;
  3918. if ((TargetRef.offset mod 16) = 8) and
  3919. (
  3920. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3921. (TargetRef.base = current_procinfo.framepointer) or
  3922. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3923. ) then
  3924. taicpu(hp1).opcode := MovAligned
  3925. else
  3926. taicpu(hp1).opcode := MovUnaligned;
  3927. taicpu(hp1).opsize := S_XMM;
  3928. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3929. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3930. RemoveInstruction(hp2);
  3931. RemoveInstruction(hp3);
  3932. Result := True;
  3933. Exit;
  3934. end;
  3935. end;
  3936. end
  3937. else
  3938. begin
  3939. { See if the next references are 8 less rather than 8 greater }
  3940. Dec(SourceRef.offset, 16); { -8 the other way }
  3941. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3942. begin
  3943. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3944. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3945. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3946. GetNextInstruction(hp2, hp3) and
  3947. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3948. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3949. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3950. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3951. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3952. begin
  3953. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3954. if NewMMReg <> NR_NO then
  3955. begin
  3956. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3957. if ((SourceRef.offset mod 16) = 0) and
  3958. (
  3959. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3960. (SourceRef.base = current_procinfo.framepointer) or
  3961. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3962. ) then
  3963. taicpu(hp2).opcode := MovAligned
  3964. else
  3965. taicpu(hp2).opcode := MovUnaligned;
  3966. taicpu(hp2).opsize := S_XMM;
  3967. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3968. if ((TargetRef.offset mod 16) = 0) and
  3969. (
  3970. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3971. (TargetRef.base = current_procinfo.framepointer) or
  3972. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3973. ) then
  3974. taicpu(hp3).opcode := MovAligned
  3975. else
  3976. taicpu(hp3).opcode := MovUnaligned;
  3977. taicpu(hp3).opsize := S_XMM;
  3978. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3979. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3980. RemoveInstruction(hp1);
  3981. RemoveCurrentP(p);
  3982. Result := True;
  3983. Exit;
  3984. end;
  3985. end;
  3986. end;
  3987. end;
  3988. end;
  3989. {$endif x86_64}
  3990. end;
  3991. else
  3992. { The write target should be a reg or a ref }
  3993. InternalError(2021091601);
  3994. end;
  3995. else
  3996. ;
  3997. end;
  3998. end
  3999. else if (taicpu(p).oper[0]^.typ = top_const) and
  4000. { %treg is used afterwards, but all eventualities other
  4001. than the first MOV instruction being a constant are
  4002. covered by DeepMOVOpt, so only check for that }
  4003. (
  4004. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  4005. not (cs_opt_size in current_settings.optimizerswitches) or
  4006. (taicpu(hp1).opsize = S_B)
  4007. ) and
  4008. (
  4009. (taicpu(hp1).oper[1]^.typ=top_reg) or
  4010. (
  4011. { For 32-to-64-bit zero-extension, the immediate
  4012. must be between 0 and 2^31 - 1}
  4013. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  4014. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  4015. ) or
  4016. (
  4017. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  4018. (
  4019. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  4020. )
  4021. )
  4022. ) then
  4023. begin
  4024. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  4025. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  4026. Include(OptsToCheck, aoc_ForceNewIteration);
  4027. end;
  4028. end;
  4029. Break;
  4030. end;
  4031. end;
  4032. if taicpu(p).oper[0]^.typ = top_reg then
  4033. begin
  4034. { oper[1] is a reference }
  4035. { Saves on a large number of dereferences }
  4036. p_SourceReg := taicpu(p).oper[0]^.reg;
  4037. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  4038. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  4039. else
  4040. GetNextInstruction_p := GetNextInstruction(p, hp1);
  4041. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  4042. begin
  4043. if taicpu(p).oper[1]^.typ = top_reg then
  4044. begin
  4045. p_TargetReg := taicpu(p).oper[1]^.reg;
  4046. { Change:
  4047. movl %reg1,%reg2
  4048. ...
  4049. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  4050. ...
  4051. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  4052. To:
  4053. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  4054. ...
  4055. movl x(%reg1),%reg1
  4056. ...
  4057. movl %reg1,%regX
  4058. }
  4059. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4060. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4061. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4062. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4063. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4064. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4065. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4066. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4067. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4068. begin
  4069. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4070. if RegInRef(p_TargetReg, SourceRef) and
  4071. { If %reg1 also appears in the second reference, then it will
  4072. not refer to the same memory block as the first reference }
  4073. not RegInRef(p_SourceReg, SourceRef) then
  4074. begin
  4075. { Check to see if the references match if %reg2 is changed to %reg1 }
  4076. if SourceRef.base = p_TargetReg then
  4077. SourceRef.base := p_SourceReg;
  4078. if SourceRef.index = p_TargetReg then
  4079. SourceRef.index := p_SourceReg;
  4080. { RefsEqual also checks to ensure both references are non-volatile }
  4081. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4082. begin
  4083. taicpu(hp2).loadreg(0, p_SourceReg);
  4084. TransferUsedRegs(TmpUsedRegs);
  4085. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4086. { Make sure the register is allocated between these instructions
  4087. even though it doesn't change value, since it may cause
  4088. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4089. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4090. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4091. Result := True;
  4092. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4093. begin
  4094. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4095. RemoveCurrentP(p);
  4096. Exit;
  4097. end
  4098. else
  4099. begin
  4100. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4101. begin
  4102. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4103. RemoveCurrentP(p);
  4104. Exit;
  4105. end;
  4106. end;
  4107. { If we reach this point, p and hp1 weren't actually modified,
  4108. so we can do a bit more work on this pass }
  4109. end;
  4110. end;
  4111. end;
  4112. end;
  4113. end;
  4114. end;
  4115. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4116. { All the next optimisations require a next instruction }
  4117. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4118. Exit;
  4119. { Change:
  4120. movl/q (ref), %reg
  4121. movd/q %reg, %xmm0
  4122. (dealloc %reg)
  4123. To:
  4124. movd/q (ref), %xmm0
  4125. }
  4126. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4127. MatchInstruction(hp1,[A_MOVD,A_VMOVD{$ifdef x86_64},A_MOVQ,A_VMOVQ{$endif x86_64}],[]) and
  4128. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  4129. (taicpu(hp1).oper[1]^.typ=top_reg) and
  4130. (GetRegType(taicpu(hp1).oper[1]^.reg)=R_MMREGISTER) then
  4131. begin
  4132. TransferUsedRegs(TmpUsedRegs);
  4133. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4134. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  4135. begin
  4136. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  4137. { loadref increases the reference count, so decrement it again }
  4138. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  4139. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  4140. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  4141. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  4142. DebugMsg(SPeepholeOptimization+'Merged MOV and (V)MOVD/(V)MOVQ to eliminate intermediate register (MovMovD/Q2MovD/Q)',p);
  4143. RemoveCurrentP(p,hp1);
  4144. Result:=True;
  4145. Exit;
  4146. end;
  4147. end;
  4148. { Next instruction is also a MOV ? }
  4149. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4150. begin
  4151. if MatchOpType(taicpu(p), top_const, top_ref) and
  4152. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4153. TryConstMerge(p, hp1) then
  4154. begin
  4155. Result := True;
  4156. { In case we have four byte writes in a row, check for 2 more
  4157. right now so we don't have to wait for another iteration of
  4158. pass 1
  4159. }
  4160. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4161. case taicpu(p).opsize of
  4162. S_W:
  4163. begin
  4164. if GetNextInstruction(p, hp1) and
  4165. MatchInstruction(hp1, A_MOV, [S_B]) and
  4166. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4167. GetNextInstruction(hp1, hp2) and
  4168. MatchInstruction(hp2, A_MOV, [S_B]) and
  4169. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4170. { Try to merge the two bytes }
  4171. TryConstMerge(hp1, hp2) then
  4172. { Now try to merge the two words (hp2 will get deleted) }
  4173. TryConstMerge(p, hp1);
  4174. end;
  4175. S_L:
  4176. begin
  4177. { Though this only really benefits x86_64 and not i386, it
  4178. gets a potential optimisation done faster and hence
  4179. reduces the number of times OptPass1MOV is entered }
  4180. if GetNextInstruction(p, hp1) and
  4181. MatchInstruction(hp1, A_MOV, [S_W]) and
  4182. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4183. GetNextInstruction(hp1, hp2) and
  4184. MatchInstruction(hp2, A_MOV, [S_W]) and
  4185. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4186. { Try to merge the two words }
  4187. TryConstMerge(hp1, hp2) then
  4188. { This will always fail on i386, so don't bother
  4189. calling it unless we're doing x86_64 }
  4190. {$ifdef x86_64}
  4191. { Now try to merge the two longwords (hp2 will get deleted) }
  4192. TryConstMerge(p, hp1)
  4193. {$endif x86_64}
  4194. ;
  4195. end;
  4196. else
  4197. ;
  4198. end;
  4199. Exit;
  4200. end;
  4201. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4202. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4203. { mov reg1, mem1 or mov mem1, reg1
  4204. mov mem2, reg2 mov reg2, mem2}
  4205. begin
  4206. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4207. { mov reg1, mem1 or mov mem1, reg1
  4208. mov mem2, reg1 mov reg2, mem1}
  4209. begin
  4210. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4211. { Removes the second statement from
  4212. mov reg1, mem1/reg2
  4213. mov mem1/reg2, reg1 }
  4214. begin
  4215. if taicpu(p).oper[0]^.typ=top_reg then
  4216. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4217. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4218. RemoveInstruction(hp1);
  4219. Result:=true;
  4220. if (taicpu(p).oper[1]^.typ = top_reg) then
  4221. begin
  4222. TransferUsedRegs(TmpUsedRegs);
  4223. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, p, TmpUsedRegs) then
  4224. begin
  4225. { reg2 is no longer in use }
  4226. DebugMsg(SPeepholeOptimization + 'Mov2Nop 6 done',p);
  4227. RemoveCurrentP(p);
  4228. end;
  4229. end;
  4230. exit;
  4231. end
  4232. else
  4233. begin
  4234. TransferUsedRegs(TmpUsedRegs);
  4235. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4236. if (taicpu(p).oper[1]^.typ = top_ref) and
  4237. { mov reg1, mem1
  4238. mov mem2, reg1 }
  4239. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4240. GetNextInstruction(hp1, hp2) and
  4241. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4242. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4243. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4244. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4245. { change to
  4246. mov reg1, mem1 mov reg1, mem1
  4247. mov mem2, reg1 cmp reg1, mem2
  4248. cmp mem1, reg1
  4249. }
  4250. begin
  4251. RemoveInstruction(hp2);
  4252. taicpu(hp1).opcode := A_CMP;
  4253. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4254. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4255. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4256. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4257. end;
  4258. end;
  4259. end
  4260. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4261. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4262. begin
  4263. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4264. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4265. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4266. end
  4267. else
  4268. begin
  4269. TransferUsedRegs(TmpUsedRegs);
  4270. if GetNextInstruction(hp1, hp2) and
  4271. MatchOpType(taicpu(p),top_ref,top_reg) and
  4272. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4273. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4274. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4275. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4276. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4277. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4278. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4279. { mov mem1, %reg1
  4280. mov %reg1, mem2
  4281. mov mem2, reg2
  4282. to:
  4283. mov mem1, reg2
  4284. mov reg2, mem2}
  4285. begin
  4286. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4287. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4288. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4289. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4290. RemoveInstruction(hp2);
  4291. Result := True;
  4292. end
  4293. {$ifdef i386}
  4294. { this is enabled for i386 only, as the rules to create the reg sets below
  4295. are too complicated for x86-64, so this makes this code too error prone
  4296. on x86-64
  4297. }
  4298. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4299. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4300. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4301. { mov mem1, reg1 mov mem1, reg1
  4302. mov reg1, mem2 mov reg1, mem2
  4303. mov mem2, reg2 mov mem2, reg1
  4304. to: to:
  4305. mov mem1, reg1 mov mem1, reg1
  4306. mov mem1, reg2 mov reg1, mem2
  4307. mov reg1, mem2
  4308. or (if mem1 depends on reg1
  4309. and/or if mem2 depends on reg2)
  4310. to:
  4311. mov mem1, reg1
  4312. mov reg1, mem2
  4313. mov reg1, reg2
  4314. }
  4315. begin
  4316. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4317. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4318. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4319. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4320. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4321. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4322. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4323. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4324. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4325. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4326. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4327. end
  4328. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4329. begin
  4330. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4331. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4332. end
  4333. else
  4334. begin
  4335. RemoveInstruction(hp2);
  4336. end
  4337. {$endif i386}
  4338. ;
  4339. end;
  4340. end
  4341. { movl [mem1],reg1
  4342. movl [mem1],reg2
  4343. to
  4344. movl [mem1],reg1
  4345. movl reg1,reg2
  4346. }
  4347. else if not CheckMovMov2MovMov2(p, hp1) and
  4348. { movl const1,[mem1]
  4349. movl [mem1],reg1
  4350. to
  4351. movl const1,reg1
  4352. movl reg1,[mem1]
  4353. }
  4354. MatchOpType(Taicpu(p),top_const,top_ref) and
  4355. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4356. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4357. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4358. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4359. begin
  4360. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4361. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4362. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4363. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4364. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4365. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4366. Result:=true;
  4367. exit;
  4368. end;
  4369. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4370. end;
  4371. { search further than the next instruction for a mov (as long as it's not a jump) }
  4372. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4373. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4374. (taicpu(p).oper[1]^.typ = top_reg) and
  4375. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4376. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4377. begin
  4378. { we work with hp2 here, so hp1 can be still used later on when
  4379. checking for GetNextInstruction_p }
  4380. hp3 := hp1;
  4381. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4382. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4383. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4384. TransferUsedRegs(TmpUsedRegs);
  4385. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4386. if NotFirstIteration then
  4387. JumpTracking := TLinkedList.Create
  4388. else
  4389. JumpTracking := nil;
  4390. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4391. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4392. (hp2.typ=ait_instruction) do
  4393. begin
  4394. case taicpu(hp2).opcode of
  4395. A_POP:
  4396. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4397. begin
  4398. if not CrossJump and
  4399. not RegUsedBetween(p_TargetReg, p, hp2) then
  4400. begin
  4401. { We can remove the original MOV since the register
  4402. wasn't used between it and its popping from the stack }
  4403. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4404. RemoveCurrentp(p, hp1);
  4405. Result := True;
  4406. JumpTracking.Free;
  4407. Exit;
  4408. end;
  4409. { Can't go any further }
  4410. Break;
  4411. end;
  4412. A_MOV:
  4413. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4414. ((taicpu(p).oper[0]^.typ=top_const) or
  4415. ((taicpu(p).oper[0]^.typ=top_reg) and
  4416. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4417. )
  4418. ) then
  4419. begin
  4420. { we have
  4421. mov x, %treg
  4422. mov %treg, y
  4423. }
  4424. { We don't need to call UpdateUsedRegs for every instruction between
  4425. p and hp2 because the register we're concerned about will not
  4426. become deallocated (otherwise GetNextInstructionUsingReg would
  4427. have stopped at an earlier instruction). [Kit] }
  4428. TempRegUsed :=
  4429. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4430. RegReadByInstruction(p_TargetReg, hp3) or
  4431. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4432. case taicpu(p).oper[0]^.typ Of
  4433. top_reg:
  4434. begin
  4435. { change
  4436. mov %reg, %treg
  4437. mov %treg, y
  4438. to
  4439. mov %reg, y
  4440. }
  4441. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4442. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4443. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4444. begin
  4445. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4446. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4447. if TempRegUsed then
  4448. begin
  4449. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4450. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4451. { Set the start of the next GetNextInstructionUsingRegCond search
  4452. to start at the entry right before hp2 (which is about to be removed) }
  4453. hp3 := tai(hp2.Previous);
  4454. RemoveInstruction(hp2);
  4455. Include(OptsToCheck, aoc_ForceNewIteration);
  4456. { See if there's more we can optimise }
  4457. Continue;
  4458. end
  4459. else
  4460. begin
  4461. RemoveInstruction(hp2);
  4462. { We can remove the original MOV too }
  4463. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4464. RemoveCurrentP(p, hp1);
  4465. Result:=true;
  4466. JumpTracking.Free;
  4467. Exit;
  4468. end;
  4469. end
  4470. else
  4471. begin
  4472. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4473. taicpu(hp2).loadReg(0, p_SourceReg);
  4474. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4475. { Check to see if the register also appears in the reference }
  4476. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4477. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4478. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4479. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4480. begin
  4481. { Don't remove the first instruction if the temporary register is in use }
  4482. if not TempRegUsed then
  4483. begin
  4484. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4485. RemoveCurrentP(p, hp1);
  4486. Result:=true;
  4487. JumpTracking.Free;
  4488. Exit;
  4489. end;
  4490. { No need to set Result to True here. If there's another instruction later
  4491. on that can be optimised, it will be detected when the main Pass 1 loop
  4492. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4493. hp3 := hp2;
  4494. Continue;
  4495. end;
  4496. end;
  4497. end;
  4498. top_const:
  4499. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4500. begin
  4501. { change
  4502. mov const, %treg
  4503. mov %treg, y
  4504. to
  4505. mov const, y
  4506. }
  4507. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4508. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4509. begin
  4510. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4511. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4512. if TempRegUsed then
  4513. begin
  4514. { Don't remove the first instruction if the temporary register is in use }
  4515. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4516. { No need to set Result to True. If there's another instruction later on
  4517. that can be optimised, it will be detected when the main Pass 1 loop
  4518. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4519. end
  4520. else
  4521. begin
  4522. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4523. RemoveCurrentP(p, hp1);
  4524. Result:=true;
  4525. Exit;
  4526. end;
  4527. end;
  4528. end;
  4529. else
  4530. Internalerror(2019103001);
  4531. end;
  4532. end
  4533. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4534. begin
  4535. if not CrossJump and
  4536. not RegUsedBetween(p_TargetReg, p, hp2) and
  4537. not RegReadByInstruction(p_TargetReg, hp2) then
  4538. begin
  4539. { Register is not used before it is overwritten }
  4540. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4541. RemoveCurrentp(p, hp1);
  4542. Result := True;
  4543. Exit;
  4544. end;
  4545. if (taicpu(p).oper[0]^.typ = top_const) and
  4546. (taicpu(hp2).oper[0]^.typ = top_const) then
  4547. begin
  4548. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4549. begin
  4550. { Same value - register hasn't changed }
  4551. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4552. RemoveInstruction(hp2);
  4553. Include(OptsToCheck, aoc_ForceNewIteration);
  4554. { See if there's more we can optimise }
  4555. Continue;
  4556. end;
  4557. end;
  4558. {$ifdef x86_64}
  4559. end
  4560. { Change:
  4561. movl %reg1l,%reg2l
  4562. ...
  4563. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4564. To:
  4565. movl %reg1l,%reg2l
  4566. ...
  4567. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4568. If %reg1 = %reg3, convert to:
  4569. movl %reg1l,%reg2l
  4570. ...
  4571. andl %reg1l,%reg1l
  4572. }
  4573. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4574. (taicpu(p).oper[0]^.typ = top_reg) and
  4575. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4576. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4577. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4578. begin
  4579. TempRegUsed :=
  4580. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4581. RegReadByInstruction(p_TargetReg, hp3) or
  4582. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4583. taicpu(hp2).opsize := S_L;
  4584. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4585. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4586. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4587. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4588. begin
  4589. { %reg1 = %reg3 }
  4590. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4591. taicpu(hp2).opcode := A_AND;
  4592. end
  4593. else
  4594. begin
  4595. { %reg1 <> %reg3 }
  4596. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4597. end;
  4598. if not TempRegUsed then
  4599. begin
  4600. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4601. RemoveCurrentP(p, hp1);
  4602. Result := True;
  4603. Exit;
  4604. end
  4605. else
  4606. begin
  4607. { Initial instruction wasn't actually changed }
  4608. Include(OptsToCheck, aoc_ForceNewIteration);
  4609. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4610. appears below since %reg1 has technically changed }
  4611. if taicpu(hp2).opcode = A_AND then
  4612. Break;
  4613. end;
  4614. {$endif x86_64}
  4615. end
  4616. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4617. GetNextInstruction(hp2, hp4) and
  4618. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4619. { Optimise the following first:
  4620. movl [mem1],reg1
  4621. movl [mem1],reg2
  4622. to
  4623. movl [mem1],reg1
  4624. movl reg1,reg2
  4625. If [mem1] contains the target register and reg1 is the
  4626. the source register, this optimisation will get missed
  4627. and produce less efficient code later on.
  4628. }
  4629. if CheckMovMov2MovMov2(hp2, hp4) then
  4630. { Initial instruction wasn't actually changed }
  4631. Include(OptsToCheck, aoc_ForceNewIteration);
  4632. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4633. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4634. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4635. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4636. begin
  4637. {
  4638. Change from:
  4639. mov ###, %reg
  4640. ...
  4641. movs/z %reg,%reg (Same register, just different sizes)
  4642. To:
  4643. movs/z ###, %reg (Longer version)
  4644. ...
  4645. (remove)
  4646. }
  4647. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4648. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4649. { Keep the first instruction as mov if ### is a constant }
  4650. if taicpu(p).oper[0]^.typ = top_const then
  4651. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4652. else
  4653. begin
  4654. taicpu(p).opcode := taicpu(hp2).opcode;
  4655. taicpu(p).opsize := taicpu(hp2).opsize;
  4656. end;
  4657. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4658. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4659. RemoveInstruction(hp2);
  4660. Result := True;
  4661. JumpTracking.Free;
  4662. Exit;
  4663. end;
  4664. else
  4665. { Move down to the if-block below };
  4666. end;
  4667. { Also catches MOV/S/Z instructions that aren't modified }
  4668. if taicpu(p).oper[0]^.typ = top_reg then
  4669. begin
  4670. p_SourceReg := taicpu(p).oper[0]^.reg;
  4671. if
  4672. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4673. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4674. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4675. begin
  4676. Result := True;
  4677. { Just in case something didn't get modified (e.g. an
  4678. implicit register). Also, if it does read from this
  4679. register, then there's no longer an advantage to
  4680. changing the register on subsequent instructions.}
  4681. if not RegReadByInstruction(p_TargetReg, hp2) then
  4682. begin
  4683. { If a conditional jump was crossed, do not delete
  4684. the original MOV no matter what }
  4685. if not CrossJump and
  4686. { RegEndOfLife returns True if the register is
  4687. deallocated before the next instruction or has
  4688. been loaded with a new value }
  4689. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4690. begin
  4691. { We can remove the original MOV }
  4692. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4693. RemoveCurrentp(p, hp1);
  4694. JumpTracking.Free;
  4695. Result := True;
  4696. Exit;
  4697. end;
  4698. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4699. begin
  4700. { See if there's more we can optimise }
  4701. hp3 := hp2;
  4702. Continue;
  4703. end;
  4704. end;
  4705. end;
  4706. end;
  4707. { Break out of the while loop under normal circumstances }
  4708. Break;
  4709. end;
  4710. JumpTracking.Free;
  4711. end;
  4712. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4713. (taicpu(p).oper[1]^.typ = top_reg) and
  4714. (taicpu(p).opsize = S_L) and
  4715. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4716. (hp2.typ = ait_instruction) and
  4717. (taicpu(hp2).opcode = A_AND) and
  4718. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4719. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4720. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4721. ) then
  4722. begin
  4723. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4724. begin
  4725. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4726. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4727. begin
  4728. { Optimize out:
  4729. mov x, %reg
  4730. and ffffffffh, %reg
  4731. }
  4732. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4733. RemoveInstruction(hp2);
  4734. Result:=true;
  4735. exit;
  4736. end;
  4737. end;
  4738. end;
  4739. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4740. x >= RetOffset) as it doesn't do anything (it writes either to a
  4741. parameter or to the temporary storage room for the function
  4742. result)
  4743. }
  4744. if IsExitCode(hp1) and
  4745. (taicpu(p).oper[1]^.typ = top_ref) and
  4746. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4747. (
  4748. (
  4749. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4750. not (
  4751. assigned(current_procinfo.procdef.funcretsym) and
  4752. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4753. )
  4754. ) or
  4755. { Also discard writes to the stack that are below the base pointer,
  4756. as this is temporary storage rather than a function result on the
  4757. stack, say. }
  4758. (
  4759. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4760. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4761. )
  4762. ) then
  4763. begin
  4764. RemoveCurrentp(p, hp1);
  4765. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4766. RemoveLastDeallocForFuncRes(p);
  4767. Result:=true;
  4768. exit;
  4769. end;
  4770. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4771. begin
  4772. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4773. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4774. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4775. begin
  4776. { change
  4777. mov reg1, mem1
  4778. test/cmp x, mem1
  4779. to
  4780. mov reg1, mem1
  4781. test/cmp x, reg1
  4782. }
  4783. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4784. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4785. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4786. Result := True;
  4787. Exit;
  4788. end;
  4789. if DoMovCmpMemOpt(p, hp1) then
  4790. begin
  4791. Result := True;
  4792. Exit;
  4793. end;
  4794. end;
  4795. if (taicpu(p).oper[1]^.typ = top_reg) and
  4796. (hp1.typ = ait_instruction) and
  4797. GetNextInstruction(hp1, hp2) and
  4798. MatchInstruction(hp2,A_MOV,[]) and
  4799. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4800. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4801. (
  4802. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4803. {$ifdef x86_64}
  4804. or
  4805. (
  4806. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4807. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4808. )
  4809. {$endif x86_64}
  4810. ) then
  4811. begin
  4812. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4813. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4814. { change movsX/movzX reg/ref, reg2
  4815. add/sub/or/... reg3/$const, reg2
  4816. mov reg2 reg/ref
  4817. dealloc reg2
  4818. to
  4819. add/sub/or/... reg3/$const, reg/ref }
  4820. begin
  4821. TransferUsedRegs(TmpUsedRegs);
  4822. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4823. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4824. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4825. begin
  4826. { by example:
  4827. movswl %si,%eax movswl %si,%eax p
  4828. decl %eax addl %edx,%eax hp1
  4829. movw %ax,%si movw %ax,%si hp2
  4830. ->
  4831. movswl %si,%eax movswl %si,%eax p
  4832. decw %eax addw %edx,%eax hp1
  4833. movw %ax,%si movw %ax,%si hp2
  4834. }
  4835. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4836. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4837. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4838. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4839. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4840. {
  4841. ->
  4842. movswl %si,%eax movswl %si,%eax p
  4843. decw %si addw %dx,%si hp1
  4844. movw %ax,%si movw %ax,%si hp2
  4845. }
  4846. case taicpu(hp1).ops of
  4847. 1:
  4848. begin
  4849. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4850. if taicpu(hp1).oper[0]^.typ=top_reg then
  4851. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4852. end;
  4853. 2:
  4854. begin
  4855. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4856. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4857. (taicpu(hp1).opcode<>A_SHL) and
  4858. (taicpu(hp1).opcode<>A_SHR) and
  4859. (taicpu(hp1).opcode<>A_SAR) then
  4860. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4861. end;
  4862. else
  4863. internalerror(2008042701);
  4864. end;
  4865. {
  4866. ->
  4867. decw %si addw %dx,%si p
  4868. }
  4869. RemoveInstruction(hp2);
  4870. RemoveCurrentP(p, hp1);
  4871. Result:=True;
  4872. Exit;
  4873. end;
  4874. end;
  4875. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4876. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4877. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4878. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4879. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4880. ) and
  4881. { if ref contains a symbol, we cannot change its size to a smaller size }
  4882. ((taicpu(p).oper[0]^.typ<>top_ref) or (taicpu(p).oper[0]^.ref^.symbol=nil) or
  4883. (topsize2memsize[taicpu(p).opsize]<=topsize2memsize[taicpu(hp2).opsize])
  4884. )
  4885. {$ifdef i386}
  4886. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4887. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4888. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4889. {$endif i386}
  4890. then
  4891. { change movsX/movzX reg/ref, reg2
  4892. add/sub/or/... regX/$const, reg2
  4893. mov reg2, reg3
  4894. dealloc reg2
  4895. to
  4896. movsX/movzX reg/ref, reg3
  4897. add/sub/or/... reg3/$const, reg3
  4898. }
  4899. begin
  4900. TransferUsedRegs(TmpUsedRegs);
  4901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4904. begin
  4905. { by example:
  4906. movswl %si,%eax movswl %si,%eax p
  4907. decl %eax addl %edx,%eax hp1
  4908. movw %ax,%si movw %ax,%si hp2
  4909. ->
  4910. movswl %si,%eax movswl %si,%eax p
  4911. decw %eax addw %edx,%eax hp1
  4912. movw %ax,%si movw %ax,%si hp2
  4913. }
  4914. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4915. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4916. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4917. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4918. { limit size of constants as well to avoid assembler errors, but
  4919. check opsize to avoid overflow when left shifting the 1 }
  4920. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4921. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4922. {$ifdef x86_64}
  4923. { Be careful of, for example:
  4924. movl %reg1,%reg2
  4925. addl %reg3,%reg2
  4926. movq %reg2,%reg4
  4927. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4928. }
  4929. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4930. begin
  4931. taicpu(hp2).changeopsize(S_L);
  4932. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4933. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4934. end;
  4935. {$endif x86_64}
  4936. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4937. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4938. if taicpu(p).oper[0]^.typ=top_reg then
  4939. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4940. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4941. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4942. {
  4943. ->
  4944. movswl %si,%eax movswl %si,%eax p
  4945. decw %si addw %dx,%si hp1
  4946. movw %ax,%si movw %ax,%si hp2
  4947. }
  4948. case taicpu(hp1).ops of
  4949. 1:
  4950. begin
  4951. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4952. if taicpu(hp1).oper[0]^.typ=top_reg then
  4953. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4954. end;
  4955. 2:
  4956. begin
  4957. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4958. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4959. (taicpu(hp1).opcode<>A_SHL) and
  4960. (taicpu(hp1).opcode<>A_SHR) and
  4961. (taicpu(hp1).opcode<>A_SAR) then
  4962. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4963. end;
  4964. else
  4965. internalerror(2018111801);
  4966. end;
  4967. {
  4968. ->
  4969. decw %si addw %dx,%si p
  4970. }
  4971. RemoveInstruction(hp2);
  4972. end;
  4973. end;
  4974. end;
  4975. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4976. GetNextInstruction(hp1, hp2) and
  4977. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4978. MatchOperand(Taicpu(p).oper[0]^,0) and
  4979. (Taicpu(p).oper[1]^.typ = top_reg) and
  4980. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4981. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4982. { mov reg1,0
  4983. bts reg1,operand1 --> mov reg1,operand2
  4984. or reg1,operand2 bts reg1,operand1}
  4985. begin
  4986. Taicpu(hp2).opcode:=A_MOV;
  4987. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4988. asml.remove(hp1);
  4989. insertllitem(hp2,hp2.next,hp1);
  4990. RemoveCurrentp(p, hp1);
  4991. Result:=true;
  4992. exit;
  4993. end;
  4994. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4995. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4996. GetNextInstruction(hp1, hp2) and
  4997. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4998. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4999. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  5000. { change
  5001. mov reg1,reg2
  5002. sub reg3,reg2
  5003. cmp reg3,reg1
  5004. into
  5005. mov reg1,reg2
  5006. sub reg3,reg2
  5007. }
  5008. begin
  5009. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  5010. RemoveInstruction(hp2);
  5011. Result:=true;
  5012. exit;
  5013. end;
  5014. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  5015. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  5016. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5017. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  5018. begin
  5019. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  5020. {$ifdef x86_64}
  5021. { Convert:
  5022. movq x(ref),%reg64
  5023. shrq y,%reg64
  5024. To:
  5025. movl x+4(ref),%reg32
  5026. shrl y-32,%reg32 (Remove if y = 32)
  5027. }
  5028. if (taicpu(p).opsize = S_Q) and
  5029. (taicpu(hp1).opcode = A_SHR) and
  5030. (taicpu(hp1).oper[0]^.val >= 32) then
  5031. begin
  5032. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5033. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  5034. { Convert to 32-bit }
  5035. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  5036. taicpu(p).opsize := S_L;
  5037. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  5038. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  5039. if (taicpu(hp1).oper[0]^.val = 32) then
  5040. begin
  5041. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  5042. RemoveInstruction(hp1);
  5043. end
  5044. else
  5045. begin
  5046. { This will potentially open up more arithmetic operations since
  5047. the peephole optimizer now has a big hint that only the lower
  5048. 32 bits are currently in use (and opcodes are smaller in size) }
  5049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  5050. taicpu(hp1).opsize := S_L;
  5051. Dec(taicpu(hp1).oper[0]^.val, 32);
  5052. DebugMsg(SPeepholeOptimization + PreMessage +
  5053. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  5054. end;
  5055. Result := True;
  5056. Exit;
  5057. end;
  5058. {$endif x86_64}
  5059. { Convert:
  5060. movl x(ref),%reg
  5061. shrl $24,%reg
  5062. To:
  5063. movzbl x+3(ref),%reg
  5064. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  5065. Also accept sar instead of shr, but convert to movsx instead of movzx
  5066. }
  5067. if taicpu(hp1).opcode = A_SHR then
  5068. MovUnaligned := A_MOVZX
  5069. else
  5070. MovUnaligned := A_MOVSX;
  5071. NewSize := S_NO;
  5072. NewOffset := 0;
  5073. case taicpu(p).opsize of
  5074. S_B:
  5075. { No valid combinations };
  5076. S_W:
  5077. if (taicpu(hp1).oper[0]^.val = 8) then
  5078. begin
  5079. NewSize := S_BW;
  5080. NewOffset := 1;
  5081. end;
  5082. S_L:
  5083. case taicpu(hp1).oper[0]^.val of
  5084. 16:
  5085. begin
  5086. NewSize := S_WL;
  5087. NewOffset := 2;
  5088. end;
  5089. 24:
  5090. begin
  5091. NewSize := S_BL;
  5092. NewOffset := 3;
  5093. end;
  5094. else
  5095. ;
  5096. end;
  5097. {$ifdef x86_64}
  5098. S_Q:
  5099. case taicpu(hp1).oper[0]^.val of
  5100. 32:
  5101. begin
  5102. if taicpu(hp1).opcode = A_SAR then
  5103. begin
  5104. { 32-bit to 64-bit is a distinct instruction }
  5105. MovUnaligned := A_MOVSXD;
  5106. NewSize := S_LQ;
  5107. NewOffset := 4;
  5108. end
  5109. else
  5110. { Should have been handled by MovShr2Mov above }
  5111. InternalError(2022081811);
  5112. end;
  5113. 48:
  5114. begin
  5115. NewSize := S_WQ;
  5116. NewOffset := 6;
  5117. end;
  5118. 56:
  5119. begin
  5120. NewSize := S_BQ;
  5121. NewOffset := 7;
  5122. end;
  5123. else
  5124. ;
  5125. end;
  5126. {$endif x86_64}
  5127. else
  5128. InternalError(2022081810);
  5129. end;
  5130. if (NewSize <> S_NO) and
  5131. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5132. begin
  5133. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5134. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5135. debug_op2str(MovUnaligned);
  5136. {$ifdef x86_64}
  5137. if MovUnaligned <> A_MOVSXD then
  5138. { Don't add size suffix for MOVSXD }
  5139. {$endif x86_64}
  5140. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5141. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5142. taicpu(p).opcode := MovUnaligned;
  5143. taicpu(p).opsize := NewSize;
  5144. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5145. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5146. RemoveInstruction(hp1);
  5147. Result := True;
  5148. Exit;
  5149. end;
  5150. end;
  5151. { Backward optimisation shared with OptPass2MOV }
  5152. if FuncMov2Func(p, hp1) then
  5153. begin
  5154. Result := True;
  5155. Exit;
  5156. end;
  5157. end;
  5158. function TX86AsmOptimizer.OptPass1MOVD(var p : tai) : boolean;
  5159. { This function also handles the 64-bit version, MOVQ }
  5160. var
  5161. hp1: tai;
  5162. begin
  5163. Result:=false;
  5164. { Change:
  5165. movd/q %xmm0, %reg
  5166. ...
  5167. movl/q %reg, (ref)
  5168. (dealloc %reg)
  5169. To:
  5170. movd/q %xmm0, (ref)
  5171. }
  5172. if MatchOpType(taicpu(p),top_reg,top_reg) and
  5173. (GetRegType(taicpu(p).oper[0]^.reg)=R_MMREGISTER) and
  5174. (GetRegType(taicpu(p).oper[1]^.reg)=R_INTREGISTER) and
  5175. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  5176. MatchInstruction(hp1, A_MOV, []) and
  5177. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^.reg) and
  5178. (taicpu(hp1).oper[1]^.typ=top_ref) and
  5179. not RegInRef(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.ref^) then
  5180. begin
  5181. TransferUsedRegs(TmpUsedRegs);
  5182. UpdateUsedRegsBetween(TmpUsedRegs,p,hp1);
  5183. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs) then
  5184. begin
  5185. if (
  5186. { Instructions are always adjacent under -O2 and under }
  5187. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5188. (
  5189. (
  5190. (taicpu(hp1).oper[1]^.ref^.base=NR_NO) or
  5191. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.base,p,hp1)
  5192. ) and
  5193. (
  5194. (taicpu(hp1).oper[1]^.ref^.index=NR_NO) or
  5195. not RegModifiedBetween(taicpu(hp1).oper[1]^.ref^.index,p,hp1)
  5196. )
  5197. )
  5198. ) then
  5199. begin
  5200. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1a)',p);
  5201. taicpu(p).loadref(1,taicpu(hp1).oper[1]^.ref^);
  5202. { loadref increases the reference count, so decrement it again }
  5203. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5204. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5205. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5206. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5207. RemoveInstruction(hp1);
  5208. Include(OptsToCheck, aoc_ForceNewIteration);
  5209. end
  5210. else if not RegModifiedBetween(taicpu(p).oper[0]^.reg,p,hp1) then
  5211. begin
  5212. { Still possible to optimise if hp1 is converted instead }
  5213. DebugMsg(SPeepholeOptimization+'Merged (V)MOVD/(V)MOVQ and MOV to eliminate intermediate register (MovD/QMov2MovD/Q 1b)',hp1);
  5214. { Decrement the reference prior to replacing it }
  5215. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  5216. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  5217. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  5218. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  5219. taicpu(hp1).opcode:=taicpu(p).opcode;
  5220. taicpu(hp1).opsize:=taicpu(p).opsize;
  5221. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  5222. TransferUsedRegs(TmpUsedRegs);
  5223. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,TmpUsedRegs);
  5224. RemoveCurrentP(p);
  5225. Result:=True;
  5226. Exit;
  5227. end;
  5228. end;
  5229. end;
  5230. end;
  5231. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5232. var
  5233. hp1 : tai;
  5234. begin
  5235. Result:=false;
  5236. if taicpu(p).ops <> 2 then
  5237. exit;
  5238. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5239. GetNextInstruction(p,hp1) then
  5240. begin
  5241. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5242. (taicpu(hp1).ops = 2) then
  5243. begin
  5244. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5245. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5246. { movXX reg1, mem1 or movXX mem1, reg1
  5247. movXX mem2, reg2 movXX reg2, mem2}
  5248. begin
  5249. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5250. { movXX reg1, mem1 or movXX mem1, reg1
  5251. movXX mem2, reg1 movXX reg2, mem1}
  5252. begin
  5253. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5254. begin
  5255. { Removes the second statement from
  5256. movXX reg1, mem1/reg2
  5257. movXX mem1/reg2, reg1
  5258. }
  5259. if taicpu(p).oper[0]^.typ=top_reg then
  5260. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5261. { Removes the second statement from
  5262. movXX mem1/reg1, reg2
  5263. movXX reg2, mem1/reg1
  5264. }
  5265. if (taicpu(p).oper[1]^.typ=top_reg) and
  5266. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5267. begin
  5268. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5269. RemoveInstruction(hp1);
  5270. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5271. Result:=true;
  5272. exit;
  5273. end
  5274. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5275. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5276. begin
  5277. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5278. RemoveInstruction(hp1);
  5279. Result:=true;
  5280. exit;
  5281. end;
  5282. end
  5283. end;
  5284. end;
  5285. end;
  5286. end;
  5287. end;
  5288. {$ifndef i8086}
  5289. function TX86AsmOptimizer.OptPass1NOT(var p: tai): Boolean;
  5290. var
  5291. hp1, p_next: tai;
  5292. flags_used: Boolean;
  5293. procedure Do_NotAnd2Andn1;
  5294. var
  5295. tempoper: poper;
  5296. begin
  5297. { Change "and %reg1,%reg2" to "andn %reg2,%reg1,%reg2" }
  5298. taicpu(hp1).allocate_oper(3);
  5299. taicpu(hp1).ops:=3;
  5300. { Swap the 1st and 2nd operands by swapping their pointers }
  5301. tempoper:=taicpu(hp1).oper[1];
  5302. taicpu(hp1).oper[1]:=taicpu(hp1).oper[0];
  5303. taicpu(hp1).oper[0]:=tempoper;
  5304. taicpu(hp1).loadreg(2, tempoper^.reg);
  5305. taicpu(hp1).opcode:=A_ANDN;
  5306. end;
  5307. begin
  5308. Result:=False;
  5309. { Don't optimise this for size as ANDN is bigger than NOT and AND combined }
  5310. if not (cs_opt_size in current_settings.optimizerswitches) and
  5311. (CPUX86_HAS_BMI2 in cpu_capabilities[current_settings.optimizecputype]) then
  5312. begin
  5313. { Convert: To:
  5314. not %reg1 andn %reg2,%reg1,%reg2
  5315. and %reg1,%reg2 not %reg1
  5316. Or remove "not %reg1" completely if %reg1 is deallocated.
  5317. This breaks the dependency chain.
  5318. }
  5319. if (taicpu(p).oper[0]^.typ=top_reg) and
  5320. { ANDN only supports 32-bit and 64-bit }
  5321. (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5322. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) and
  5323. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5324. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[0]^.reg) and
  5325. (taicpu(hp1).oper[1]^.typ=top_reg) and
  5326. (taicpu(hp1).oper[1]^.reg<>taicpu(p).oper[0]^.reg) and
  5327. (
  5328. { p and hp1 are adjacent on -O2 and below }
  5329. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5330. not RegModifiedBetween(taicpu(hp1).oper[1]^.reg,p,hp1)
  5331. ) then
  5332. begin
  5333. p_next:=tai(p.Next);
  5334. TransferUsedRegs(TmpUsedRegs);
  5335. UpdateUsedRegsBetween(TmpUsedRegs, p_next, hp1);
  5336. { Make a note as to whether the flags are in use because
  5337. RegUsedAfterInstruction might change the state }
  5338. flags_used:=RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs);
  5339. if not RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  5340. begin
  5341. DebugMsg(SPeepholeOptimization + 'NotAnd2Andn 1 done', p);
  5342. Do_NotAnd2Andn1;
  5343. RemoveCurrentP(p, p_next);
  5344. Result:=True;
  5345. Exit;
  5346. end
  5347. else if not flags_used then
  5348. begin
  5349. DebugMsg(SPeepholeOptimization + 'NotAnd2AndnNot 1 done', p);
  5350. Do_NotAnd2Andn1;
  5351. asml.Remove(p);
  5352. asml.InsertAfter(p, hp1);
  5353. AllocRegBetween(taicpu(p).oper[0]^.reg, hp1, p, TmpUsedRegs);
  5354. { Make sure the pass 2 iteration continues from the
  5355. correct place, right after p }
  5356. p:=p_next;
  5357. Result:=True;
  5358. Exit;
  5359. end;
  5360. end;
  5361. end;
  5362. end;
  5363. {$endif not i8086}
  5364. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5365. var
  5366. hp1 : tai;
  5367. begin
  5368. result:=false;
  5369. { replace
  5370. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5371. MovX %mreg2,%mreg1
  5372. dealloc %mreg2
  5373. by
  5374. <Op>X %mreg2,%mreg1
  5375. ?
  5376. }
  5377. if GetNextInstruction(p,hp1) and
  5378. { we mix single and double opperations here because we assume that the compiler
  5379. generates vmovapd only after double operations and vmovaps only after single operations }
  5380. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5381. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5382. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5383. (taicpu(p).oper[0]^.typ=top_reg) then
  5384. begin
  5385. TransferUsedRegs(TmpUsedRegs);
  5386. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5387. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5388. begin
  5389. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5390. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5391. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5392. RemoveInstruction(hp1);
  5393. result:=true;
  5394. end;
  5395. end;
  5396. end;
  5397. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5398. var
  5399. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5400. JumpLabel, JumpLabel_dist: TAsmLabel;
  5401. FirstValue, SecondValue: TCGInt;
  5402. function OptimizeJump(var InputP: tai): Boolean;
  5403. var
  5404. TempBool: Boolean;
  5405. begin
  5406. Result := False;
  5407. TempBool := True;
  5408. if DoJumpOptimizations(InputP, TempBool) or
  5409. not TempBool then
  5410. begin
  5411. Result := True;
  5412. if Assigned(InputP) then
  5413. begin
  5414. { CollapseZeroDistJump will be set to the label or an align
  5415. before it after the jump if it optimises, whether or not
  5416. the label is live or dead }
  5417. if (InputP.typ = ait_align) or
  5418. (
  5419. (InputP.typ = ait_label) and
  5420. not (tai_label(InputP).labsym.is_used)
  5421. ) then
  5422. GetNextInstruction(InputP, InputP);
  5423. end;
  5424. Exit;
  5425. end;
  5426. end;
  5427. begin
  5428. Result := False;
  5429. if (taicpu(p).oper[0]^.typ = top_const) and
  5430. (taicpu(p).oper[0]^.val <> -1) then
  5431. begin
  5432. { Convert unsigned maximum constants to -1 to aid optimisation }
  5433. case taicpu(p).opsize of
  5434. S_B:
  5435. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5436. begin
  5437. taicpu(p).oper[0]^.val := -1;
  5438. Result := True;
  5439. Exit;
  5440. end;
  5441. S_W:
  5442. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5443. begin
  5444. taicpu(p).oper[0]^.val := -1;
  5445. Result := True;
  5446. Exit;
  5447. end;
  5448. S_L:
  5449. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5450. begin
  5451. taicpu(p).oper[0]^.val := -1;
  5452. Result := True;
  5453. Exit;
  5454. end;
  5455. {$ifdef x86_64}
  5456. S_Q:
  5457. { Storing anything greater than $7FFFFFFF is not possible so do
  5458. nothing };
  5459. {$endif x86_64}
  5460. else
  5461. InternalError(2021121001);
  5462. end;
  5463. end;
  5464. if GetNextInstruction(p, hp1) and
  5465. TrySwapMovCmp(p, hp1) then
  5466. begin
  5467. Result := True;
  5468. Exit;
  5469. end;
  5470. p_label := nil;
  5471. JumpLabel := nil;
  5472. if MatchInstruction(hp1, A_Jcc, []) then
  5473. begin
  5474. if OptimizeJump(hp1) then
  5475. begin
  5476. Result := True;
  5477. if Assigned(hp1) then
  5478. begin
  5479. { CollapseZeroDistJump will be set to the label or an align
  5480. before it after the jump if it optimises, whether or not
  5481. the label is live or dead }
  5482. if (hp1.typ = ait_align) or
  5483. (
  5484. (hp1.typ = ait_label) and
  5485. not (tai_label(hp1).labsym.is_used)
  5486. ) then
  5487. GetNextInstruction(hp1, hp1);
  5488. end;
  5489. TransferUsedRegs(TmpUsedRegs);
  5490. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5491. if not Assigned(hp1) or
  5492. (
  5493. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5494. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5495. ) then
  5496. begin
  5497. { No more conditional jumps; conditional statement is no longer required }
  5498. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5499. RemoveCurrentP(p);
  5500. end;
  5501. Exit;
  5502. end;
  5503. if IsJumpToLabel(taicpu(hp1)) then
  5504. begin
  5505. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5506. if Assigned(JumpLabel) then
  5507. p_label := getlabelwithsym(JumpLabel);
  5508. end;
  5509. end;
  5510. { Search for:
  5511. test $x,(reg/ref)
  5512. jne @lbl1
  5513. test $y,(reg/ref) (same register or reference)
  5514. jne @lbl1
  5515. Change to:
  5516. test $(x or y),(reg/ref)
  5517. jne @lbl1
  5518. (Note, this doesn't work with je instead of jne)
  5519. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5520. Also search for:
  5521. test $x,(reg/ref)
  5522. je @lbl1
  5523. ...
  5524. test $y,(reg/ref)
  5525. je/jne @lbl2
  5526. If (x or y) = x, then the second jump is deterministic
  5527. }
  5528. if (
  5529. (
  5530. (taicpu(p).oper[0]^.typ = top_const) or
  5531. (
  5532. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5533. (taicpu(p).oper[0]^.typ = top_reg) and
  5534. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5535. )
  5536. ) and
  5537. MatchInstruction(hp1, A_JCC, [])
  5538. ) then
  5539. begin
  5540. if (taicpu(p).oper[0]^.typ = top_reg) and
  5541. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5542. FirstValue := -1
  5543. else
  5544. FirstValue := taicpu(p).oper[0]^.val;
  5545. { If we have several test/jne's in a row, it might be the case that
  5546. the second label doesn't go to the same location, but the one
  5547. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5548. so accommodate for this with a while loop.
  5549. }
  5550. hp1_last := hp1;
  5551. while (
  5552. (
  5553. (taicpu(p).oper[1]^.typ = top_reg) and
  5554. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5555. ) or GetNextInstruction(hp1_last, p_dist)
  5556. ) and (p_dist.typ = ait_instruction) do
  5557. begin
  5558. if (
  5559. (
  5560. (taicpu(p_dist).opcode = A_TEST) and
  5561. (
  5562. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5563. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5564. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5565. )
  5566. ) or
  5567. (
  5568. { cmp 0,%reg = test %reg,%reg }
  5569. (taicpu(p_dist).opcode = A_CMP) and
  5570. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5571. )
  5572. ) and
  5573. { Make sure the destination operands are actually the same }
  5574. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5575. GetNextInstruction(p_dist, hp1_dist) and
  5576. MatchInstruction(hp1_dist, A_JCC, []) then
  5577. begin
  5578. if OptimizeJump(hp1_dist) then
  5579. begin
  5580. Result := True;
  5581. Exit;
  5582. end;
  5583. if
  5584. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5585. (
  5586. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5587. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5588. ) then
  5589. SecondValue := -1
  5590. else
  5591. SecondValue := taicpu(p_dist).oper[0]^.val;
  5592. { If both of the TEST constants are identical, delete the
  5593. second TEST that is unnecessary (be careful though, just
  5594. in case the flags are modified in between) }
  5595. if (FirstValue = SecondValue) then
  5596. begin
  5597. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5598. begin
  5599. { Since the second jump's condition is a subset of the first, we
  5600. know it will never branch because the first jump dominates it.
  5601. Get it out of the way now rather than wait for the jump
  5602. optimisations for a speed boost. }
  5603. if IsJumpToLabel(taicpu(hp1_dist)) then
  5604. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5605. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5606. RemoveInstruction(hp1_dist);
  5607. Result := True;
  5608. end
  5609. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5610. begin
  5611. { If the inverse of the first condition is a subset of the second,
  5612. the second one will definitely branch if the first one doesn't }
  5613. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5614. { We can remove the TEST instruction too }
  5615. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5616. RemoveInstruction(p_dist);
  5617. MakeUnconditional(taicpu(hp1_dist));
  5618. RemoveDeadCodeAfterJump(hp1_dist);
  5619. { Since the jump is now unconditional, we can't
  5620. continue any further with this particular
  5621. optimisation. The original TEST is still intact
  5622. though, so there might be something else we can
  5623. do }
  5624. Include(OptsToCheck, aoc_ForceNewIteration);
  5625. Break;
  5626. end;
  5627. if Result or
  5628. { If a jump wasn't removed or made unconditional, only
  5629. remove the identical TEST instruction if the flags
  5630. weren't modified }
  5631. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5632. begin
  5633. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5634. RemoveInstruction(p_dist);
  5635. { If the jump was removed or made unconditional, we
  5636. don't need to allocate NR_DEFAULTFLAGS over the
  5637. entire range }
  5638. if not Result then
  5639. begin
  5640. { Mark the flags as 'in use' over the entire range }
  5641. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5642. { Speed gain - continue search from the Jcc instruction }
  5643. hp1_last := hp1_dist;
  5644. { Only the TEST instruction was removed, and the
  5645. original was unchanged, so we can safely do
  5646. another iteration of the while loop }
  5647. Include(OptsToCheck, aoc_ForceNewIteration);
  5648. Continue;
  5649. end;
  5650. Exit;
  5651. end;
  5652. end;
  5653. hp1_last := nil;
  5654. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5655. (
  5656. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5657. { Always adjacent under -O2 and under }
  5658. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5659. (
  5660. GetNextInstruction(hp1, hp1_last) and
  5661. (hp1_last = p_dist)
  5662. )
  5663. ) and
  5664. (
  5665. (
  5666. { Test the following variant:
  5667. test $x,(reg/ref)
  5668. jne @lbl1
  5669. test $y,(reg/ref)
  5670. je @lbl2
  5671. @lbl1:
  5672. Becomes:
  5673. test $(x or y),(reg/ref)
  5674. je @lbl2
  5675. @lbl1: (may become a dead label)
  5676. }
  5677. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5678. GetNextInstruction(hp1_dist, hp1_last) and
  5679. (hp1_last = p_label)
  5680. ) or
  5681. (
  5682. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5683. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5684. then the second jump will never branch, so it can also be
  5685. removed regardless of where it goes }
  5686. (
  5687. (FirstValue = -1) or
  5688. (SecondValue = -1) or
  5689. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5690. )
  5691. )
  5692. ) then
  5693. begin
  5694. { Same jump location... can be a register since nothing's changed }
  5695. { If any of the entries are equivalent to test %reg,%reg, then the
  5696. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5697. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5698. if (hp1_last = p_label) then
  5699. begin
  5700. { Variant }
  5701. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5702. RemoveInstruction(p_dist);
  5703. if Assigned(JumpLabel) then
  5704. JumpLabel.decrefs;
  5705. RemoveInstruction(hp1);
  5706. end
  5707. else
  5708. begin
  5709. { Only remove the second test if no jumps or other conditional instructions follow }
  5710. TransferUsedRegs(TmpUsedRegs);
  5711. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5712. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5713. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5714. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5715. begin
  5716. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5717. RemoveInstruction(p_dist);
  5718. { Remove the first jump, not the second, to keep
  5719. any register deallocations between the second
  5720. TEST/JNE pair in the same place. Aids future
  5721. optimisation. }
  5722. if Assigned(JumpLabel) then
  5723. JumpLabel.decrefs;
  5724. RemoveInstruction(hp1);
  5725. end
  5726. else
  5727. begin
  5728. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5729. if IsJumpToLabel(taicpu(hp1_dist)) then
  5730. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5731. { Remove second jump in this instance }
  5732. RemoveInstruction(hp1_dist);
  5733. end;
  5734. end;
  5735. Result := True;
  5736. Exit;
  5737. end;
  5738. end;
  5739. if { If -O2 and under, it may stop on any old instruction }
  5740. (cs_opt_level3 in current_settings.optimizerswitches) and
  5741. (taicpu(p).oper[1]^.typ = top_reg) and
  5742. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5743. begin
  5744. hp1_last := p_dist;
  5745. Continue;
  5746. end;
  5747. Break;
  5748. end;
  5749. end;
  5750. { Search for:
  5751. test %reg,%reg
  5752. j(c1) @lbl1
  5753. ...
  5754. @lbl:
  5755. test %reg,%reg (same register)
  5756. j(c2) @lbl2
  5757. If c2 is a subset of c1, change to:
  5758. test %reg,%reg
  5759. j(c1) @lbl2
  5760. (@lbl1 may become a dead label as a result)
  5761. }
  5762. if (taicpu(p).oper[1]^.typ = top_reg) and
  5763. (taicpu(p).oper[0]^.typ = top_reg) and
  5764. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5765. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5766. Assigned(p_label) and
  5767. GetNextInstruction(p_label, p_dist) and
  5768. MatchInstruction(p_dist, A_TEST, []) and
  5769. { It's fine if the second test uses smaller sub-registers }
  5770. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5771. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5772. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5773. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5774. GetNextInstruction(p_dist, hp1_dist) and
  5775. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5776. begin
  5777. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5778. if JumpLabel = JumpLabel_dist then
  5779. { This is an infinite loop }
  5780. Exit;
  5781. { Best optimisation when the first condition is a subset (or equal) of the second }
  5782. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5783. begin
  5784. { Any registers used here will already be allocated }
  5785. if Assigned(JumpLabel) then
  5786. JumpLabel.DecRefs;
  5787. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5788. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5789. Result := True;
  5790. Exit;
  5791. end;
  5792. end;
  5793. end;
  5794. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5795. var
  5796. hp1, hp2: tai;
  5797. ActiveReg: TRegister;
  5798. OldOffset: asizeint;
  5799. ThisConst: TCGInt;
  5800. function RegDeallocated: Boolean;
  5801. begin
  5802. TransferUsedRegs(TmpUsedRegs);
  5803. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5804. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5805. end;
  5806. begin
  5807. result:=false;
  5808. hp1 := nil;
  5809. { replace
  5810. addX const,%reg1
  5811. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5812. dealloc %reg1
  5813. by
  5814. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5815. }
  5816. if MatchOpType(taicpu(p),top_const,top_reg) then
  5817. begin
  5818. ActiveReg := taicpu(p).oper[1]^.reg;
  5819. { Ensures the entire register was updated }
  5820. if (taicpu(p).opsize >= S_L) and
  5821. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5822. MatchInstruction(hp1,A_LEA,[]) and
  5823. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5824. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5825. (
  5826. { Cover the case where the register in the reference is also the destination register }
  5827. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5828. (
  5829. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5830. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5831. RegDeallocated
  5832. )
  5833. ) then
  5834. begin
  5835. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5836. {$push}
  5837. {$R-}{$Q-}
  5838. { Explicitly disable overflow checking for these offset calculation
  5839. as those do not matter for the final result }
  5840. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5841. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5842. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5843. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5844. {$pop}
  5845. {$ifdef x86_64}
  5846. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5847. begin
  5848. { Overflow; abort }
  5849. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5850. end
  5851. else
  5852. {$endif x86_64}
  5853. begin
  5854. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5855. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5856. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5857. RemoveCurrentP(p, hp1)
  5858. else
  5859. RemoveCurrentP(p);
  5860. result:=true;
  5861. Exit;
  5862. end;
  5863. end;
  5864. if (
  5865. { Save calling GetNextInstructionUsingReg again }
  5866. Assigned(hp1) or
  5867. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5868. ) and
  5869. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5870. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5871. begin
  5872. { Make sure the flags aren't in use by the second operation }
  5873. TransferUsedRegs(TmpUsedRegs);
  5874. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  5875. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5876. begin
  5877. if taicpu(hp1).oper[0]^.typ = top_const then
  5878. begin
  5879. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5880. if taicpu(hp1).opcode = A_ADD then
  5881. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5882. else
  5883. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5884. Result := True;
  5885. { Handle any overflows }
  5886. case taicpu(p).opsize of
  5887. S_B:
  5888. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5889. S_W:
  5890. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5891. S_L:
  5892. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5893. {$ifdef x86_64}
  5894. S_Q:
  5895. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5896. { Overflow; abort }
  5897. Result := False
  5898. else
  5899. taicpu(p).oper[0]^.val := ThisConst;
  5900. {$endif x86_64}
  5901. else
  5902. InternalError(2021102610);
  5903. end;
  5904. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5905. if Result then
  5906. begin
  5907. if (taicpu(p).oper[0]^.val < 0) and
  5908. (
  5909. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5910. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5911. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5912. ) then
  5913. begin
  5914. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5915. taicpu(p).opcode := A_SUB;
  5916. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5917. end
  5918. else
  5919. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5920. RemoveInstruction(hp1);
  5921. end;
  5922. end
  5923. else
  5924. begin
  5925. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5926. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5927. Asml.Remove(p);
  5928. Asml.InsertAfter(p, hp1);
  5929. p := hp1;
  5930. Result := True;
  5931. Exit;
  5932. end;
  5933. end;
  5934. end;
  5935. if DoArithCombineOpt(p) then
  5936. Result:=true;
  5937. end;
  5938. end;
  5939. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5940. var
  5941. hp1, hp2: tai;
  5942. ref: Integer;
  5943. saveref: treference;
  5944. offsetcalc: Int64;
  5945. TempReg: TRegister;
  5946. Multiple: TCGInt;
  5947. Adjacent, IntermediateRegDiscarded: Boolean;
  5948. begin
  5949. Result:=false;
  5950. { play save and throw an error if LEA uses a seg register prefix,
  5951. this is most likely an error somewhere else }
  5952. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5953. internalerror(2022022001);
  5954. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5955. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5956. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5957. (
  5958. { do not mess with leas accessing the stack pointer
  5959. unless it's a null operation }
  5960. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5961. (
  5962. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5963. (taicpu(p).oper[0]^.ref^.offset = 0)
  5964. )
  5965. ) and
  5966. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5967. begin
  5968. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5969. begin
  5970. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5971. begin
  5972. taicpu(p).opcode := A_MOV;
  5973. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5974. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5975. end
  5976. else
  5977. begin
  5978. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5979. RemoveCurrentP(p);
  5980. end;
  5981. Result:=true;
  5982. exit;
  5983. end
  5984. else if (
  5985. { continue to use lea to adjust the stack pointer,
  5986. it is the recommended way, but only if not optimizing for size }
  5987. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5988. (cs_opt_size in current_settings.optimizerswitches)
  5989. ) and
  5990. { If the flags register is in use, don't change the instruction
  5991. to an ADD otherwise this will scramble the flags. [Kit] }
  5992. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5993. ConvertLEA(taicpu(p)) then
  5994. begin
  5995. Result:=true;
  5996. exit;
  5997. end;
  5998. end;
  5999. { Don't optimise if the stack or frame pointer is the destination register }
  6000. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  6001. Exit;
  6002. if GetNextInstruction(p,hp1) and
  6003. (hp1.typ=ait_instruction) then
  6004. begin
  6005. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6006. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6007. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  6008. begin
  6009. TransferUsedRegs(TmpUsedRegs);
  6010. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6011. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6012. begin
  6013. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6014. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  6015. RemoveInstruction(hp1);
  6016. result:=true;
  6017. exit;
  6018. end;
  6019. end;
  6020. { changes
  6021. lea <ref1>, reg1
  6022. <op> ...,<ref. with reg1>,...
  6023. to
  6024. <op> ...,<ref1>,... }
  6025. { find a reference which uses reg1 }
  6026. 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
  6027. ref:=0
  6028. 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
  6029. ref:=1
  6030. else
  6031. ref:=-1;
  6032. if (ref<>-1) and
  6033. { reg1 must be either the base or the index }
  6034. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  6035. begin
  6036. { reg1 can be removed from the reference }
  6037. saveref:=taicpu(hp1).oper[ref]^.ref^;
  6038. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  6039. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  6040. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  6041. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  6042. else
  6043. Internalerror(2019111201);
  6044. { check if the can insert all data of the lea into the second instruction }
  6045. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  6046. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  6047. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  6048. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  6049. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  6050. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  6051. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  6052. {$ifdef x86_64}
  6053. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  6054. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  6055. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  6056. )
  6057. {$endif x86_64}
  6058. then
  6059. begin
  6060. { reg1 might not used by the second instruction after it is remove from the reference }
  6061. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  6062. begin
  6063. TransferUsedRegs(TmpUsedRegs);
  6064. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6065. { reg1 is not updated so it might not be used afterwards }
  6066. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6067. begin
  6068. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  6069. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  6070. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6071. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6072. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6073. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  6074. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  6075. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  6076. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  6077. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  6078. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  6079. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6080. RemoveCurrentP(p, hp1);
  6081. result:=true;
  6082. exit;
  6083. end
  6084. end;
  6085. end;
  6086. { recover }
  6087. taicpu(hp1).oper[ref]^.ref^:=saveref;
  6088. end;
  6089. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  6090. if Adjacent or
  6091. { Check further ahead (up to 2 instructions ahead for -O2) }
  6092. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  6093. begin
  6094. { Check common LEA/LEA conditions }
  6095. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  6096. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  6097. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  6098. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  6099. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  6100. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  6101. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  6102. (
  6103. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  6104. calling it (since it calls GetNextInstruction) }
  6105. Adjacent or
  6106. (
  6107. (
  6108. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  6109. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  6110. ) and (
  6111. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  6112. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6113. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  6114. )
  6115. )
  6116. ) then
  6117. begin
  6118. TransferUsedRegs(TmpUsedRegs);
  6119. hp2 := p;
  6120. repeat
  6121. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6122. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  6123. IntermediateRegDiscarded :=
  6124. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  6125. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  6126. { changes
  6127. lea offset1(regX,scale), reg1
  6128. lea offset2(reg1,reg1), reg2
  6129. to
  6130. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  6131. and
  6132. lea offset1(regX,scale1), reg1
  6133. lea offset2(reg1,scale2), reg2
  6134. to
  6135. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  6136. and
  6137. lea offset1(regX,scale1), reg1
  6138. lea offset2(reg3,reg1,scale2), reg2
  6139. to
  6140. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  6141. ... so long as the final scale does not exceed 8
  6142. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  6143. }
  6144. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6145. (
  6146. { Don't optimise if size is a concern and the intermediate register remains in use }
  6147. IntermediateRegDiscarded or
  6148. (
  6149. not (cs_opt_size in current_settings.optimizerswitches) and
  6150. { If the intermediate register is not discarded, it must not
  6151. appear in the first LEA's reference. (Fixes #41166) }
  6152. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6153. )
  6154. ) and
  6155. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6156. (
  6157. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  6158. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6159. ) and (
  6160. (
  6161. { lea (reg1,scale2), reg2 variant }
  6162. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  6163. (
  6164. Adjacent or
  6165. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  6166. ) and
  6167. (
  6168. (
  6169. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  6170. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  6171. ) or (
  6172. { lea (regX,regX), reg1 variant }
  6173. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  6174. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  6175. )
  6176. )
  6177. ) or (
  6178. { lea (reg1,reg1), reg1 variant }
  6179. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6180. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  6181. )
  6182. ) then
  6183. begin
  6184. { Make everything homogeneous to make calculations easier }
  6185. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  6186. begin
  6187. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  6188. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  6189. taicpu(p).oper[0]^.ref^.scalefactor := 2
  6190. else
  6191. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  6192. taicpu(p).oper[0]^.ref^.base := NR_NO;
  6193. end;
  6194. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6195. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6196. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6197. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6198. begin
  6199. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6200. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  6201. begin
  6202. { Put the register to change in the index register }
  6203. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  6204. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  6205. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  6206. end;
  6207. { Change lea (reg,reg) to lea(,reg,2) }
  6208. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  6209. begin
  6210. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  6211. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  6212. end;
  6213. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  6214. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6215. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  6216. { Just to prevent miscalculations }
  6217. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  6218. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  6219. else
  6220. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  6221. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6222. if IntermediateRegDiscarded then
  6223. begin
  6224. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  6225. RemoveCurrentP(p);
  6226. end
  6227. else
  6228. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  6229. result:=true;
  6230. exit;
  6231. end;
  6232. end;
  6233. { changes
  6234. lea offset1(regX), reg1
  6235. lea offset2(reg1), reg2
  6236. to
  6237. lea offset1+offset2(regX), reg2 }
  6238. if (
  6239. { Don't optimise if size is a concern and the intermediate register remains in use }
  6240. IntermediateRegDiscarded or
  6241. (
  6242. not (cs_opt_size in current_settings.optimizerswitches) and
  6243. { If the intermediate register is not discarded, it must not
  6244. appear in the first LEA's reference. (Fixes #41166) }
  6245. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  6246. )
  6247. ) and
  6248. (
  6249. (
  6250. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6251. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6252. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6253. ) or (
  6254. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6255. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6256. (
  6257. (
  6258. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6259. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6260. ) or (
  6261. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6262. (
  6263. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6264. (
  6265. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6266. (
  6267. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6268. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6269. )
  6270. )
  6271. )
  6272. )
  6273. )
  6274. )
  6275. ) then
  6276. begin
  6277. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6278. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6279. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6280. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6281. begin
  6282. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6283. begin
  6284. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6285. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6286. { if the register is used as index and base, we have to increase for base as well
  6287. and adapt base }
  6288. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6289. begin
  6290. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6291. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6292. end;
  6293. end
  6294. else
  6295. begin
  6296. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6297. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6298. end;
  6299. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6300. begin
  6301. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6302. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6303. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6304. { Catch the situation where the base = index
  6305. and treat this as *2. The scalefactor of
  6306. p will be 0 or 1 due to the conditional
  6307. checks above. Fixes i40647 }
  6308. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6309. else
  6310. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6311. end;
  6312. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6313. if IntermediateRegDiscarded then
  6314. begin
  6315. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6316. RemoveCurrentP(p);
  6317. end
  6318. else
  6319. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6320. result:=true;
  6321. exit;
  6322. end;
  6323. end;
  6324. end;
  6325. { Change:
  6326. leal/q $x(%reg1),%reg2
  6327. ...
  6328. shll/q $y,%reg2
  6329. To:
  6330. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6331. }
  6332. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6333. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6334. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6335. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6336. (taicpu(hp1).oper[0]^.val <= 3) then
  6337. begin
  6338. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6339. TransferUsedRegs(TmpUsedRegs);
  6340. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6341. if
  6342. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6343. (this works even if scalefactor is zero) }
  6344. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6345. { Ensure offset doesn't go out of bounds }
  6346. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6347. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6348. (
  6349. (
  6350. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6351. (
  6352. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6353. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6354. (
  6355. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6356. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6357. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6358. )
  6359. )
  6360. ) or (
  6361. (
  6362. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6363. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6364. ) and
  6365. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6366. )
  6367. ) then
  6368. begin
  6369. repeat
  6370. with taicpu(p).oper[0]^.ref^ do
  6371. begin
  6372. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6373. if index = base then
  6374. begin
  6375. if Multiple > 4 then
  6376. { Optimisation will no longer work because resultant
  6377. scale factor will exceed 8 }
  6378. Break;
  6379. base := NR_NO;
  6380. scalefactor := 2;
  6381. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6382. end
  6383. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6384. begin
  6385. { Scale factor only works on the index register }
  6386. index := base;
  6387. base := NR_NO;
  6388. end;
  6389. { For safety }
  6390. if scalefactor <= 1 then
  6391. begin
  6392. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6393. scalefactor := Multiple;
  6394. end
  6395. else
  6396. begin
  6397. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6398. scalefactor := scalefactor * Multiple;
  6399. end;
  6400. offset := offset * Multiple;
  6401. end;
  6402. RemoveInstruction(hp1);
  6403. Result := True;
  6404. Exit;
  6405. { This repeat..until loop exists for the benefit of Break }
  6406. until True;
  6407. end;
  6408. end;
  6409. end;
  6410. end;
  6411. end;
  6412. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6413. var
  6414. hp1 : tai;
  6415. SubInstr: Boolean;
  6416. ThisConst: TCGInt;
  6417. const
  6418. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6419. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6420. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6421. begin
  6422. Result := False;
  6423. if taicpu(p).oper[0]^.typ <> top_const then
  6424. { Should have been confirmed before calling }
  6425. InternalError(2021102601);
  6426. SubInstr := (taicpu(p).opcode = A_SUB);
  6427. if not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  6428. GetLastInstruction(p, hp1) and
  6429. (hp1.typ = ait_instruction) and
  6430. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6431. begin
  6432. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6433. { Bad size }
  6434. InternalError(2022042001);
  6435. case taicpu(hp1).opcode Of
  6436. A_INC:
  6437. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6438. begin
  6439. if SubInstr then
  6440. ThisConst := taicpu(p).oper[0]^.val - 1
  6441. else
  6442. ThisConst := taicpu(p).oper[0]^.val + 1;
  6443. end
  6444. else
  6445. Exit;
  6446. A_DEC:
  6447. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6448. begin
  6449. if SubInstr then
  6450. ThisConst := taicpu(p).oper[0]^.val + 1
  6451. else
  6452. ThisConst := taicpu(p).oper[0]^.val - 1;
  6453. end
  6454. else
  6455. Exit;
  6456. A_SUB:
  6457. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6458. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6459. begin
  6460. if SubInstr then
  6461. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6462. else
  6463. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6464. end
  6465. else
  6466. Exit;
  6467. A_ADD:
  6468. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6469. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6470. begin
  6471. if SubInstr then
  6472. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6473. else
  6474. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6475. end
  6476. else
  6477. Exit;
  6478. else
  6479. Exit;
  6480. end;
  6481. { Check that the values are in range }
  6482. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6483. { Overflow; abort }
  6484. Exit;
  6485. if (ThisConst = 0) then
  6486. begin
  6487. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6488. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6489. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6490. RemoveInstruction(hp1);
  6491. hp1 := tai(p.next);
  6492. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6493. if not GetLastInstruction(hp1, p) then
  6494. p := hp1;
  6495. end
  6496. else
  6497. begin
  6498. if taicpu(hp1).opercnt=1 then
  6499. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6500. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6501. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6502. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6503. else
  6504. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6505. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6506. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6507. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6508. RemoveInstruction(hp1);
  6509. taicpu(p).loadconst(0, ThisConst);
  6510. end;
  6511. Result := True;
  6512. end;
  6513. end;
  6514. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6515. begin
  6516. Result := False;
  6517. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6518. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6519. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6520. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6521. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6522. (
  6523. (
  6524. (taicpu(hp1).opcode = A_TEST)
  6525. ) or (
  6526. (taicpu(hp1).opcode = A_CMP) and
  6527. { A sanity check more than anything }
  6528. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6529. )
  6530. ) then
  6531. begin
  6532. { change
  6533. mov mem, %reg
  6534. ...
  6535. cmp/test x, %reg / test %reg,%reg
  6536. (reg deallocated)
  6537. to
  6538. cmp/test x, mem / cmp 0, mem
  6539. }
  6540. TransferUsedRegs(TmpUsedRegs);
  6541. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6542. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6543. begin
  6544. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6545. if (taicpu(hp1).opcode = A_TEST) and
  6546. (
  6547. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6548. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6549. ) then
  6550. begin
  6551. taicpu(hp1).opcode := A_CMP;
  6552. taicpu(hp1).loadconst(0, 0);
  6553. end;
  6554. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6555. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6556. RemoveCurrentP(p);
  6557. if (p <> hp1) then
  6558. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6559. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6560. { Make sure the flags are allocated across the CMP instruction }
  6561. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6562. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6563. Result := True;
  6564. Exit;
  6565. end;
  6566. end;
  6567. end;
  6568. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6569. var
  6570. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6571. ThisReg, SecondReg: TRegister;
  6572. JumpLoc: TAsmLabel;
  6573. NewSize: TOpSize;
  6574. begin
  6575. Result := False;
  6576. {
  6577. Convert:
  6578. j<c> .L1
  6579. .L2:
  6580. mov 1,reg
  6581. jmp .L3 (or ret, although it might not be a RET yet)
  6582. .L1:
  6583. mov 0,reg
  6584. jmp .L3 (or ret)
  6585. ( As long as .L3 <> .L1 or .L2)
  6586. To:
  6587. mov 0,reg
  6588. set<not(c)> reg
  6589. jmp .L3 (or ret)
  6590. .L2:
  6591. mov 1,reg
  6592. jmp .L3 (or ret)
  6593. .L1:
  6594. mov 0,reg
  6595. jmp .L3 (or ret)
  6596. }
  6597. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6598. Exit;
  6599. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6600. if GetNextInstruction(hp_label, hp2) and
  6601. MatchInstruction(hp2,A_MOV,[]) and
  6602. (taicpu(hp2).oper[0]^.typ = top_const) and
  6603. (
  6604. (
  6605. (taicpu(hp2).oper[1]^.typ = top_reg)
  6606. {$ifdef i386}
  6607. { Under i386, ESI, EDI, EBP and ESP
  6608. don't have an 8-bit representation }
  6609. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6610. {$endif i386}
  6611. ) or (
  6612. {$ifdef i386}
  6613. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6614. {$endif i386}
  6615. (taicpu(hp2).opsize = S_B)
  6616. )
  6617. ) and
  6618. GetNextInstruction(hp2, hp3) and
  6619. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6620. (
  6621. (taicpu(hp3).opcode=A_RET) or
  6622. (
  6623. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6624. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6625. )
  6626. ) and
  6627. GetNextInstruction(hp3, hp4) and
  6628. FindLabel(JumpLoc, hp4) and
  6629. (
  6630. not (cs_opt_size in current_settings.optimizerswitches) or
  6631. { If the initial jump is the label's only reference, then it will
  6632. become a dead label if the other conditions are met and hence
  6633. remove at least 2 instructions, including a jump }
  6634. (JumpLoc.getrefs = 1)
  6635. ) and
  6636. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6637. that will be optimised out }
  6638. GetNextInstruction(hp4, hp5) and
  6639. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6640. (taicpu(hp5).oper[0]^.typ = top_const) and
  6641. (
  6642. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6643. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6644. ) and
  6645. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6646. GetNextInstruction(hp5,hp6) and
  6647. (
  6648. not (hp6.typ in [ait_align, ait_label]) or
  6649. SkipLabels(hp6, hp6)
  6650. ) and
  6651. (hp6.typ=ait_instruction) then
  6652. begin
  6653. { First, let's look at the two jumps that are hp3 and hp6 }
  6654. if not
  6655. (
  6656. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6657. (
  6658. (taicpu(hp6).opcode=A_RET) or
  6659. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6660. )
  6661. ) then
  6662. { If condition is False, then the JMP/RET instructions matched conventionally }
  6663. begin
  6664. { See if one of the jumps can be instantly converted into a RET }
  6665. if (taicpu(hp3).opcode=A_JMP) then
  6666. begin
  6667. { Reuse hp5 }
  6668. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6669. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6670. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6671. Exit;
  6672. if MatchInstruction(hp5, A_RET, []) then
  6673. begin
  6674. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6675. ConvertJumpToRET(hp3, hp5);
  6676. Result := True;
  6677. end
  6678. else
  6679. Exit;
  6680. end;
  6681. if (taicpu(hp6).opcode=A_JMP) then
  6682. begin
  6683. { Reuse hp5 }
  6684. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6685. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6686. Exit;
  6687. if MatchInstruction(hp5, A_RET, []) then
  6688. begin
  6689. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6690. ConvertJumpToRET(hp6, hp5);
  6691. Result := True;
  6692. end
  6693. else
  6694. Exit;
  6695. end;
  6696. if not
  6697. (
  6698. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6699. (
  6700. (taicpu(hp6).opcode=A_RET) or
  6701. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6702. )
  6703. ) then
  6704. { Still doesn't match }
  6705. Exit;
  6706. end;
  6707. if (taicpu(hp2).oper[0]^.val = 1) then
  6708. begin
  6709. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6710. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6711. end
  6712. else
  6713. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6714. if taicpu(hp2).opsize=S_B then
  6715. begin
  6716. if taicpu(hp2).oper[1]^.typ = top_reg then
  6717. begin
  6718. SecondReg := taicpu(hp2).oper[1]^.reg;
  6719. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6720. end
  6721. else
  6722. begin
  6723. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6724. SecondReg := NR_NO;
  6725. end;
  6726. hp_pos := p;
  6727. hp_allocstart := hp4;
  6728. end
  6729. else
  6730. begin
  6731. { Will be a register because the size can't be S_B otherwise }
  6732. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6733. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6734. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6735. if (cs_opt_size in current_settings.optimizerswitches) then
  6736. begin
  6737. { Favour using MOVZX when optimising for size }
  6738. case taicpu(hp2).opsize of
  6739. S_W:
  6740. NewSize := S_BW;
  6741. S_L:
  6742. NewSize := S_BL;
  6743. {$ifdef x86_64}
  6744. S_Q:
  6745. begin
  6746. NewSize := S_BL;
  6747. { Will implicitly zero-extend to 64-bit }
  6748. setsubreg(SecondReg, R_SUBD);
  6749. end;
  6750. {$endif x86_64}
  6751. else
  6752. InternalError(2022101301);
  6753. end;
  6754. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6755. { Inserting it right before p will guarantee that the flags are also tracked }
  6756. Asml.InsertBefore(hp5, p);
  6757. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6758. hp_pos := hp5;
  6759. hp_allocstart := hp4;
  6760. end
  6761. else
  6762. begin
  6763. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6764. { Inserting it right before p will guarantee that the flags are also tracked }
  6765. Asml.InsertBefore(hp5, p);
  6766. hp_pos := p;
  6767. hp_allocstart := hp5;
  6768. end;
  6769. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6770. end;
  6771. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6772. taicpu(hp4).condition := taicpu(p).condition;
  6773. asml.InsertBefore(hp4, hp_pos);
  6774. if taicpu(hp3).is_jmp then
  6775. begin
  6776. JumpLoc.decrefs;
  6777. MakeUnconditional(taicpu(p));
  6778. { This also increases the reference count }
  6779. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6780. end
  6781. else
  6782. ConvertJumpToRET(p, hp3);
  6783. if SecondReg <> NR_NO then
  6784. { Ensure the destination register is allocated over this region }
  6785. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6786. if (JumpLoc.getrefs = 0) then
  6787. RemoveDeadCodeAfterJump(hp3);
  6788. Result:=true;
  6789. exit;
  6790. end;
  6791. end;
  6792. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6793. var
  6794. hp1, hp2: tai;
  6795. ActiveReg: TRegister;
  6796. OldOffset: asizeint;
  6797. ThisConst: TCGInt;
  6798. function RegDeallocated: Boolean;
  6799. begin
  6800. TransferUsedRegs(TmpUsedRegs);
  6801. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6802. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6803. end;
  6804. begin
  6805. Result:=false;
  6806. hp1 := nil;
  6807. { replace
  6808. subX const,%reg1
  6809. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6810. dealloc %reg1
  6811. by
  6812. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6813. }
  6814. if MatchOpType(taicpu(p),top_const,top_reg) then
  6815. begin
  6816. ActiveReg := taicpu(p).oper[1]^.reg;
  6817. { Ensures the entire register was updated }
  6818. if (taicpu(p).opsize >= S_L) and
  6819. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6820. MatchInstruction(hp1,A_LEA,[]) and
  6821. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6822. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6823. (
  6824. { Cover the case where the register in the reference is also the destination register }
  6825. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6826. (
  6827. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6828. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6829. RegDeallocated
  6830. )
  6831. ) then
  6832. begin
  6833. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6834. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6835. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6836. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6837. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6838. {$ifdef x86_64}
  6839. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6840. begin
  6841. { Overflow; abort }
  6842. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6843. end
  6844. else
  6845. {$endif x86_64}
  6846. begin
  6847. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6848. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6849. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6850. RemoveCurrentP(p, hp1)
  6851. else
  6852. RemoveCurrentP(p);
  6853. result:=true;
  6854. Exit;
  6855. end;
  6856. end;
  6857. if (
  6858. { Save calling GetNextInstructionUsingReg again }
  6859. Assigned(hp1) or
  6860. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6861. ) and
  6862. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6863. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6864. begin
  6865. { Make sure the flags aren't in use by the second operation }
  6866. TransferUsedRegs(TmpUsedRegs);
  6867. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  6868. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6869. begin
  6870. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6871. begin
  6872. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6873. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6874. Result := True;
  6875. { Handle any overflows }
  6876. case taicpu(p).opsize of
  6877. S_B:
  6878. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6879. S_W:
  6880. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6881. S_L:
  6882. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6883. {$ifdef x86_64}
  6884. S_Q:
  6885. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6886. { Overflow; abort }
  6887. Result := False
  6888. else
  6889. taicpu(p).oper[0]^.val := ThisConst;
  6890. {$endif x86_64}
  6891. else
  6892. InternalError(2021102611);
  6893. end;
  6894. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6895. if Result then
  6896. begin
  6897. if (taicpu(p).oper[0]^.val < 0) and
  6898. (
  6899. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6900. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6901. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6902. ) then
  6903. begin
  6904. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6905. taicpu(p).opcode := A_SUB;
  6906. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6907. end
  6908. else
  6909. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6910. RemoveInstruction(hp1);
  6911. end;
  6912. end
  6913. else
  6914. begin
  6915. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6916. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6917. Asml.Remove(p);
  6918. Asml.InsertAfter(p, hp1);
  6919. p := hp1;
  6920. Result := True;
  6921. Exit;
  6922. end;
  6923. end;
  6924. end;
  6925. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6926. { * change "sub/add const1, reg" or "dec reg" followed by
  6927. "sub const2, reg" to one "sub ..., reg" }
  6928. {$ifdef i386}
  6929. if (taicpu(p).oper[0]^.val = 2) and
  6930. (ActiveReg = NR_ESP) and
  6931. { Don't do the sub/push optimization if the sub }
  6932. { comes from setting up the stack frame (JM) }
  6933. (not(GetLastInstruction(p,hp1)) or
  6934. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6935. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6936. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6937. begin
  6938. hp1 := tai(p.next);
  6939. while Assigned(hp1) and
  6940. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6941. not RegReadByInstruction(NR_ESP,hp1) and
  6942. not RegModifiedByInstruction(NR_ESP,hp1) do
  6943. hp1 := tai(hp1.next);
  6944. if Assigned(hp1) and
  6945. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6946. begin
  6947. taicpu(hp1).changeopsize(S_L);
  6948. if taicpu(hp1).oper[0]^.typ=top_reg then
  6949. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6950. hp1 := tai(p.next);
  6951. RemoveCurrentp(p, hp1);
  6952. Result:=true;
  6953. exit;
  6954. end;
  6955. end;
  6956. {$endif i386}
  6957. if DoArithCombineOpt(p) then
  6958. Result:=true;
  6959. end;
  6960. end;
  6961. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6962. var
  6963. TmpBool1,TmpBool2 : Boolean;
  6964. tmpref : treference;
  6965. hp1,hp2: tai;
  6966. mask, shiftval: tcgint;
  6967. begin
  6968. Result:=false;
  6969. { All these optimisations work on "shl/sal const,%reg" }
  6970. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6971. Exit;
  6972. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6973. (taicpu(p).oper[0]^.val <= 3) then
  6974. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6975. begin
  6976. { should we check the next instruction? }
  6977. TmpBool1 := True;
  6978. { have we found an add/sub which could be
  6979. integrated in the lea? }
  6980. TmpBool2 := False;
  6981. reference_reset(tmpref,2,[]);
  6982. TmpRef.index := taicpu(p).oper[1]^.reg;
  6983. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6984. while TmpBool1 and
  6985. GetNextInstruction(p, hp1) and
  6986. (tai(hp1).typ = ait_instruction) and
  6987. ((((taicpu(hp1).opcode = A_ADD) or
  6988. (taicpu(hp1).opcode = A_SUB)) and
  6989. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6990. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6991. (((taicpu(hp1).opcode = A_INC) or
  6992. (taicpu(hp1).opcode = A_DEC)) and
  6993. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6994. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6995. ((taicpu(hp1).opcode = A_LEA) and
  6996. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6997. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6998. (not GetNextInstruction(hp1,hp2) or
  6999. not instrReadsFlags(hp2)) Do
  7000. begin
  7001. TmpBool1 := False;
  7002. if taicpu(hp1).opcode=A_LEA then
  7003. begin
  7004. if (TmpRef.base = NR_NO) and
  7005. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  7006. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  7007. { Segment register isn't a concern here }
  7008. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  7009. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  7010. begin
  7011. TmpBool1 := True;
  7012. TmpBool2 := True;
  7013. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  7014. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  7015. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  7016. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  7017. RemoveInstruction(hp1);
  7018. end
  7019. end
  7020. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  7021. begin
  7022. TmpBool1 := True;
  7023. TmpBool2 := True;
  7024. case taicpu(hp1).opcode of
  7025. A_ADD:
  7026. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  7027. A_SUB:
  7028. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  7029. else
  7030. internalerror(2019050536);
  7031. end;
  7032. RemoveInstruction(hp1);
  7033. end
  7034. else
  7035. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  7036. (((taicpu(hp1).opcode = A_ADD) and
  7037. (TmpRef.base = NR_NO)) or
  7038. (taicpu(hp1).opcode = A_INC) or
  7039. (taicpu(hp1).opcode = A_DEC)) then
  7040. begin
  7041. TmpBool1 := True;
  7042. TmpBool2 := True;
  7043. case taicpu(hp1).opcode of
  7044. A_ADD:
  7045. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  7046. A_INC:
  7047. inc(TmpRef.offset);
  7048. A_DEC:
  7049. dec(TmpRef.offset);
  7050. else
  7051. internalerror(2019050535);
  7052. end;
  7053. RemoveInstruction(hp1);
  7054. end;
  7055. end;
  7056. if TmpBool2
  7057. {$ifndef x86_64}
  7058. or
  7059. ((current_settings.optimizecputype < cpu_Pentium2) and
  7060. (taicpu(p).oper[0]^.val <= 3) and
  7061. not(cs_opt_size in current_settings.optimizerswitches))
  7062. {$endif x86_64}
  7063. then
  7064. begin
  7065. if not(TmpBool2) and
  7066. (taicpu(p).oper[0]^.val=1) then
  7067. begin
  7068. taicpu(p).opcode := A_ADD;
  7069. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7070. end
  7071. else
  7072. begin
  7073. taicpu(p).opcode := A_LEA;
  7074. taicpu(p).loadref(0, TmpRef);
  7075. end;
  7076. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  7077. Result := True;
  7078. end;
  7079. end
  7080. {$ifndef x86_64}
  7081. else if (current_settings.optimizecputype < cpu_Pentium2) then
  7082. begin
  7083. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  7084. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  7085. (unlike shl, which is only Tairable in the U pipe) }
  7086. if taicpu(p).oper[0]^.val=1 then
  7087. begin
  7088. taicpu(p).opcode := A_ADD;
  7089. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  7090. Result := True;
  7091. end
  7092. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  7093. "shl $3, %reg" to "lea (,%reg,8), %reg }
  7094. else if (taicpu(p).opsize = S_L) and
  7095. (taicpu(p).oper[0]^.val<= 3) then
  7096. begin
  7097. reference_reset(tmpref,2,[]);
  7098. TmpRef.index := taicpu(p).oper[1]^.reg;
  7099. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  7100. taicpu(p).opcode := A_LEA;
  7101. taicpu(p).loadref(0, TmpRef);
  7102. Result := True;
  7103. end;
  7104. end
  7105. {$endif x86_64}
  7106. else if
  7107. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  7108. (
  7109. (
  7110. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  7111. SetAndTest(hp1, hp2)
  7112. {$ifdef x86_64}
  7113. ) or
  7114. (
  7115. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  7116. GetNextInstruction(hp1, hp2) and
  7117. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  7118. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7119. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  7120. {$endif x86_64}
  7121. )
  7122. ) and
  7123. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  7124. begin
  7125. { Change:
  7126. shl x, %reg1
  7127. mov -(1<<x), %reg2
  7128. and %reg2, %reg1
  7129. Or:
  7130. shl x, %reg1
  7131. and -(1<<x), %reg1
  7132. To just:
  7133. shl x, %reg1
  7134. Since the and operation only zeroes bits that are already zero from the shl operation
  7135. }
  7136. case taicpu(p).oper[0]^.val of
  7137. 8:
  7138. mask:=$FFFFFFFFFFFFFF00;
  7139. 16:
  7140. mask:=$FFFFFFFFFFFF0000;
  7141. 32:
  7142. mask:=$FFFFFFFF00000000;
  7143. 63:
  7144. { Constant pre-calculated to prevent overflow errors with Int64 }
  7145. mask:=$8000000000000000;
  7146. else
  7147. begin
  7148. if taicpu(p).oper[0]^.val >= 64 then
  7149. { Shouldn't happen realistically, since the register
  7150. is guaranteed to be set to zero at this point }
  7151. mask := 0
  7152. else
  7153. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  7154. end;
  7155. end;
  7156. if taicpu(hp1).oper[0]^.val = mask then
  7157. begin
  7158. { Everything checks out, perform the optimisation, as long as
  7159. the FLAGS register isn't being used}
  7160. TransferUsedRegs(TmpUsedRegs);
  7161. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7162. {$ifdef x86_64}
  7163. if (hp1 <> hp2) then
  7164. begin
  7165. { "shl/mov/and" version }
  7166. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  7167. { Don't do the optimisation if the FLAGS register is in use }
  7168. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  7169. begin
  7170. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  7171. { Don't remove the 'mov' instruction if its register is used elsewhere }
  7172. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  7173. begin
  7174. RemoveInstruction(hp1);
  7175. Result := True;
  7176. end;
  7177. { Only set Result to True if the 'mov' instruction was removed }
  7178. RemoveInstruction(hp2);
  7179. end;
  7180. end
  7181. else
  7182. {$endif x86_64}
  7183. begin
  7184. { "shl/and" version }
  7185. { Don't do the optimisation if the FLAGS register is in use }
  7186. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  7187. begin
  7188. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  7189. RemoveInstruction(hp1);
  7190. Result := True;
  7191. end;
  7192. end;
  7193. Exit;
  7194. end
  7195. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  7196. begin
  7197. { Even if the mask doesn't allow for its removal, we might be
  7198. able to optimise the mask for the "shl/and" version, which
  7199. may permit other peephole optimisations }
  7200. {$ifdef DEBUG_AOPTCPU}
  7201. mask := taicpu(hp1).oper[0]^.val and mask;
  7202. if taicpu(hp1).oper[0]^.val <> mask then
  7203. begin
  7204. DebugMsg(
  7205. SPeepholeOptimization +
  7206. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  7207. ' to $' + debug_tostr(mask) +
  7208. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  7209. taicpu(hp1).oper[0]^.val := mask;
  7210. end;
  7211. {$else DEBUG_AOPTCPU}
  7212. { If debugging is off, just set the operand even if it's the same }
  7213. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  7214. {$endif DEBUG_AOPTCPU}
  7215. end;
  7216. end;
  7217. {
  7218. change
  7219. shl/sal const,reg
  7220. <op> ...(...,reg,1),...
  7221. into
  7222. <op> ...(...,reg,1 shl const),...
  7223. if const in 1..3
  7224. }
  7225. if MatchOpType(taicpu(p), top_const, top_reg) and
  7226. (taicpu(p).oper[0]^.val in [1..3]) and
  7227. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7228. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  7229. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  7230. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  7231. MatchOpType(taicpu(hp1),top_ref))
  7232. ) and
  7233. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  7234. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  7235. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  7236. begin
  7237. TransferUsedRegs(TmpUsedRegs);
  7238. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7239. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  7240. begin
  7241. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  7242. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  7243. RemoveCurrentP(p);
  7244. Result:=true;
  7245. exit;
  7246. end;
  7247. end;
  7248. if MatchOpType(taicpu(p), top_const, top_reg) and
  7249. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7250. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7251. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7252. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7253. begin
  7254. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7255. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7256. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7257. {$ifdef x86_64}
  7258. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7259. {$endif x86_64}
  7260. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7261. begin
  7262. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7263. taicpu(hp1).opcode:=A_MOV;
  7264. taicpu(hp1).oper[0]^.val:=0;
  7265. end
  7266. else
  7267. begin
  7268. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7269. taicpu(hp1).oper[0]^.val:=shiftval;
  7270. end;
  7271. RemoveCurrentP(p);
  7272. Result:=true;
  7273. exit;
  7274. end;
  7275. end;
  7276. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7277. begin
  7278. case shr_size of
  7279. S_B:
  7280. { No valid combinations }
  7281. Result := False;
  7282. S_W:
  7283. Result := (Shift >= 8) and (movz_size = S_BW);
  7284. S_L:
  7285. Result :=
  7286. (Shift >= 24) { Any opsize is valid for this shift } or
  7287. ((Shift >= 16) and (movz_size = S_WL));
  7288. {$ifdef x86_64}
  7289. S_Q:
  7290. Result :=
  7291. (Shift >= 56) { Any opsize is valid for this shift } or
  7292. ((Shift >= 48) and (movz_size = S_WL));
  7293. {$endif x86_64}
  7294. else
  7295. InternalError(2022081510);
  7296. end;
  7297. end;
  7298. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7299. var
  7300. hp1, hp2: tai;
  7301. IdentityMask, Shift: TCGInt;
  7302. LimitSize: Topsize;
  7303. DoNotMerge: Boolean;
  7304. begin
  7305. if not MatchInstruction(p, A_SHR, []) then
  7306. InternalError(2025040301);
  7307. Result := False;
  7308. DoNotMerge := False;
  7309. Shift := taicpu(p).oper[0]^.val;
  7310. LimitSize := taicpu(p).opsize;
  7311. hp1 := p;
  7312. repeat
  7313. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7314. Exit;
  7315. case taicpu(hp1).opcode of
  7316. A_AND:
  7317. { Detect:
  7318. shr x, %reg
  7319. and y, %reg
  7320. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7321. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7322. (Post-peephole only)
  7323. }
  7324. if PostPeephole and
  7325. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7326. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7327. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7328. begin
  7329. { Make sure the FLAGS register isn't in use }
  7330. TransferUsedRegs(TmpUsedRegs);
  7331. hp2 := p;
  7332. repeat
  7333. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7334. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7335. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7336. begin
  7337. { Generate the identity mask }
  7338. case taicpu(p).opsize of
  7339. S_B:
  7340. IdentityMask := $FF shr Shift;
  7341. S_W:
  7342. IdentityMask := $FFFF shr Shift;
  7343. S_L:
  7344. IdentityMask := $FFFFFFFF shr Shift;
  7345. {$ifdef x86_64}
  7346. S_Q:
  7347. { We need to force the operands to be unsigned 64-bit
  7348. integers otherwise the wrong value is generated }
  7349. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7350. {$endif x86_64}
  7351. else
  7352. InternalError(2022081501);
  7353. end;
  7354. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7355. begin
  7356. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7357. { All the possible 1 bits are covered, so we can remove the AND }
  7358. hp2 := tai(hp1.Previous);
  7359. RemoveInstruction(hp1);
  7360. { p wasn't actually changed, so don't set Result to True,
  7361. but a change was nonetheless made elsewhere }
  7362. Include(OptsToCheck, aoc_ForceNewIteration);
  7363. { Do another pass in case other AND or MOVZX instructions
  7364. follow }
  7365. hp1 := hp2;
  7366. Continue;
  7367. end;
  7368. end;
  7369. end;
  7370. A_TEST, A_CMP:
  7371. { Skip over relevant comparisons, but shift instructions must
  7372. now not be merged since the original value is being read }
  7373. begin
  7374. DoNotMerge := True;
  7375. Continue;
  7376. end;
  7377. A_Jcc:
  7378. { Skip over conditional jumps and relevant comparisons }
  7379. Continue;
  7380. A_MOVZX:
  7381. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7382. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7383. begin
  7384. { Since the original register is being read as is, subsequent
  7385. SHRs must not be merged at this point }
  7386. DoNotMerge := True;
  7387. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7388. begin
  7389. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7390. begin
  7391. { If the MOVZX instruction reads and writes the same register,
  7392. defer this to the post-peephole optimisation stage }
  7393. if PostPeephole then
  7394. begin
  7395. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7396. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7397. hp2 := tai(hp1.Previous);
  7398. RemoveInstruction(hp1);
  7399. hp1 := hp2;
  7400. end;
  7401. end
  7402. else { Different register target }
  7403. begin
  7404. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7405. taicpu(hp1).opcode := A_MOV;
  7406. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7407. case taicpu(hp1).opsize of
  7408. S_BW:
  7409. taicpu(hp1).opsize := S_W;
  7410. S_BL, S_WL:
  7411. taicpu(hp1).opsize := S_L;
  7412. else
  7413. InternalError(2022081503);
  7414. end;
  7415. { p itself hasn't changed, so no need to set Result to True }
  7416. Include(OptsToCheck, aoc_ForceNewIteration);
  7417. { See if there's anything afterwards that can be
  7418. optimised, since the input register hasn't changed }
  7419. Continue;
  7420. end;
  7421. Exit;
  7422. end
  7423. else if PostPeephole and
  7424. (Shift > 0) and
  7425. (taicpu(p).opsize = S_W) and
  7426. (taicpu(hp1).opsize = S_WL) and
  7427. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7428. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7429. begin
  7430. { Detect:
  7431. shr x, %ax (x > 0)
  7432. ...
  7433. movzwl %ax,%eax
  7434. -
  7435. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7436. But first, check to see if movzwl %ax,%eax can be removed...
  7437. }
  7438. hp2 := tai(hp1.Previous);
  7439. TransferUsedRegs(TmpUsedRegs);
  7440. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7441. if PostPeepholeOptMovZX(hp1) then
  7442. hp1 := hp2
  7443. else
  7444. begin
  7445. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7446. taicpu(hp1).opcode := A_CWDE;
  7447. taicpu(hp1).clearop(0);
  7448. taicpu(hp1).clearop(1);
  7449. taicpu(hp1).ops := 0;
  7450. end;
  7451. RestoreUsedRegs(TmpUsedRegs);
  7452. { Don't need to set aoc_ForceNewIteration if
  7453. PostPeepholeOptMovZX returned True because it's the
  7454. post-peephole stage }
  7455. end;
  7456. { Move onto the next instruction }
  7457. Continue;
  7458. end;
  7459. A_SHL, A_SAL, A_SHR:
  7460. if (taicpu(hp1).opsize <= LimitSize) and
  7461. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7462. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7463. begin
  7464. { Make sure the sizes don't exceed the register size limit
  7465. (measured by the shift value falling below the limit) }
  7466. if taicpu(hp1).opsize < LimitSize then
  7467. LimitSize := taicpu(hp1).opsize;
  7468. if taicpu(hp1).opcode = A_SHR then
  7469. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7470. else
  7471. begin
  7472. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7473. DoNotMerge := True;
  7474. end;
  7475. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7476. Exit;
  7477. { Since we've established that the combined shift is within
  7478. limits, we can actually combine the adjacent SHR
  7479. instructions even if they're different sizes }
  7480. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7481. begin
  7482. hp2 := tai(hp1.Previous);
  7483. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7484. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7485. RemoveInstruction(hp1);
  7486. hp1 := hp2;
  7487. { Though p has changed, only the constant has, and its
  7488. effects can still be detected on the next iteration of
  7489. the repeat..until loop }
  7490. Include(OptsToCheck, aoc_ForceNewIteration);
  7491. end;
  7492. { Move onto the next instruction }
  7493. Continue;
  7494. end;
  7495. else
  7496. ;
  7497. end;
  7498. { If the register isn't actually modified, move onto the next instruction,
  7499. but set DoNotMerge to True since the register is being read }
  7500. if (
  7501. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7502. the next instruction, whether or not it contains the register }
  7503. (cs_opt_level3 in current_settings.optimizerswitches) or
  7504. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7505. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7506. begin
  7507. DoNotMerge := True;
  7508. Continue;
  7509. end;
  7510. Break;
  7511. until False;
  7512. end;
  7513. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7514. begin
  7515. Result := False;
  7516. { All these optimisations work on "shr const,%reg" }
  7517. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7518. Exit;
  7519. Result := HandleSHRMerge(p, False);
  7520. end;
  7521. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7522. var
  7523. CurrentRef: TReference;
  7524. FullReg: TRegister;
  7525. hp1, hp2: tai;
  7526. begin
  7527. Result := False;
  7528. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7529. Exit;
  7530. { We assume you've checked if the operand is actually a reference by
  7531. this point. If it isn't, you'll most likely get an access violation }
  7532. CurrentRef := first_mov.oper[1]^.ref^;
  7533. { Memory must be aligned }
  7534. if (CurrentRef.offset mod 4) <> 0 then
  7535. Exit;
  7536. Inc(CurrentRef.offset);
  7537. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7538. if MatchOperand(second_mov.oper[0]^, 0) and
  7539. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7540. GetNextInstruction(second_mov, hp1) and
  7541. (hp1.typ = ait_instruction) and
  7542. (taicpu(hp1).opcode = A_MOV) and
  7543. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7544. (taicpu(hp1).oper[0]^.val = 0) then
  7545. begin
  7546. Inc(CurrentRef.offset);
  7547. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7548. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7549. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7550. begin
  7551. case taicpu(hp1).opsize of
  7552. S_B:
  7553. if GetNextInstruction(hp1, hp2) and
  7554. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7555. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7556. (taicpu(hp2).oper[0]^.val = 0) then
  7557. begin
  7558. Inc(CurrentRef.offset);
  7559. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7560. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7561. (taicpu(hp2).opsize = S_B) then
  7562. begin
  7563. RemoveInstruction(hp1);
  7564. RemoveInstruction(hp2);
  7565. first_mov.opsize := S_L;
  7566. if first_mov.oper[0]^.typ = top_reg then
  7567. begin
  7568. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7569. { Reuse second_mov as a MOVZX instruction }
  7570. second_mov.opcode := A_MOVZX;
  7571. second_mov.opsize := S_BL;
  7572. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7573. second_mov.loadreg(1, FullReg);
  7574. first_mov.oper[0]^.reg := FullReg;
  7575. asml.Remove(second_mov);
  7576. asml.InsertBefore(second_mov, first_mov);
  7577. end
  7578. else
  7579. { It's a value }
  7580. begin
  7581. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7582. RemoveInstruction(second_mov);
  7583. end;
  7584. Result := True;
  7585. Exit;
  7586. end;
  7587. end;
  7588. S_W:
  7589. begin
  7590. RemoveInstruction(hp1);
  7591. first_mov.opsize := S_L;
  7592. if first_mov.oper[0]^.typ = top_reg then
  7593. begin
  7594. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7595. { Reuse second_mov as a MOVZX instruction }
  7596. second_mov.opcode := A_MOVZX;
  7597. second_mov.opsize := S_BL;
  7598. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7599. second_mov.loadreg(1, FullReg);
  7600. first_mov.oper[0]^.reg := FullReg;
  7601. asml.Remove(second_mov);
  7602. asml.InsertBefore(second_mov, first_mov);
  7603. end
  7604. else
  7605. { It's a value }
  7606. begin
  7607. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7608. RemoveInstruction(second_mov);
  7609. end;
  7610. Result := True;
  7611. Exit;
  7612. end;
  7613. else
  7614. ;
  7615. end;
  7616. end;
  7617. end;
  7618. end;
  7619. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7620. { returns true if a "continue" should be done after this optimization }
  7621. var
  7622. hp1, hp2, hp3: tai;
  7623. begin
  7624. Result := false;
  7625. hp3 := nil;
  7626. if MatchOpType(taicpu(p),top_ref) and
  7627. GetNextInstruction(p, hp1) and
  7628. (hp1.typ = ait_instruction) and
  7629. (((taicpu(hp1).opcode = A_FLD) and
  7630. (taicpu(p).opcode = A_FSTP)) or
  7631. ((taicpu(p).opcode = A_FISTP) and
  7632. (taicpu(hp1).opcode = A_FILD))) and
  7633. MatchOpType(taicpu(hp1),top_ref) and
  7634. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7635. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7636. begin
  7637. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7638. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7639. GetNextInstruction(hp1, hp2) and
  7640. (((hp2.typ = ait_instruction) and
  7641. IsExitCode(hp2) and
  7642. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7643. not(assigned(current_procinfo.procdef.funcretsym) and
  7644. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7645. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7646. { fstp <temp>
  7647. fld <temp>
  7648. <dealloc> <temp>
  7649. }
  7650. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7651. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7652. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7653. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7654. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7655. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7656. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7657. )
  7658. )
  7659. ) then
  7660. begin
  7661. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7662. RemoveInstruction(hp1);
  7663. RemoveCurrentP(p, hp2);
  7664. { first case: exit code }
  7665. if hp2.typ = ait_instruction then
  7666. RemoveLastDeallocForFuncRes(p);
  7667. Result := true;
  7668. end
  7669. else
  7670. { we can do this only in fast math mode as fstp is rounding ...
  7671. ... still disabled as it breaks the compiler and/or rtl }
  7672. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7673. { ... or if another fstp equal to the first one follows }
  7674. GetNextInstruction(hp1,hp2) and
  7675. (hp2.typ = ait_instruction) and
  7676. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7677. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7678. begin
  7679. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7680. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7681. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7682. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7683. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7684. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7685. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7686. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7687. ) then
  7688. begin
  7689. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7690. RemoveCurrentP(p,hp2);
  7691. RemoveInstruction(hp1);
  7692. Result := true;
  7693. end
  7694. else if { fst can't store an extended/comp value }
  7695. (taicpu(p).opsize <> S_FX) and
  7696. (taicpu(p).opsize <> S_IQ) then
  7697. begin
  7698. if (taicpu(p).opcode = A_FSTP) then
  7699. taicpu(p).opcode := A_FST
  7700. else
  7701. taicpu(p).opcode := A_FIST;
  7702. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7703. RemoveInstruction(hp1);
  7704. Result := true;
  7705. end;
  7706. end;
  7707. end;
  7708. end;
  7709. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7710. var
  7711. hp1, hp2, hp3: tai;
  7712. begin
  7713. result:=false;
  7714. if MatchOpType(taicpu(p),top_reg) and
  7715. GetNextInstruction(p, hp1) and
  7716. (hp1.typ = Ait_Instruction) and
  7717. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7718. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7719. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7720. { change to
  7721. fld reg fxxx reg,st
  7722. fxxxp st, st1 (hp1)
  7723. Remark: non commutative operations must be reversed!
  7724. }
  7725. begin
  7726. case taicpu(hp1).opcode Of
  7727. A_FMULP,A_FADDP,
  7728. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7729. begin
  7730. case taicpu(hp1).opcode Of
  7731. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7732. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7733. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7734. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7735. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7736. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7737. else
  7738. internalerror(2019050534);
  7739. end;
  7740. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7741. taicpu(hp1).oper[1]^.reg := NR_ST;
  7742. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7743. RemoveCurrentP(p, hp1);
  7744. Result:=true;
  7745. exit;
  7746. end;
  7747. else
  7748. ;
  7749. end;
  7750. end
  7751. else
  7752. if MatchOpType(taicpu(p),top_ref) and
  7753. GetNextInstruction(p, hp2) and
  7754. (hp2.typ = Ait_Instruction) and
  7755. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7756. (taicpu(p).opsize in [S_FS, S_FL]) and
  7757. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7758. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7759. if GetLastInstruction(p, hp1) and
  7760. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7761. MatchOpType(taicpu(hp1),top_ref) and
  7762. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7763. if ((taicpu(hp2).opcode = A_FMULP) or
  7764. (taicpu(hp2).opcode = A_FADDP)) then
  7765. { change to
  7766. fld/fst mem1 (hp1) fld/fst mem1
  7767. fld mem1 (p) fadd/
  7768. faddp/ fmul st, st
  7769. fmulp st, st1 (hp2) }
  7770. begin
  7771. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7772. RemoveCurrentP(p, hp1);
  7773. if (taicpu(hp2).opcode = A_FADDP) then
  7774. taicpu(hp2).opcode := A_FADD
  7775. else
  7776. taicpu(hp2).opcode := A_FMUL;
  7777. taicpu(hp2).oper[1]^.reg := NR_ST;
  7778. end
  7779. else
  7780. { change to
  7781. fld/fst mem1 (hp1) fld/fst mem1
  7782. fld mem1 (p) fld st
  7783. }
  7784. begin
  7785. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7786. taicpu(p).changeopsize(S_FL);
  7787. taicpu(p).loadreg(0,NR_ST);
  7788. end
  7789. else
  7790. begin
  7791. case taicpu(hp2).opcode Of
  7792. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7793. { change to
  7794. fld/fst mem1 (hp1) fld/fst mem1
  7795. fld mem2 (p) fxxx mem2
  7796. fxxxp st, st1 (hp2) }
  7797. begin
  7798. case taicpu(hp2).opcode Of
  7799. A_FADDP: taicpu(p).opcode := A_FADD;
  7800. A_FMULP: taicpu(p).opcode := A_FMUL;
  7801. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7802. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7803. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7804. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7805. else
  7806. internalerror(2019050533);
  7807. end;
  7808. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7809. RemoveInstruction(hp2);
  7810. end
  7811. else
  7812. ;
  7813. end
  7814. end
  7815. end;
  7816. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7817. begin
  7818. Result := condition_in(cond1, cond2) or
  7819. { Not strictly subsets due to the actual flags checked, but because we're
  7820. comparing integers, E is a subset of AE and GE and their aliases }
  7821. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7822. end;
  7823. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7824. var
  7825. v: TCGInt;
  7826. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7827. FirstMatch, TempBool: Boolean;
  7828. NewReg: TRegister;
  7829. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7830. begin
  7831. Result:=false;
  7832. { All these optimisations need a next instruction }
  7833. if not GetNextInstruction(p, hp1) then
  7834. Exit;
  7835. true_hp1 := hp1;
  7836. { Search for:
  7837. cmp ###,###
  7838. j(c1) @lbl1
  7839. ...
  7840. @lbl:
  7841. cmp ###,### (same comparison as above)
  7842. j(c2) @lbl2
  7843. If c1 is a subset of c2, change to:
  7844. cmp ###,###
  7845. j(c1) @lbl2
  7846. (@lbl1 may become a dead label as a result)
  7847. }
  7848. { Also handle cases where there are multiple jumps in a row }
  7849. p_jump := hp1;
  7850. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7851. begin
  7852. Prefetch(p_jump.Next);
  7853. if IsJumpToLabel(taicpu(p_jump)) then
  7854. begin
  7855. { Do jump optimisations first in case the condition becomes
  7856. unnecessary }
  7857. TempBool := True;
  7858. if DoJumpOptimizations(p_jump, TempBool) or
  7859. not TempBool then
  7860. begin
  7861. if Assigned(p_jump) then
  7862. begin
  7863. { CollapseZeroDistJump will be set to the label or an align
  7864. before it after the jump if it optimises, whether or not
  7865. the label is live or dead }
  7866. if (p_jump.typ = ait_align) or
  7867. (
  7868. (p_jump.typ = ait_label) and
  7869. not (tai_label(p_jump).labsym.is_used)
  7870. ) then
  7871. GetNextInstruction(p_jump, p_jump);
  7872. end;
  7873. TransferUsedRegs(TmpUsedRegs);
  7874. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7875. if not Assigned(p_jump) or
  7876. (
  7877. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7878. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7879. ) then
  7880. begin
  7881. { No more conditional jumps; conditional statement is no longer required }
  7882. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7883. RemoveCurrentP(p);
  7884. Result := True;
  7885. Exit;
  7886. end;
  7887. hp1 := p_jump;
  7888. Include(OptsToCheck, aoc_ForceNewIteration);
  7889. Continue;
  7890. end;
  7891. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7892. if GetNextInstruction(p_jump, hp2) and
  7893. (
  7894. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7895. not TempBool
  7896. ) then
  7897. begin
  7898. hp1 := p_jump;
  7899. Include(OptsToCheck, aoc_ForceNewIteration);
  7900. Continue;
  7901. end;
  7902. p_label := nil;
  7903. if Assigned(JumpLabel) then
  7904. p_label := getlabelwithsym(JumpLabel);
  7905. if Assigned(p_label) and
  7906. GetNextInstruction(p_label, p_dist) and
  7907. MatchInstruction(p_dist, A_CMP, []) and
  7908. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7909. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7910. GetNextInstruction(p_dist, hp1_dist) and
  7911. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7912. begin
  7913. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7914. if JumpLabel = JumpLabel_dist then
  7915. { This is an infinite loop }
  7916. Exit;
  7917. { Best optimisation when the first condition is a subset (or equal) of the second }
  7918. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7919. begin
  7920. { Any registers used here will already be allocated }
  7921. if Assigned(JumpLabel) then
  7922. JumpLabel.DecRefs;
  7923. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7924. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7925. Include(OptsToCheck, aoc_ForceNewIteration);
  7926. { Don't exit yet. Since p and p_jump haven't actually been
  7927. removed, we can check for more on this iteration }
  7928. end
  7929. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7930. GetNextInstruction(hp1_dist, hp1_label) and
  7931. (hp1_label.typ = ait_label) then
  7932. begin
  7933. JumpLabel_far := tai_label(hp1_label).labsym;
  7934. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7935. { This is an infinite loop }
  7936. Exit;
  7937. if Assigned(JumpLabel_far) then
  7938. begin
  7939. { In this situation, if the first jump branches, the second one will never,
  7940. branch so change the destination label to after the second jump }
  7941. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7942. if Assigned(JumpLabel) then
  7943. JumpLabel.DecRefs;
  7944. JumpLabel_far.IncRefs;
  7945. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7946. Result := True;
  7947. { Don't exit yet. Since p and p_jump haven't actually been
  7948. removed, we can check for more on this iteration }
  7949. Continue;
  7950. end;
  7951. end;
  7952. end;
  7953. end;
  7954. { Search for:
  7955. cmp ###,###
  7956. j(c1) @lbl1
  7957. cmp ###,### (same as first)
  7958. Remove second cmp
  7959. }
  7960. if GetNextInstruction(p_jump, hp2) and
  7961. (
  7962. (
  7963. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7964. (
  7965. (
  7966. MatchOpType(taicpu(p), top_const, top_reg) and
  7967. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7968. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7969. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7970. ) or (
  7971. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7972. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7973. )
  7974. )
  7975. ) or (
  7976. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7977. MatchOperand(taicpu(p).oper[0]^, 0) and
  7978. (taicpu(p).oper[1]^.typ = top_reg) and
  7979. MatchInstruction(hp2, A_TEST, []) and
  7980. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7981. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7982. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7983. )
  7984. ) then
  7985. begin
  7986. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7987. TransferUsedRegs(TmpUsedRegs);
  7988. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7989. RemoveInstruction(hp2);
  7990. Result := True;
  7991. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7992. end
  7993. else
  7994. begin
  7995. { hp2 is the next instruction, so save time and just set p_jump
  7996. to it instead of calling GetNextInstruction below }
  7997. p_jump := hp2;
  7998. Continue;
  7999. end;
  8000. GetNextInstruction(p_jump, p_jump);
  8001. end;
  8002. if (
  8003. { Don't call GetNextInstruction again if we already have it }
  8004. (true_hp1 = p_jump) or
  8005. GetNextInstruction(p, hp1)
  8006. ) and
  8007. MatchInstruction(hp1, A_Jcc, []) and
  8008. IsJumpToLabel(taicpu(hp1)) and
  8009. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  8010. GetNextInstruction(hp1, hp2) then
  8011. begin
  8012. {
  8013. cmp x, y (or "cmp y, x")
  8014. je @lbl
  8015. mov x, y
  8016. @lbl:
  8017. (x and y can be constants, registers or references)
  8018. Change to:
  8019. mov x, y (x and y will always be equal in the end)
  8020. @lbl: (may beceome a dead label)
  8021. Also:
  8022. cmp x, y (or "cmp y, x")
  8023. jne @lbl
  8024. mov x, y
  8025. @lbl:
  8026. (x and y can be constants, registers or references)
  8027. Change to:
  8028. Absolutely nothing! (Except @lbl if it's still live)
  8029. }
  8030. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  8031. (
  8032. (
  8033. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  8034. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  8035. ) or (
  8036. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  8037. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  8038. )
  8039. ) and
  8040. GetNextInstruction(hp2, hp1_label) and
  8041. (hp1_label.typ = ait_label) and
  8042. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  8043. begin
  8044. tai_label(hp1_label).labsym.DecRefs;
  8045. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  8046. begin
  8047. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  8048. RemoveInstruction(hp2);
  8049. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  8050. end
  8051. else
  8052. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  8053. RemoveInstruction(hp1);
  8054. RemoveCurrentp(p, hp2);
  8055. Result := True;
  8056. Exit;
  8057. end;
  8058. {
  8059. Try to optimise the following:
  8060. cmp $x,### ($x and $y can be registers or constants)
  8061. je @lbl1 (only reference)
  8062. cmp $y,### (### are identical)
  8063. @Lbl:
  8064. sete %reg1
  8065. Change to:
  8066. cmp $x,###
  8067. sete %reg2 (allocate new %reg2)
  8068. cmp $y,###
  8069. sete %reg1
  8070. orb %reg2,%reg1
  8071. (dealloc %reg2)
  8072. This adds an instruction (so don't perform under -Os), but it removes
  8073. a conditional branch.
  8074. }
  8075. if not (cs_opt_size in current_settings.optimizerswitches) and
  8076. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  8077. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  8078. { The first operand of CMP instructions can only be a register or
  8079. immediate anyway, so no need to check }
  8080. GetNextInstruction(hp2, p_label) and
  8081. (p_label.typ = ait_label) and
  8082. (tai_label(p_label).labsym.getrefs = 1) and
  8083. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  8084. GetNextInstruction(p_label, p_dist) and
  8085. MatchInstruction(p_dist, A_SETcc, []) and
  8086. (taicpu(p_dist).condition in [C_E, C_Z]) and
  8087. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8088. begin
  8089. TransferUsedRegs(TmpUsedRegs);
  8090. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8091. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8092. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  8093. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  8094. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  8095. { Get the instruction after the SETcc instruction so we can
  8096. allocate a new register over the entire range }
  8097. GetNextInstruction(p_dist, hp1_dist) then
  8098. begin
  8099. { Register can appear in p if it's not used afterwards, so only
  8100. allocate between hp1 and hp1_dist }
  8101. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  8102. if NewReg <> NR_NO then
  8103. begin
  8104. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  8105. { Change the jump instruction into a SETcc instruction }
  8106. taicpu(hp1).opcode := A_SETcc;
  8107. taicpu(hp1).opsize := S_B;
  8108. taicpu(hp1).loadreg(0, NewReg);
  8109. { This is now a dead label }
  8110. tai_label(p_label).labsym.decrefs;
  8111. { Prefer adding before the next instruction so the FLAGS
  8112. register is deallicated first }
  8113. AsmL.InsertBefore(
  8114. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  8115. hp1_dist
  8116. );
  8117. Result := True;
  8118. { Don't exit yet, as p wasn't changed and hp1, while
  8119. modified, is still intact and might be optimised by the
  8120. SETcc optimisation below }
  8121. end;
  8122. end;
  8123. end;
  8124. end;
  8125. if (taicpu(p).oper[0]^.typ = top_const) and
  8126. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  8127. begin
  8128. if (taicpu(p).oper[0]^.val = 0) and
  8129. (taicpu(p).oper[1]^.typ = top_reg) then
  8130. begin
  8131. hp2 := p;
  8132. FirstMatch := True;
  8133. { When dealing with "cmp $0,%reg", only ZF and SF contain
  8134. anything meaningful once it's converted to "test %reg,%reg";
  8135. additionally, some jumps will always (or never) branch, so
  8136. evaluate every jump immediately following the
  8137. comparison, optimising the conditions if possible.
  8138. Similarly with SETcc... those that are always set to 0 or 1
  8139. are changed to MOV instructions }
  8140. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  8141. (
  8142. GetNextInstruction(hp2, hp1) and
  8143. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  8144. ) do
  8145. begin
  8146. Prefetch(hp1.Next);
  8147. FirstMatch := False;
  8148. case taicpu(hp1).condition of
  8149. C_B, C_C, C_NAE, C_O:
  8150. { For B/NAE:
  8151. Will never branch since an unsigned integer can never be below zero
  8152. For C/O:
  8153. Result cannot overflow because 0 is being subtracted
  8154. }
  8155. begin
  8156. if taicpu(hp1).opcode = A_Jcc then
  8157. begin
  8158. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  8159. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  8160. RemoveInstruction(hp1);
  8161. { Since hp1 was deleted, hp2 must not be updated }
  8162. Continue;
  8163. end
  8164. else
  8165. begin
  8166. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  8167. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  8168. taicpu(hp1).opcode := A_MOV;
  8169. taicpu(hp1).ops := 2;
  8170. taicpu(hp1).condition := C_None;
  8171. taicpu(hp1).opsize := S_B;
  8172. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8173. taicpu(hp1).loadconst(0, 0);
  8174. end;
  8175. end;
  8176. C_BE, C_NA:
  8177. begin
  8178. { Will only branch if equal to zero }
  8179. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  8180. taicpu(hp1).condition := C_E;
  8181. end;
  8182. C_A, C_NBE:
  8183. begin
  8184. { Will only branch if not equal to zero }
  8185. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  8186. taicpu(hp1).condition := C_NE;
  8187. end;
  8188. C_AE, C_NB, C_NC, C_NO:
  8189. begin
  8190. { Will always branch }
  8191. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  8192. if taicpu(hp1).opcode = A_Jcc then
  8193. begin
  8194. MakeUnconditional(taicpu(hp1));
  8195. { Any jumps/set that follow will now be dead code }
  8196. RemoveDeadCodeAfterJump(taicpu(hp1));
  8197. Break;
  8198. end
  8199. else
  8200. begin
  8201. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  8202. taicpu(hp1).opcode := A_MOV;
  8203. taicpu(hp1).ops := 2;
  8204. taicpu(hp1).condition := C_None;
  8205. taicpu(hp1).opsize := S_B;
  8206. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8207. taicpu(hp1).loadconst(0, 1);
  8208. end;
  8209. end;
  8210. C_None:
  8211. InternalError(2020012201);
  8212. C_P, C_PE, C_NP, C_PO:
  8213. { We can't handle parity checks and they should never be generated
  8214. after a general-purpose CMP (it's used in some floating-point
  8215. comparisons that don't use CMP) }
  8216. InternalError(2020012202);
  8217. else
  8218. { Zero/Equality, Sign, their complements and all of the
  8219. signed comparisons do not need to be converted };
  8220. end;
  8221. hp2 := hp1;
  8222. end;
  8223. { Convert the instruction to a TEST }
  8224. taicpu(p).opcode := A_TEST;
  8225. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8226. Result := True;
  8227. Exit;
  8228. end
  8229. else
  8230. begin
  8231. TransferUsedRegs(TmpUsedRegs);
  8232. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8233. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8234. begin
  8235. if (taicpu(p).oper[0]^.val = 1) and
  8236. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  8237. begin
  8238. { Convert; To:
  8239. cmp $1,r/m cmp $0,r/m
  8240. jl @lbl jle @lbl
  8241. (Also do inverted conditions)
  8242. }
  8243. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  8244. taicpu(p).oper[0]^.val := 0;
  8245. if taicpu(hp1).condition in [C_L, C_NGE] then
  8246. taicpu(hp1).condition := C_LE
  8247. else
  8248. taicpu(hp1).condition := C_NLE;
  8249. { If the instruction is now "cmp $0,%reg", convert it to a
  8250. TEST (and effectively do the work of the "cmp $0,%reg" in
  8251. the block above)
  8252. }
  8253. if (taicpu(p).oper[1]^.typ = top_reg) then
  8254. begin
  8255. taicpu(p).opcode := A_TEST;
  8256. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8257. end;
  8258. Result := True;
  8259. Exit;
  8260. end
  8261. else if (taicpu(p).oper[1]^.typ = top_reg)
  8262. {$ifdef x86_64}
  8263. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8264. {$endif x86_64}
  8265. then
  8266. begin
  8267. { cmp register,$8000 neg register
  8268. je target --> jo target
  8269. .... only if register is deallocated before jump.}
  8270. case Taicpu(p).opsize of
  8271. S_B: v:=$80;
  8272. S_W: v:=$8000;
  8273. S_L: v:=qword($80000000);
  8274. else
  8275. internalerror(2013112905);
  8276. end;
  8277. if (taicpu(p).oper[0]^.val=v) and
  8278. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8279. begin
  8280. TransferUsedRegs(TmpUsedRegs);
  8281. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8282. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8283. begin
  8284. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8285. Taicpu(p).opcode:=A_NEG;
  8286. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8287. Taicpu(p).clearop(1);
  8288. Taicpu(p).ops:=1;
  8289. if Taicpu(hp1).condition=C_E then
  8290. Taicpu(hp1).condition:=C_O
  8291. else
  8292. Taicpu(hp1).condition:=C_NO;
  8293. Result:=true;
  8294. exit;
  8295. end;
  8296. end;
  8297. end;
  8298. end;
  8299. end;
  8300. end;
  8301. if TrySwapMovCmp(p, hp1) then
  8302. begin
  8303. Result := True;
  8304. Exit;
  8305. end;
  8306. end;
  8307. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8308. var
  8309. hp1: tai;
  8310. begin
  8311. {
  8312. remove the second (v)pxor from
  8313. pxor reg,reg
  8314. ...
  8315. pxor reg,reg
  8316. }
  8317. Result:=false;
  8318. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8319. MatchOpType(taicpu(p),top_reg,top_reg) and
  8320. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8321. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8322. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8323. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8324. begin
  8325. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8326. RemoveInstruction(hp1);
  8327. Result:=true;
  8328. Exit;
  8329. end
  8330. {
  8331. replace
  8332. pxor reg1,reg1
  8333. movapd/s reg1,reg2
  8334. dealloc reg1
  8335. by
  8336. pxor reg2,reg2
  8337. }
  8338. else if GetNextInstruction(p,hp1) and
  8339. { we mix single and double opperations here because we assume that the compiler
  8340. generates vmovapd only after double operations and vmovaps only after single operations }
  8341. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8342. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8343. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8344. (taicpu(p).oper[0]^.typ=top_reg) then
  8345. begin
  8346. TransferUsedRegs(TmpUsedRegs);
  8347. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8348. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8349. begin
  8350. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8351. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8352. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8353. RemoveInstruction(hp1);
  8354. result:=true;
  8355. end;
  8356. end;
  8357. end;
  8358. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8359. var
  8360. hp1: tai;
  8361. begin
  8362. {
  8363. remove the second (v)pxor from
  8364. (v)pxor reg,reg
  8365. ...
  8366. (v)pxor reg,reg
  8367. }
  8368. Result:=false;
  8369. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8370. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8371. begin
  8372. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8373. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8374. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8375. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8376. begin
  8377. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8378. RemoveInstruction(hp1);
  8379. Result:=true;
  8380. Exit;
  8381. end;
  8382. {$ifdef x86_64}
  8383. {
  8384. replace
  8385. vpxor reg1,reg1,reg1
  8386. vmov reg,mem
  8387. by
  8388. movq $0,mem
  8389. }
  8390. if GetNextInstruction(p,hp1) and
  8391. MatchInstruction(hp1,A_VMOVSD,[]) and
  8392. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8393. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8394. begin
  8395. TransferUsedRegs(TmpUsedRegs);
  8396. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8397. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8398. begin
  8399. taicpu(hp1).loadconst(0,0);
  8400. taicpu(hp1).opcode:=A_MOV;
  8401. taicpu(hp1).opsize:=S_Q;
  8402. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8403. RemoveCurrentP(p);
  8404. result:=true;
  8405. Exit;
  8406. end;
  8407. end;
  8408. {$endif x86_64}
  8409. end
  8410. {
  8411. replace
  8412. vpxor reg1,reg1,reg2
  8413. by
  8414. vpxor reg2,reg2,reg2
  8415. to avoid unncessary data dependencies
  8416. }
  8417. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8418. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8419. begin
  8420. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8421. { avoid unncessary data dependency }
  8422. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8423. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8424. result:=true;
  8425. exit;
  8426. end;
  8427. Result:=OptPass1VOP(p);
  8428. end;
  8429. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8430. var
  8431. hp1 : tai;
  8432. begin
  8433. result:=false;
  8434. { replace
  8435. IMul const,%mreg1,%mreg2
  8436. Mov %reg2,%mreg3
  8437. dealloc %mreg3
  8438. by
  8439. Imul const,%mreg1,%mreg23
  8440. }
  8441. if (taicpu(p).ops=3) and
  8442. GetNextInstruction(p,hp1) and
  8443. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8444. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8445. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8446. begin
  8447. TransferUsedRegs(TmpUsedRegs);
  8448. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8449. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8450. begin
  8451. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8452. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8453. RemoveInstruction(hp1);
  8454. result:=true;
  8455. end;
  8456. end;
  8457. end;
  8458. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8459. var
  8460. hp1 : tai;
  8461. begin
  8462. result:=false;
  8463. { replace
  8464. IMul %reg0,%reg1,%reg2
  8465. Mov %reg2,%reg3
  8466. dealloc %reg2
  8467. by
  8468. Imul %reg0,%reg1,%reg3
  8469. }
  8470. if GetNextInstruction(p,hp1) and
  8471. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8472. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8473. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8474. begin
  8475. TransferUsedRegs(TmpUsedRegs);
  8476. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8477. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8478. begin
  8479. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8480. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8481. RemoveInstruction(hp1);
  8482. result:=true;
  8483. end;
  8484. end;
  8485. end;
  8486. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8487. var
  8488. hp1: tai;
  8489. begin
  8490. Result:=false;
  8491. { get rid of
  8492. (v)cvtss2sd reg0,<reg1,>reg2
  8493. (v)cvtss2sd reg2,<reg2,>reg0
  8494. }
  8495. if GetNextInstruction(p,hp1) and
  8496. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8497. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8498. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8499. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8500. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8501. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8502. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8503. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8504. )
  8505. ) then
  8506. begin
  8507. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8508. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8509. begin
  8510. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8511. RemoveCurrentP(p);
  8512. RemoveInstruction(hp1);
  8513. end
  8514. else
  8515. begin
  8516. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8517. if taicpu(hp1).opcode=A_CVTSD2SS then
  8518. begin
  8519. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8520. taicpu(p).opcode:=A_MOVAPS;
  8521. end
  8522. else
  8523. begin
  8524. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8525. taicpu(p).opcode:=A_VMOVAPS;
  8526. end;
  8527. taicpu(p).ops:=2;
  8528. RemoveInstruction(hp1);
  8529. end;
  8530. Result:=true;
  8531. Exit;
  8532. end;
  8533. end;
  8534. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8535. var
  8536. hp1, hp2, hp3, hp4, hp5: tai;
  8537. ThisReg: TRegister;
  8538. begin
  8539. Result := False;
  8540. if not GetNextInstruction(p,hp1) then
  8541. Exit;
  8542. {
  8543. convert
  8544. j<c> .L1
  8545. mov 1,reg
  8546. jmp .L2
  8547. .L1
  8548. mov 0,reg
  8549. .L2
  8550. into
  8551. mov 0,reg
  8552. set<not(c)> reg
  8553. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8554. would destroy the flag contents
  8555. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8556. executed at the same time as a previous comparison.
  8557. set<not(c)> reg
  8558. movzx reg, reg
  8559. }
  8560. if MatchInstruction(hp1,A_MOV,[]) and
  8561. (taicpu(hp1).oper[0]^.typ = top_const) and
  8562. (
  8563. (
  8564. (taicpu(hp1).oper[1]^.typ = top_reg)
  8565. {$ifdef i386}
  8566. { Under i386, ESI, EDI, EBP and ESP
  8567. don't have an 8-bit representation }
  8568. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8569. {$endif i386}
  8570. ) or (
  8571. {$ifdef i386}
  8572. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8573. {$endif i386}
  8574. (taicpu(hp1).opsize = S_B)
  8575. )
  8576. ) and
  8577. GetNextInstruction(hp1,hp2) and
  8578. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8579. GetNextInstruction(hp2,hp3) and
  8580. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8581. GetNextInstruction(hp3,hp4) and
  8582. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8583. (taicpu(hp4).oper[0]^.typ = top_const) and
  8584. (
  8585. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8586. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8587. ) and
  8588. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8589. GetNextInstruction(hp4,hp5) and
  8590. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8591. begin
  8592. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8593. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8594. tai_label(hp3).labsym.DecRefs;
  8595. { If this isn't the only reference to the middle label, we can
  8596. still make a saving - only that the first jump and everything
  8597. that follows will remain. }
  8598. if (tai_label(hp3).labsym.getrefs = 0) then
  8599. begin
  8600. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8601. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8602. else
  8603. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8604. { remove jump, first label and second MOV (also catching any aligns) }
  8605. repeat
  8606. if not GetNextInstruction(hp2, hp3) then
  8607. InternalError(2021040810);
  8608. RemoveInstruction(hp2);
  8609. hp2 := hp3;
  8610. until hp2 = hp5;
  8611. { Don't decrement reference count before the removal loop
  8612. above, otherwise GetNextInstruction won't stop on the
  8613. the label }
  8614. tai_label(hp5).labsym.DecRefs;
  8615. end
  8616. else
  8617. begin
  8618. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8619. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8620. else
  8621. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8622. end;
  8623. taicpu(p).opcode:=A_SETcc;
  8624. taicpu(p).opsize:=S_B;
  8625. taicpu(p).is_jmp:=False;
  8626. if taicpu(hp1).opsize=S_B then
  8627. begin
  8628. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8629. if taicpu(hp1).oper[1]^.typ = top_reg then
  8630. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8631. RemoveInstruction(hp1);
  8632. end
  8633. else
  8634. begin
  8635. { Will be a register because the size can't be S_B otherwise }
  8636. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8637. taicpu(p).loadreg(0, ThisReg);
  8638. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8639. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8640. begin
  8641. case taicpu(hp1).opsize of
  8642. S_W:
  8643. taicpu(hp1).opsize := S_BW;
  8644. S_L:
  8645. taicpu(hp1).opsize := S_BL;
  8646. {$ifdef x86_64}
  8647. S_Q:
  8648. begin
  8649. taicpu(hp1).opsize := S_BL;
  8650. { Change the destination register to 32-bit }
  8651. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8652. end;
  8653. {$endif x86_64}
  8654. else
  8655. InternalError(2021040820);
  8656. end;
  8657. taicpu(hp1).opcode := A_MOVZX;
  8658. taicpu(hp1).loadreg(0, ThisReg);
  8659. end
  8660. else
  8661. begin
  8662. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8663. { hp1 is already a MOV instruction with the correct register }
  8664. taicpu(hp1).loadconst(0, 0);
  8665. { Inserting it right before p will guarantee that the flags are also tracked }
  8666. asml.Remove(hp1);
  8667. asml.InsertBefore(hp1, p);
  8668. end;
  8669. end;
  8670. Result:=true;
  8671. exit;
  8672. end
  8673. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8674. Result := TryJccStcClcOpt(p, hp1)
  8675. else if (hp1.typ = ait_label) then
  8676. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8677. end;
  8678. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8679. var
  8680. hp1, hp2, hp3: tai;
  8681. SourceRef, TargetRef: TReference;
  8682. CurrentReg: TRegister;
  8683. begin
  8684. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8685. if not UseAVX then
  8686. InternalError(2021100501);
  8687. Result := False;
  8688. { Look for the following to simplify:
  8689. vmovdqa/u x(mem1), %xmmreg
  8690. vmovdqa/u %xmmreg, y(mem2)
  8691. vmovdqa/u x+16(mem1), %xmmreg
  8692. vmovdqa/u %xmmreg, y+16(mem2)
  8693. Change to:
  8694. vmovdqa/u x(mem1), %ymmreg
  8695. vmovdqa/u %ymmreg, y(mem2)
  8696. vpxor %ymmreg, %ymmreg, %ymmreg
  8697. ( The VPXOR instruction is to zero the upper half, thus removing the
  8698. need to call the potentially expensive VZEROUPPER instruction. Other
  8699. peephole optimisations can remove VPXOR if it's unnecessary )
  8700. }
  8701. TransferUsedRegs(TmpUsedRegs);
  8702. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8703. { NOTE: In the optimisations below, if the references dictate that an
  8704. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8705. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8706. if (taicpu(p).opsize = S_XMM) and
  8707. MatchOpType(taicpu(p), top_ref, top_reg) and
  8708. GetNextInstruction(p, hp1) and
  8709. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8710. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8711. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8712. begin
  8713. SourceRef := taicpu(p).oper[0]^.ref^;
  8714. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8715. if GetNextInstruction(hp1, hp2) and
  8716. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8717. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8718. begin
  8719. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8720. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8721. Inc(SourceRef.offset, 16);
  8722. { Reuse the register in the first block move }
  8723. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8724. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8725. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8726. begin
  8727. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8728. Inc(TargetRef.offset, 16);
  8729. if GetNextInstruction(hp2, hp3) and
  8730. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8731. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8732. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8733. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8734. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8735. begin
  8736. { Update the register tracking to the new size }
  8737. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8738. { Remember that the offsets are 16 ahead }
  8739. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8740. if not (
  8741. ((SourceRef.offset mod 32) = 16) and
  8742. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8743. ) then
  8744. taicpu(p).opcode := A_VMOVDQU;
  8745. taicpu(p).opsize := S_YMM;
  8746. taicpu(p).oper[1]^.reg := CurrentReg;
  8747. if not (
  8748. ((TargetRef.offset mod 32) = 16) and
  8749. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8750. ) then
  8751. taicpu(hp1).opcode := A_VMOVDQU;
  8752. taicpu(hp1).opsize := S_YMM;
  8753. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8754. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8755. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8756. if (pi_uses_ymm in current_procinfo.flags) then
  8757. RemoveInstruction(hp2)
  8758. else
  8759. begin
  8760. { Upper 128 bits will be set to zero; change to XMM
  8761. to avoid requirement of AVX2 }
  8762. setsubreg(CurrentReg, R_SUBMMX);
  8763. taicpu(hp2).opcode := A_VPXOR;
  8764. taicpu(hp2).opsize := S_XMM;
  8765. taicpu(hp2).loadreg(0, CurrentReg);
  8766. taicpu(hp2).loadreg(1, CurrentReg);
  8767. taicpu(hp2).loadreg(2, CurrentReg);
  8768. taicpu(hp2).ops := 3;
  8769. end;
  8770. RemoveInstruction(hp3);
  8771. Result := True;
  8772. Exit;
  8773. end;
  8774. end
  8775. else
  8776. begin
  8777. { See if the next references are 16 less rather than 16 greater }
  8778. Dec(SourceRef.offset, 32); { -16 the other way }
  8779. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8780. begin
  8781. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8782. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8783. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8784. GetNextInstruction(hp2, hp3) and
  8785. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8786. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8787. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8788. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8789. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8790. begin
  8791. { Update the register tracking to the new size }
  8792. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8793. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8794. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8795. if not(
  8796. ((SourceRef.offset mod 32) = 0) and
  8797. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8798. ) then
  8799. taicpu(hp2).opcode := A_VMOVDQU;
  8800. taicpu(hp2).opsize := S_YMM;
  8801. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8802. if not (
  8803. ((TargetRef.offset mod 32) = 0) and
  8804. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8805. ) then
  8806. taicpu(hp3).opcode := A_VMOVDQU;
  8807. taicpu(hp3).opsize := S_YMM;
  8808. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8809. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8810. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8811. if (pi_uses_ymm in current_procinfo.flags) then
  8812. RemoveInstruction(hp1)
  8813. else
  8814. begin
  8815. { Upper 128 bits will be set to zero; change to
  8816. XMM to avoid requirement of AVX2 }
  8817. setsubreg(CurrentReg, R_SUBMMX);
  8818. taicpu(hp1).opcode := A_VPXOR;
  8819. taicpu(hp1).opsize := S_XMM;
  8820. taicpu(hp1).loadreg(0, CurrentReg);
  8821. taicpu(hp1).loadreg(1, CurrentReg);
  8822. taicpu(hp1).loadreg(2, CurrentReg);
  8823. taicpu(hp1).ops := 3;
  8824. Asml.Remove(hp1);
  8825. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8826. end;
  8827. RemoveCurrentP(p, hp2);
  8828. Result := True;
  8829. Exit;
  8830. end;
  8831. end;
  8832. end;
  8833. end;
  8834. end;
  8835. end;
  8836. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8837. var
  8838. hp2, hp3, first_assignment: tai;
  8839. IncCount, OperIdx: Integer;
  8840. OrigLabel: TAsmLabel;
  8841. begin
  8842. Count := 0;
  8843. Result := False;
  8844. first_assignment := nil;
  8845. if (LoopCount >= 20) then
  8846. begin
  8847. { Guard against infinite loops }
  8848. Exit;
  8849. end;
  8850. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8851. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8852. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8853. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8854. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8855. Exit;
  8856. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8857. {
  8858. change
  8859. jmp .L1
  8860. ...
  8861. .L1:
  8862. mov ##, ## ( multiple movs possible )
  8863. jmp/ret
  8864. into
  8865. mov ##, ##
  8866. jmp/ret
  8867. }
  8868. if not Assigned(hp1) then
  8869. begin
  8870. hp1 := GetLabelWithSym(OrigLabel);
  8871. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8872. Exit;
  8873. end;
  8874. hp2 := hp1;
  8875. while Assigned(hp2) do
  8876. begin
  8877. if Assigned(hp2) and (hp2.typ = ait_label) then
  8878. SkipLabels(hp2,hp2);
  8879. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8880. Break;
  8881. case taicpu(hp2).opcode of
  8882. A_MOVSD:
  8883. begin
  8884. if taicpu(hp2).ops = 0 then
  8885. { Wrong MOVSD }
  8886. Break;
  8887. Inc(Count);
  8888. if Count >= 5 then
  8889. { Too many to be worthwhile }
  8890. Break;
  8891. GetNextInstruction(hp2, hp2);
  8892. Continue;
  8893. end;
  8894. A_MOV,
  8895. A_MOVD,
  8896. A_MOVQ,
  8897. A_MOVSX,
  8898. {$ifdef x86_64}
  8899. A_MOVSXD,
  8900. {$endif x86_64}
  8901. A_MOVZX,
  8902. A_MOVAPS,
  8903. A_MOVUPS,
  8904. A_MOVSS,
  8905. A_MOVAPD,
  8906. A_MOVUPD,
  8907. A_MOVDQA,
  8908. A_MOVDQU,
  8909. A_VMOVSS,
  8910. A_VMOVAPS,
  8911. A_VMOVUPS,
  8912. A_VMOVSD,
  8913. A_VMOVAPD,
  8914. A_VMOVUPD,
  8915. A_VMOVDQA,
  8916. A_VMOVDQU:
  8917. begin
  8918. Inc(Count);
  8919. if Count >= 5 then
  8920. { Too many to be worthwhile }
  8921. Break;
  8922. GetNextInstruction(hp2, hp2);
  8923. Continue;
  8924. end;
  8925. A_JMP:
  8926. begin
  8927. { Guard against infinite loops }
  8928. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8929. Exit;
  8930. { Analyse this jump first in case it also duplicates assignments }
  8931. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8932. begin
  8933. { Something did change! }
  8934. Result := True;
  8935. Inc(Count, IncCount);
  8936. if Count >= 5 then
  8937. begin
  8938. { Too many to be worthwhile }
  8939. Exit;
  8940. end;
  8941. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8942. Break;
  8943. end;
  8944. Result := True;
  8945. Break;
  8946. end;
  8947. A_RET:
  8948. begin
  8949. Result := True;
  8950. Break;
  8951. end;
  8952. else
  8953. Break;
  8954. end;
  8955. end;
  8956. if Result then
  8957. begin
  8958. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8959. if Count = 0 then
  8960. begin
  8961. Result := False;
  8962. Exit;
  8963. end;
  8964. TransferUsedRegs(TmpUsedRegs);
  8965. hp3 := p;
  8966. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8967. while True do
  8968. begin
  8969. if Assigned(hp1) and (hp1.typ = ait_label) then
  8970. SkipLabels(hp1,hp1);
  8971. case hp1.typ of
  8972. ait_regalloc:
  8973. if tai_regalloc(hp1).ratype = ra_dealloc then
  8974. begin
  8975. { Duplicate the register deallocation... }
  8976. hp3:=tai(hp1.getcopy);
  8977. if first_assignment = nil then
  8978. first_assignment := hp3;
  8979. asml.InsertBefore(hp3, p);
  8980. { ... but also reallocate it after the jump }
  8981. hp3:=tai(hp1.getcopy);
  8982. tai_regalloc(hp3).ratype := ra_alloc;
  8983. asml.InsertAfter(hp3, p);
  8984. end;
  8985. ait_instruction:
  8986. case taicpu(hp1).opcode of
  8987. A_JMP:
  8988. begin
  8989. { Change the original jump to the new destination }
  8990. OrigLabel.decrefs;
  8991. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8992. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8993. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8994. if not Assigned(first_assignment) then
  8995. InternalError(2021040810)
  8996. else
  8997. p := first_assignment;
  8998. Exit;
  8999. end;
  9000. A_RET:
  9001. begin
  9002. { Now change the jump into a RET instruction }
  9003. ConvertJumpToRET(p, hp1);
  9004. { Set p to the first duplicated assignment so it can get optimised if needs be }
  9005. if not Assigned(first_assignment) then
  9006. InternalError(2021040811)
  9007. else
  9008. p := first_assignment;
  9009. Exit;
  9010. end;
  9011. else
  9012. begin
  9013. { Duplicate the MOV instruction }
  9014. hp3:=tai(hp1.getcopy);
  9015. if first_assignment = nil then
  9016. first_assignment := hp3;
  9017. asml.InsertBefore(hp3, p);
  9018. { Make sure the compiler knows about any final registers written here }
  9019. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  9020. with taicpu(hp3).oper[OperIdx]^ do
  9021. begin
  9022. case typ of
  9023. top_ref:
  9024. begin
  9025. if (ref^.base <> NR_NO) and
  9026. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  9027. (
  9028. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  9029. (
  9030. { Allow the frame pointer if it's not being used by the procedure as such }
  9031. Assigned(current_procinfo) and
  9032. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  9033. )
  9034. )
  9035. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  9036. then
  9037. begin
  9038. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  9039. if not Assigned(first_assignment) then
  9040. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  9041. end;
  9042. if (ref^.index <> NR_NO) and
  9043. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  9044. (
  9045. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  9046. (
  9047. { Allow the frame pointer if it's not being used by the procedure as such }
  9048. Assigned(current_procinfo) and
  9049. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  9050. )
  9051. )
  9052. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  9053. (ref^.index <> ref^.base) then
  9054. begin
  9055. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  9056. if not Assigned(first_assignment) then
  9057. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  9058. end;
  9059. end;
  9060. top_reg:
  9061. begin
  9062. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  9063. if not Assigned(first_assignment) then
  9064. IncludeRegInUsedRegs(reg, UsedRegs);
  9065. end;
  9066. else
  9067. ;
  9068. end;
  9069. end;
  9070. end;
  9071. end;
  9072. else
  9073. InternalError(2021040720);
  9074. end;
  9075. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  9076. { Should have dropped out earlier }
  9077. InternalError(2021040710);
  9078. end;
  9079. end;
  9080. end;
  9081. const
  9082. WriteOp: array[0..3] of set of TInsChange = (
  9083. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  9084. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  9085. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  9086. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  9087. RegWriteFlags: array[0..7] of set of TInsChange = (
  9088. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  9089. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  9090. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  9091. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  9092. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  9093. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  9094. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  9095. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  9096. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  9097. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  9098. var
  9099. hp2: tai;
  9100. X: Integer;
  9101. begin
  9102. { If we have something like:
  9103. op ###,###
  9104. mov ###,###
  9105. Try to move the MOV instruction to before OP as long as OP and MOV don't
  9106. interfere in regards to what they write to.
  9107. NOTE: p must be a 2-operand instruction
  9108. }
  9109. Result := False;
  9110. if (hp1.typ <> ait_instruction) or
  9111. taicpu(hp1).is_jmp or
  9112. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  9113. Exit;
  9114. { NOP is a pipeline fence, likely marking the beginning of the function
  9115. epilogue, so drop out. Similarly, drop out if POP or RET are
  9116. encountered }
  9117. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  9118. Exit;
  9119. if (taicpu(hp1).opcode = A_MOVSD) and
  9120. (taicpu(hp1).ops = 0) then
  9121. { Wrong MOVSD }
  9122. Exit;
  9123. { Check for writes to specific registers first }
  9124. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9125. for X := 0 to 7 do
  9126. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  9127. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  9128. Exit;
  9129. for X := 0 to taicpu(hp1).ops - 1 do
  9130. begin
  9131. { Check to see if this operand writes to something }
  9132. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  9133. { And matches something in the CMP/TEST instruction }
  9134. (
  9135. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  9136. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  9137. (
  9138. { If it's a register, make sure the register written to doesn't
  9139. appear in the cmp instruction as part of a reference }
  9140. (taicpu(hp1).oper[X]^.typ = top_reg) and
  9141. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  9142. )
  9143. ) then
  9144. Exit;
  9145. end;
  9146. { Check p to make sure it doesn't write to something that affects hp1 }
  9147. { Check for writes to specific registers first }
  9148. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  9149. for X := 0 to 7 do
  9150. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  9151. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  9152. Exit;
  9153. for X := 0 to taicpu(p).ops - 1 do
  9154. begin
  9155. { Check to see if this operand writes to something }
  9156. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  9157. { And matches something in hp1 }
  9158. (taicpu(p).oper[X]^.typ = top_reg) and
  9159. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  9160. Exit;
  9161. end;
  9162. { The instruction can be safely moved }
  9163. asml.Remove(hp1);
  9164. { Try to insert after the last instructions where the FLAGS register is not
  9165. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  9166. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  9167. asml.InsertBefore(hp1, hp2)
  9168. { Failing that, try to insert after the last instructions where the
  9169. FLAGS register is not yet in use }
  9170. else if GetLastInstruction(p, hp2) and
  9171. (
  9172. (hp2.typ <> ait_instruction) or
  9173. { Don't insert after an instruction that uses the flags when p doesn't use them }
  9174. RegInInstruction(NR_DEFAULTFLAGS, p) or
  9175. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  9176. ) then
  9177. asml.InsertAfter(hp1, hp2)
  9178. else
  9179. { Note, if p.Previous is nil (even if it should logically never be the
  9180. case), FindRegAllocBackward immediately exits with False and so we
  9181. safely land here (we can't just pass p because FindRegAllocBackward
  9182. immediately exits on an instruction). [Kit] }
  9183. asml.InsertBefore(hp1, p);
  9184. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  9185. { We can't trust UsedRegs because we're looking backwards, although we
  9186. know the registers are allocated after p at the very least, so manually
  9187. create tai_regalloc objects if needed }
  9188. for X := 0 to taicpu(hp1).ops - 1 do
  9189. case taicpu(hp1).oper[X]^.typ of
  9190. top_reg:
  9191. begin
  9192. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  9193. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  9194. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  9195. end;
  9196. top_ref:
  9197. begin
  9198. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  9199. begin
  9200. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  9201. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  9202. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  9203. end;
  9204. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  9205. begin
  9206. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  9207. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  9208. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  9209. end;
  9210. end;
  9211. else
  9212. ;
  9213. end;
  9214. Result := True;
  9215. end;
  9216. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  9217. var
  9218. hp2: tai;
  9219. X: Integer;
  9220. begin
  9221. { If we have something like:
  9222. cmp ###,%reg1
  9223. mov 0,%reg2
  9224. And no modified registers are shared, move the instruction to before
  9225. the comparison as this means it can be optimised without worrying
  9226. about the FLAGS register. (CMP/MOV is generated by
  9227. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  9228. As long as the second instruction doesn't use the flags or one of the
  9229. registers used by CMP or TEST (also check any references that use the
  9230. registers), then it can be moved prior to the comparison.
  9231. }
  9232. Result := False;
  9233. if not TrySwapMovOp(p, hp1) then
  9234. Exit;
  9235. if taicpu(hp1).opcode = A_LEA then
  9236. { The flags will be overwritten by the CMP/TEST instruction }
  9237. ConvertLEA(taicpu(hp1));
  9238. Result := True;
  9239. { Can we move it one further back? }
  9240. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  9241. { Check to see if CMP/TEST is a comparison against zero }
  9242. (
  9243. (
  9244. (taicpu(p).opcode = A_CMP) and
  9245. MatchOperand(taicpu(p).oper[0]^, 0)
  9246. ) or
  9247. (
  9248. (taicpu(p).opcode = A_TEST) and
  9249. (
  9250. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  9251. MatchOperand(taicpu(p).oper[0]^, -1)
  9252. )
  9253. )
  9254. ) and
  9255. { These instructions set the zero flag if the result is zero }
  9256. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9257. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9258. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9259. TrySwapMovOp(hp2, hp1);
  9260. end;
  9261. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9262. var
  9263. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9264. JumpLabel: TAsmLabel;
  9265. TmpBool: Boolean;
  9266. begin
  9267. Result := False;
  9268. { Look for:
  9269. stc/clc
  9270. j(c) .L1
  9271. ...
  9272. .L1:
  9273. set(n)cb %reg
  9274. (flags deallocated)
  9275. j(c) .L2
  9276. Change to:
  9277. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9278. j(c) .L2
  9279. }
  9280. p_last := p;
  9281. while GetNextInstruction(p_last, hp1) and
  9282. (hp1.typ = ait_instruction) and
  9283. IsJumpToLabel(taicpu(hp1)) do
  9284. begin
  9285. if DoJumpOptimizations(hp1, TmpBool) then
  9286. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9287. Continue;
  9288. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9289. if not Assigned(JumpLabel) then
  9290. InternalError(2024012801);
  9291. { Optimise the J(c); stc/clc optimisation first since this will
  9292. get missed if the main optimisation takes place }
  9293. if (taicpu(hp1).opcode = A_JCC) then
  9294. begin
  9295. if GetNextInstruction(hp1, hp2) and
  9296. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9297. TryJccStcClcOpt(hp1, hp2) then
  9298. begin
  9299. Result := True;
  9300. Exit;
  9301. end;
  9302. hp2 := nil; { Suppress compiler warning }
  9303. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9304. { Make sure the flags aren't used again }
  9305. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9306. begin
  9307. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9308. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9309. begin
  9310. if (taicpu(p).opcode = A_STC) then
  9311. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9312. else
  9313. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9314. MakeUnconditional(taicpu(hp1));
  9315. { Move the jump to after the flag deallocations }
  9316. Asml.Remove(hp1);
  9317. Asml.InsertAfter(hp1, hp2);
  9318. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9319. Result := True;
  9320. Exit;
  9321. end
  9322. else
  9323. begin
  9324. if (taicpu(p).opcode = A_STC) then
  9325. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9326. else
  9327. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9328. { In this case, the jump is deterministic in that it will never be taken }
  9329. JumpLabel.DecRefs;
  9330. RemoveInstruction(hp1);
  9331. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9332. Result := True;
  9333. Exit;
  9334. end;
  9335. end;
  9336. end;
  9337. hp2 := nil; { Suppress compiler warning }
  9338. if
  9339. { Make sure the carry flag doesn't appear in the jump conditions }
  9340. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9341. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9342. GetNextInstruction(hp2, p_dist) and
  9343. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9344. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9345. begin
  9346. case taicpu(p_dist).opcode of
  9347. A_Jcc:
  9348. begin
  9349. if DoJumpOptimizations(p_dist, TmpBool) then
  9350. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9351. Continue;
  9352. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9353. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9354. begin
  9355. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9356. JumpLabel.decrefs;
  9357. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9358. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9359. Result := True;
  9360. Exit;
  9361. end
  9362. else if GetNextInstruction(p_dist, hp1_dist) and
  9363. (hp1_dist.typ = ait_label) then
  9364. begin
  9365. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9366. JumpLabel.decrefs;
  9367. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9368. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9369. Result := True;
  9370. Exit;
  9371. end;
  9372. end;
  9373. A_SETcc:
  9374. if { Make sure the flags aren't used again }
  9375. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9376. GetNextInstruction(hp2, hp1_dist) and
  9377. (hp1_dist.typ = ait_instruction) and
  9378. IsJumpToLabel(taicpu(hp1_dist)) and
  9379. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9380. { This works if hp1_dist or both are regular JMP instructions }
  9381. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9382. (
  9383. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9384. { Make sure the register isn't still in use, otherwise it
  9385. may get corrupted (fixes #40659) }
  9386. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9387. ) then
  9388. begin
  9389. taicpu(p).allocate_oper(2);
  9390. taicpu(p).ops := 2;
  9391. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9392. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9393. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9394. taicpu(p).opcode := A_MOV;
  9395. taicpu(p).opsize := S_B;
  9396. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9397. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9398. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9399. JumpLabel.decrefs;
  9400. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9401. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9402. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9403. (tai_regalloc(hp2).ratype = ra_alloc) then
  9404. begin
  9405. Asml.Remove(hp2);
  9406. Asml.InsertAfter(hp2, p);
  9407. end;
  9408. Result := True;
  9409. Exit;
  9410. end;
  9411. else
  9412. ;
  9413. end;
  9414. end;
  9415. p_last := hp1;
  9416. end;
  9417. end;
  9418. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9419. var
  9420. hp2, hp3: tai;
  9421. TempBool: Boolean;
  9422. begin
  9423. Result := False;
  9424. {
  9425. j(c) .L1
  9426. stc/clc
  9427. .L1:
  9428. jc/jnc .L2
  9429. (Flags deallocated)
  9430. Change to:
  9431. j)c) .L1
  9432. jmp .L2
  9433. .L1:
  9434. jc/jnc .L2
  9435. Then call DoJumpOptimizations to convert to:
  9436. j(nc) .L2
  9437. .L1: (may become a dead label)
  9438. jc/jnc .L2
  9439. }
  9440. if GetNextInstruction(hp1, hp2) and
  9441. (hp2.typ = ait_label) and
  9442. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9443. GetNextInstruction(hp2, hp3) and
  9444. MatchInstruction(hp3, A_Jcc, []) and
  9445. (
  9446. (
  9447. (taicpu(hp3).condition = C_C) and
  9448. (taicpu(hp1).opcode = A_STC)
  9449. ) or (
  9450. (taicpu(hp3).condition = C_NC) and
  9451. (taicpu(hp1).opcode = A_CLC)
  9452. )
  9453. ) and
  9454. { Make sure the flags aren't used again }
  9455. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9456. begin
  9457. taicpu(hp1).allocate_oper(1);
  9458. taicpu(hp1).ops := 1;
  9459. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9460. taicpu(hp1).opcode := A_JMP;
  9461. taicpu(hp1).is_jmp := True;
  9462. TempBool := True; { Prevent compiler warnings }
  9463. if DoJumpOptimizations(p, TempBool) then
  9464. Result := True
  9465. else
  9466. Include(OptsToCheck, aoc_ForceNewIteration);
  9467. end;
  9468. end;
  9469. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9470. begin
  9471. { This generally only executes under -O3 and above }
  9472. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9473. end;
  9474. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9475. var
  9476. hp1, hp2: tai;
  9477. FoundComparison: Boolean;
  9478. begin
  9479. { Run the pass 1 optimisations as well, since they may have some effect
  9480. after the CMOV blocks are created in OptPass2Jcc }
  9481. Result := False;
  9482. { Result := OptPass1CMOVcc(p);
  9483. if Result then
  9484. Exit;}
  9485. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9486. and make a slightly inefficent result on branching-type blocks, notably
  9487. when setting a function result then jumping to the function epilogue.
  9488. In this case, change:
  9489. cmov(c) %reg1,%reg2
  9490. j(c) @lbl
  9491. (%reg2 deallocated)
  9492. To:
  9493. mov %reg11,%reg2
  9494. j(c) @lbl
  9495. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9496. jump because if it's not present, we may end up with a jump that's
  9497. completely unrelated.
  9498. }
  9499. hp1 := p;
  9500. while GetNextInstruction(hp1, hp1) and
  9501. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9502. if (hp1.typ = ait_instruction) and
  9503. (taicpu(hp1).opcode = A_Jcc) and
  9504. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9505. begin
  9506. TransferUsedRegs(TmpUsedRegs);
  9507. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9508. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9509. (
  9510. { See if we can find a more distant instruction that overwrites
  9511. the destination register }
  9512. (cs_opt_level3 in current_settings.optimizerswitches) and
  9513. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9514. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9515. ) then
  9516. begin
  9517. if (taicpu(p).oper[0]^.typ = top_reg) then
  9518. begin
  9519. { Search backwards to see if the source register is set to a
  9520. constant }
  9521. FoundComparison := False;
  9522. hp1 := p;
  9523. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9524. begin
  9525. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9526. begin
  9527. FoundComparison := True;
  9528. Continue;
  9529. end;
  9530. { Once we find the CMP, TEST or similar instruction, we
  9531. have to stop if we find anything other than a MOV }
  9532. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9533. Break;
  9534. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9535. { Destination register was modified }
  9536. Break;
  9537. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9538. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9539. begin
  9540. { Found a constant! }
  9541. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9542. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9543. { The source register is no longer in use }
  9544. RemoveInstruction(hp1);
  9545. Break;
  9546. end;
  9547. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9548. { Some other instruction has modified the source register }
  9549. Break;
  9550. end;
  9551. end;
  9552. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9553. taicpu(p).opcode := A_MOV;
  9554. taicpu(p).condition := C_None;
  9555. { Rely on the post peephole stage to put the MOV before the
  9556. CMP/TEST instruction that appears prior }
  9557. Result := True;
  9558. Exit;
  9559. end;
  9560. end;
  9561. end;
  9562. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9563. function IsXCHGAcceptable: Boolean; inline;
  9564. begin
  9565. { Always accept if optimising for size }
  9566. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9567. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9568. than 3, so it becomes a saving compared to three MOVs with two of
  9569. them able to execute simultaneously. [Kit] }
  9570. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9571. end;
  9572. var
  9573. NewRef: TReference;
  9574. hp1, hp2, hp3, hp4: Tai;
  9575. {$ifndef x86_64}
  9576. OperIdx: Integer;
  9577. {$endif x86_64}
  9578. NewInstr : Taicpu;
  9579. NewAligh : Tai_align;
  9580. DestLabel: TAsmLabel;
  9581. TempTracking: TAllUsedRegs;
  9582. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9583. var
  9584. NextInstr: tai;
  9585. begin
  9586. Result := False;
  9587. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9588. if not GetNextInstruction(InputInstr, NextInstr) or
  9589. (
  9590. { The FLAGS register isn't always tracked properly, so do not
  9591. perform this optimisation if a conditional statement follows }
  9592. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9593. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9594. ) then
  9595. begin
  9596. reference_reset(NewRef, 1, []);
  9597. NewRef.base := taicpu(p).oper[0]^.reg;
  9598. NewRef.scalefactor := 1;
  9599. if taicpu(InputInstr).opcode = A_ADD then
  9600. begin
  9601. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9602. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9603. end
  9604. else
  9605. begin
  9606. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9607. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9608. end;
  9609. taicpu(p).opcode := A_LEA;
  9610. taicpu(p).loadref(0, NewRef);
  9611. { For the sake of debugging, have the line info match the
  9612. arithmetic instruction rather than the MOV instruction }
  9613. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9614. RemoveInstruction(InputInstr);
  9615. Result := True;
  9616. end;
  9617. end;
  9618. begin
  9619. Result:=false;
  9620. { This optimisation adds an instruction, so only do it for speed }
  9621. if not (cs_opt_size in current_settings.optimizerswitches) and
  9622. MatchOpType(taicpu(p), top_const, top_reg) and
  9623. (taicpu(p).oper[0]^.val = 0) then
  9624. begin
  9625. { To avoid compiler warning }
  9626. DestLabel := nil;
  9627. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9628. InternalError(2021040750);
  9629. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9630. Exit;
  9631. case hp1.typ of
  9632. ait_label:
  9633. begin
  9634. { Change:
  9635. mov $0,%reg mov $0,%reg
  9636. @Lbl1: @Lbl1:
  9637. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9638. je @Lbl2 jne @Lbl2
  9639. To: To:
  9640. mov $0,%reg mov $0,%reg
  9641. jmp @Lbl2 jmp @Lbl3
  9642. (align) (align)
  9643. @Lbl1: @Lbl1:
  9644. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9645. je @Lbl2 je @Lbl2
  9646. @Lbl3: <-- Only if label exists
  9647. (Not if it's optimised for size)
  9648. }
  9649. if not GetNextInstruction(hp1, hp2) then
  9650. Exit;
  9651. if (hp2.typ = ait_instruction) and
  9652. (
  9653. { Register sizes must exactly match }
  9654. (
  9655. (taicpu(hp2).opcode = A_CMP) and
  9656. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9657. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9658. ) or (
  9659. (taicpu(hp2).opcode = A_TEST) and
  9660. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9661. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9662. )
  9663. ) and GetNextInstruction(hp2, hp3) and
  9664. (hp3.typ = ait_instruction) and
  9665. (taicpu(hp3).opcode = A_JCC) and
  9666. (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
  9667. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9668. begin
  9669. { Check condition of jump }
  9670. { Always true? }
  9671. if condition_in(C_E, taicpu(hp3).condition) then
  9672. begin
  9673. { Copy label symbol and obtain matching label entry for the
  9674. conditional jump, as this will be our destination}
  9675. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9676. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9677. Result := True;
  9678. end
  9679. { Always false? }
  9680. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9681. begin
  9682. { This is only worth it if there's a jump to take }
  9683. case hp2.typ of
  9684. ait_instruction:
  9685. begin
  9686. if taicpu(hp2).opcode = A_JMP then
  9687. begin
  9688. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9689. { An unconditional jump follows the conditional jump which will always be false,
  9690. so use this jump's destination for the new jump }
  9691. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9692. Result := True;
  9693. end
  9694. else if taicpu(hp2).opcode = A_JCC then
  9695. begin
  9696. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9697. if condition_in(C_E, taicpu(hp2).condition) then
  9698. begin
  9699. { A second conditional jump follows the conditional jump which will always be false,
  9700. while the second jump is always True, so use this jump's destination for the new jump }
  9701. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9702. Result := True;
  9703. end;
  9704. { Don't risk it if the jump isn't always true (Result remains False) }
  9705. end;
  9706. end;
  9707. else
  9708. { If anything else don't optimise };
  9709. end;
  9710. end;
  9711. if Result then
  9712. begin
  9713. { Just so we have something to insert as a paremeter}
  9714. reference_reset(NewRef, 1, []);
  9715. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9716. { Now actually load the correct parameter (this also
  9717. increases the reference count) }
  9718. NewInstr.loadsymbol(0, DestLabel, 0);
  9719. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9720. begin
  9721. { Get instruction before original label (may not be p under -O3) }
  9722. if not GetLastInstruction(hp1, hp2) then
  9723. { Shouldn't fail here }
  9724. InternalError(2021040701);
  9725. end
  9726. else
  9727. hp2 := p;
  9728. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9729. AsmL.InsertAfter(NewInstr, hp2);
  9730. { Add new alignment field }
  9731. (* AsmL.InsertAfter(
  9732. cai_align.create_max(
  9733. current_settings.alignment.jumpalign,
  9734. current_settings.alignment.jumpalignskipmax
  9735. ),
  9736. NewInstr
  9737. ); *)
  9738. end;
  9739. Exit;
  9740. end;
  9741. end;
  9742. else
  9743. ;
  9744. end;
  9745. end;
  9746. if not GetNextInstruction(p, hp1) then
  9747. Exit;
  9748. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9749. begin
  9750. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9751. begin
  9752. Result := True;
  9753. Exit;
  9754. end;
  9755. { This optimisation is only effective on a second run of Pass 2,
  9756. hence -O3 or above.
  9757. Change:
  9758. mov %reg1,%reg2
  9759. cmp/test (contains %reg1)
  9760. mov x, %reg1
  9761. (another mov or a j(c))
  9762. To:
  9763. mov %reg1,%reg2
  9764. mov x, %reg1
  9765. cmp (%reg1 replaced with %reg2)
  9766. (another mov or a j(c))
  9767. The requirement of an additional MOV or a jump ensures there
  9768. isn't performance loss, since a j(c) will permit macro-fusion
  9769. with the cmp instruction, while another MOV likely means it's
  9770. not all being executed in a single cycle due to parallelisation.
  9771. }
  9772. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9773. MatchOpType(taicpu(p), top_reg, top_reg) and
  9774. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9775. GetNextInstruction(hp1, hp2) and
  9776. MatchInstruction(hp2, A_MOV, []) and
  9777. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9778. { Registers don't have to be the same size in this case }
  9779. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9780. GetNextInstruction(hp2, hp3) and
  9781. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9782. { Make sure the operands in the camparison can be safely replaced }
  9783. (
  9784. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9785. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9786. ) and
  9787. (
  9788. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9789. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9790. ) then
  9791. begin
  9792. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9793. AsmL.Remove(hp2);
  9794. AsmL.InsertAfter(hp2, p);
  9795. Result := True;
  9796. Exit;
  9797. end;
  9798. end;
  9799. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9800. begin
  9801. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9802. further, but we can't just put this jump optimisation in pass 1
  9803. because it tends to perform worse when conditional jumps are
  9804. nearby (e.g. when converting CMOV instructions). [Kit] }
  9805. CopyUsedRegs(TempTracking);
  9806. UpdateUsedRegs(tai(p.Next));
  9807. if OptPass2JMP(hp1) then
  9808. begin
  9809. { Restore register state }
  9810. RestoreUsedRegs(TempTracking);
  9811. ReleaseUsedRegs(TempTracking);
  9812. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9813. OptPass1MOV(p);
  9814. Result := True;
  9815. Exit;
  9816. end;
  9817. { If OptPass2JMP returned False, no optimisations were done to
  9818. the jump and there are no further optimisations that can be done
  9819. to the MOV instruction on this pass other than FuncMov2Func }
  9820. { Restore register state }
  9821. RestoreUsedRegs(TempTracking);
  9822. ReleaseUsedRegs(TempTracking);
  9823. Result := FuncMov2Func(p, hp1);
  9824. Exit;
  9825. end;
  9826. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9827. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9828. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9829. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9830. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9831. begin
  9832. { Change:
  9833. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9834. addl/q $x,%reg2 subl/q $x,%reg2
  9835. To:
  9836. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9837. }
  9838. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9839. { be lazy, checking separately for sub would be slightly better }
  9840. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9841. begin
  9842. TransferUsedRegs(TmpUsedRegs);
  9843. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9844. if TryMovArith2Lea(hp1) then
  9845. begin
  9846. Result := True;
  9847. Exit;
  9848. end
  9849. end
  9850. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9851. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9852. { Same as above, but also adds or subtracts to %reg2 in between.
  9853. It's still valid as long as the flags aren't in use }
  9854. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9855. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9856. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9857. { be lazy, checking separately for sub would be slightly better }
  9858. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9859. begin
  9860. TransferUsedRegs(TmpUsedRegs);
  9861. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9862. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9863. if TryMovArith2Lea(hp2) then
  9864. begin
  9865. Result := True;
  9866. Exit;
  9867. end;
  9868. end;
  9869. end;
  9870. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9871. {$ifdef x86_64}
  9872. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9873. {$else x86_64}
  9874. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9875. {$endif x86_64}
  9876. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9877. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9878. { mov reg1, reg2 mov reg1, reg2
  9879. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9880. begin
  9881. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9882. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9883. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9884. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9885. TransferUsedRegs(TmpUsedRegs);
  9886. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9887. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9888. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9889. then
  9890. begin
  9891. RemoveCurrentP(p, hp1);
  9892. Result:=true;
  9893. end;
  9894. Exit;
  9895. end;
  9896. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9897. IsXCHGAcceptable and
  9898. { XCHG doesn't support 8-bit registers }
  9899. (taicpu(p).opsize <> S_B) and
  9900. MatchInstruction(hp1, A_MOV, []) and
  9901. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9902. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9903. GetNextInstruction(hp1, hp2) and
  9904. MatchInstruction(hp2, A_MOV, []) and
  9905. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9906. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9907. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9908. begin
  9909. { mov %reg1,%reg2
  9910. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9911. mov %reg2,%reg3
  9912. (%reg2 not used afterwards)
  9913. Note that xchg takes 3 cycles to execute, and generally mov's take
  9914. only one cycle apiece, but the first two mov's can be executed in
  9915. parallel, only taking 2 cycles overall. Older processors should
  9916. therefore only optimise for size. [Kit]
  9917. }
  9918. TransferUsedRegs(TmpUsedRegs);
  9919. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9920. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9921. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9922. begin
  9923. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9924. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9925. taicpu(hp1).opcode := A_XCHG;
  9926. RemoveCurrentP(p, hp1);
  9927. RemoveInstruction(hp2);
  9928. Result := True;
  9929. Exit;
  9930. end;
  9931. end;
  9932. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9933. MatchInstruction(hp1, A_SAR, []) then
  9934. begin
  9935. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9936. begin
  9937. { the use of %edx also covers the opsize being S_L }
  9938. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9939. begin
  9940. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9941. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9942. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9943. begin
  9944. { Change:
  9945. movl %eax,%edx
  9946. sarl $31,%edx
  9947. To:
  9948. cltd
  9949. }
  9950. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9951. RemoveInstruction(hp1);
  9952. taicpu(p).opcode := A_CDQ;
  9953. taicpu(p).opsize := S_NO;
  9954. taicpu(p).clearop(1);
  9955. taicpu(p).clearop(0);
  9956. taicpu(p).ops:=0;
  9957. Result := True;
  9958. Exit;
  9959. end
  9960. else if (cs_opt_size in current_settings.optimizerswitches) and
  9961. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9962. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9963. begin
  9964. { Change:
  9965. movl %edx,%eax
  9966. sarl $31,%edx
  9967. To:
  9968. movl %edx,%eax
  9969. cltd
  9970. Note that this creates a dependency between the two instructions,
  9971. so only perform if optimising for size.
  9972. }
  9973. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9974. taicpu(hp1).opcode := A_CDQ;
  9975. taicpu(hp1).opsize := S_NO;
  9976. taicpu(hp1).clearop(1);
  9977. taicpu(hp1).clearop(0);
  9978. taicpu(hp1).ops:=0;
  9979. Include(OptsToCheck, aoc_ForceNewIteration);
  9980. Exit;
  9981. end;
  9982. {$ifndef x86_64}
  9983. end
  9984. { Don't bother if CMOV is supported, because a more optimal
  9985. sequence would have been generated for the Abs() intrinsic }
  9986. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9987. { the use of %eax also covers the opsize being S_L }
  9988. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9989. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9990. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9991. GetNextInstruction(hp1, hp2) and
  9992. MatchInstruction(hp2, A_XOR, [S_L]) and
  9993. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9994. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9995. GetNextInstruction(hp2, hp3) and
  9996. MatchInstruction(hp3, A_SUB, [S_L]) and
  9997. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9998. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9999. begin
  10000. { Change:
  10001. movl %eax,%edx
  10002. sarl $31,%eax
  10003. xorl %eax,%edx
  10004. subl %eax,%edx
  10005. (Instruction that uses %edx)
  10006. (%eax deallocated)
  10007. (%edx deallocated)
  10008. To:
  10009. cltd
  10010. xorl %edx,%eax <-- Note the registers have swapped
  10011. subl %edx,%eax
  10012. (Instruction that uses %eax) <-- %eax rather than %edx
  10013. }
  10014. TransferUsedRegs(TmpUsedRegs);
  10015. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10016. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10017. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10018. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  10019. begin
  10020. if GetNextInstruction(hp3, hp4) and
  10021. not RegModifiedByInstruction(NR_EDX, hp4) and
  10022. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  10023. begin
  10024. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  10025. taicpu(p).opcode := A_CDQ;
  10026. taicpu(p).clearop(1);
  10027. taicpu(p).clearop(0);
  10028. taicpu(p).ops:=0;
  10029. RemoveInstruction(hp1);
  10030. taicpu(hp2).loadreg(0, NR_EDX);
  10031. taicpu(hp2).loadreg(1, NR_EAX);
  10032. taicpu(hp3).loadreg(0, NR_EDX);
  10033. taicpu(hp3).loadreg(1, NR_EAX);
  10034. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  10035. { Convert references in the following instruction (hp4) from %edx to %eax }
  10036. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  10037. with taicpu(hp4).oper[OperIdx]^ do
  10038. case typ of
  10039. top_reg:
  10040. if getsupreg(reg) = RS_EDX then
  10041. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  10042. top_ref:
  10043. begin
  10044. if getsupreg(reg) = RS_EDX then
  10045. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  10046. if getsupreg(reg) = RS_EDX then
  10047. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  10048. end;
  10049. else
  10050. ;
  10051. end;
  10052. Result := True;
  10053. Exit;
  10054. end;
  10055. end;
  10056. {$else x86_64}
  10057. end;
  10058. end
  10059. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  10060. { the use of %rdx also covers the opsize being S_Q }
  10061. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  10062. begin
  10063. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  10064. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  10065. (taicpu(p).oper[1]^.reg = NR_RDX) then
  10066. begin
  10067. { Change:
  10068. movq %rax,%rdx
  10069. sarq $63,%rdx
  10070. To:
  10071. cqto
  10072. }
  10073. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  10074. RemoveInstruction(hp1);
  10075. taicpu(p).opcode := A_CQO;
  10076. taicpu(p).opsize := S_NO;
  10077. taicpu(p).clearop(1);
  10078. taicpu(p).clearop(0);
  10079. taicpu(p).ops:=0;
  10080. Result := True;
  10081. Exit;
  10082. end
  10083. else if (cs_opt_size in current_settings.optimizerswitches) and
  10084. (taicpu(p).oper[0]^.reg = NR_RDX) and
  10085. (taicpu(p).oper[1]^.reg = NR_RAX) then
  10086. begin
  10087. { Change:
  10088. movq %rdx,%rax
  10089. sarq $63,%rdx
  10090. To:
  10091. movq %rdx,%rax
  10092. cqto
  10093. Note that this creates a dependency between the two instructions,
  10094. so only perform if optimising for size.
  10095. }
  10096. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  10097. taicpu(hp1).opcode := A_CQO;
  10098. taicpu(hp1).opsize := S_NO;
  10099. taicpu(hp1).clearop(1);
  10100. taicpu(hp1).clearop(0);
  10101. taicpu(hp1).ops:=0;
  10102. Include(OptsToCheck, aoc_ForceNewIteration);
  10103. Exit;
  10104. {$endif x86_64}
  10105. end;
  10106. end;
  10107. end;
  10108. if MatchInstruction(hp1, A_MOV, []) and
  10109. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10110. { Though "GetNextInstruction" could be factored out, along with
  10111. the instructions that depend on hp2, it is an expensive call that
  10112. should be delayed for as long as possible, hence we do cheaper
  10113. checks first that are likely to be False. [Kit] }
  10114. begin
  10115. if (
  10116. (
  10117. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  10118. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  10119. (
  10120. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10121. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  10122. )
  10123. ) or
  10124. (
  10125. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  10126. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  10127. (
  10128. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10129. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  10130. )
  10131. )
  10132. ) and
  10133. GetNextInstruction(hp1, hp2) and
  10134. MatchInstruction(hp2, A_SAR, []) and
  10135. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  10136. begin
  10137. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  10138. begin
  10139. { Change:
  10140. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  10141. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  10142. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  10143. To:
  10144. movl r/m,%eax <- Note the change in register
  10145. cltd
  10146. }
  10147. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  10148. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  10149. taicpu(p).loadreg(1, NR_EAX);
  10150. taicpu(hp1).opcode := A_CDQ;
  10151. taicpu(hp1).clearop(1);
  10152. taicpu(hp1).clearop(0);
  10153. taicpu(hp1).ops:=0;
  10154. RemoveInstruction(hp2);
  10155. Include(OptsToCheck, aoc_ForceNewIteration);
  10156. (*
  10157. {$ifdef x86_64}
  10158. end
  10159. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  10160. { This code sequence does not get generated - however it might become useful
  10161. if and when 128-bit signed integer types make an appearance, so the code
  10162. is kept here for when it is eventually needed. [Kit] }
  10163. (
  10164. (
  10165. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  10166. (
  10167. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10168. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  10169. )
  10170. ) or
  10171. (
  10172. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  10173. (
  10174. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  10175. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  10176. )
  10177. )
  10178. ) and
  10179. GetNextInstruction(hp1, hp2) and
  10180. MatchInstruction(hp2, A_SAR, [S_Q]) and
  10181. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  10182. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  10183. begin
  10184. { Change:
  10185. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  10186. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  10187. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  10188. To:
  10189. movq r/m,%rax <- Note the change in register
  10190. cqto
  10191. }
  10192. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  10193. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  10194. taicpu(p).loadreg(1, NR_RAX);
  10195. taicpu(hp1).opcode := A_CQO;
  10196. taicpu(hp1).clearop(1);
  10197. taicpu(hp1).clearop(0);
  10198. taicpu(hp1).ops:=0;
  10199. RemoveInstruction(hp2);
  10200. Include(OptsToCheck, aoc_ForceNewIteration);
  10201. {$endif x86_64}
  10202. *)
  10203. end;
  10204. end;
  10205. {$ifdef x86_64}
  10206. end;
  10207. if (taicpu(p).opsize = S_L) and
  10208. (taicpu(p).oper[1]^.typ = top_reg) and
  10209. (
  10210. MatchInstruction(hp1, A_MOV,[]) and
  10211. (taicpu(hp1).opsize = S_L) and
  10212. (taicpu(hp1).oper[1]^.typ = top_reg)
  10213. ) and (
  10214. GetNextInstruction(hp1, hp2) and
  10215. (tai(hp2).typ=ait_instruction) and
  10216. (taicpu(hp2).opsize = S_Q) and
  10217. (
  10218. (
  10219. MatchInstruction(hp2, A_ADD,[]) and
  10220. (taicpu(hp2).opsize = S_Q) and
  10221. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10222. (
  10223. (
  10224. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10225. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10226. ) or (
  10227. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10228. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10229. )
  10230. )
  10231. ) or (
  10232. MatchInstruction(hp2, A_LEA,[]) and
  10233. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  10234. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  10235. (
  10236. (
  10237. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  10238. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10239. ) or (
  10240. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10241. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  10242. )
  10243. ) and (
  10244. (
  10245. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  10246. ) or (
  10247. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  10248. )
  10249. )
  10250. )
  10251. )
  10252. ) and (
  10253. GetNextInstruction(hp2, hp3) and
  10254. MatchInstruction(hp3, A_SHR,[]) and
  10255. (taicpu(hp3).opsize = S_Q) and
  10256. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10257. (taicpu(hp3).oper[0]^.val = 1) and
  10258. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10259. ) then
  10260. begin
  10261. { Change movl x, reg1d movl x, reg1d
  10262. movl y, reg2d movl y, reg2d
  10263. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10264. shrq $1, reg1q shrq $1, reg1q
  10265. ( reg1d and reg2d can be switched around in the first two instructions )
  10266. To movl x, reg1d
  10267. addl y, reg1d
  10268. rcrl $1, reg1d
  10269. This corresponds to the common expression (x + y) shr 1, where
  10270. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10271. smaller code, but won't account for x + y causing an overflow). [Kit]
  10272. }
  10273. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10274. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10275. begin
  10276. { Change first MOV command to have the same register as the final output }
  10277. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10278. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10279. Result := True;
  10280. end
  10281. else
  10282. begin
  10283. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10284. Include(OptsToCheck, aoc_ForceNewIteration);
  10285. end;
  10286. { Change second MOV command to an ADD command. This is easier than
  10287. converting the existing command because it means we don't have to
  10288. touch 'y', which might be a complicated reference, and also the
  10289. fact that the third command might either be ADD or LEA. [Kit] }
  10290. taicpu(hp1).opcode := A_ADD;
  10291. { Delete old ADD/LEA instruction }
  10292. RemoveInstruction(hp2);
  10293. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10294. taicpu(hp3).opcode := A_RCR;
  10295. taicpu(hp3).changeopsize(S_L);
  10296. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10297. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10298. called, so FuncMov2Func below is safe to call }
  10299. {$endif x86_64}
  10300. end;
  10301. {$ifdef x86_64}
  10302. { Note, this optimisation was moved from Pass 1 because the CMOV
  10303. optimisations in OptPass2Jcc fall foul of the loss of information
  10304. about the upper 32 bits of the target register. Fixes #41317. }
  10305. { Change:
  10306. movl %reg1l,%reg2l
  10307. movq %reg2q,%reg3q (%reg1 <> %reg3)
  10308. To:
  10309. movl %reg1l,%reg2l
  10310. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  10311. }
  10312. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10313. (taicpu(p).opsize = S_L) then
  10314. begin
  10315. TransferUsedRegs(TmpUsedRegs);
  10316. { Mark the start point for sequential calls to
  10317. GetNextInstructionUsingReg, RegModifiedBetween and
  10318. UpdateUsedRegsBetween in case this optimisation is run multiple
  10319. times }
  10320. hp2 := p;
  10321. repeat
  10322. if (
  10323. not(cs_opt_level3 in current_settings.optimizerswitches) or
  10324. { Look further ahead for this one }
  10325. GetNextInstructionUsingReg(hp2, hp1, taicpu(p).oper[1]^.reg)
  10326. ) and
  10327. MatchInstruction(hp1,A_MOV,[S_Q]) and
  10328. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp2, hp1) and
  10329. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10330. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  10331. begin
  10332. UpdateUsedRegsBetween(TmpUsedRegs, tai(hp2.Next), hp1);
  10333. taicpu(hp1).opsize := S_L;
  10334. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  10335. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10336. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  10337. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  10338. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  10339. begin
  10340. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  10341. RemoveCurrentP(p);
  10342. Result := True;
  10343. Exit;
  10344. end;
  10345. { Initial instruction wasn't actually changed }
  10346. Include(OptsToCheck, aoc_ForceNewIteration);
  10347. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10348. begin
  10349. { GetNextInstructionUsingReg will return a different
  10350. instruction, so check this optimisation again }
  10351. { Update the start point for the next calls to
  10352. GetNextInstructionUsingReg, RegModifiedBetween and
  10353. UpdateUsedRegsBetween to grant a speed boost }
  10354. hp2 := hp1;
  10355. Continue; { Jump back to "repeat" }
  10356. end;
  10357. end;
  10358. Break;
  10359. until False;
  10360. end;
  10361. {$endif x86_64}
  10362. if FuncMov2Func(p, hp1) then
  10363. begin
  10364. Result := True;
  10365. Exit;
  10366. end;
  10367. end;
  10368. {$push}
  10369. {$q-}{$r-}
  10370. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10371. var
  10372. ThisReg: TRegister;
  10373. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10374. TargetSubReg: TSubRegister;
  10375. hp1, hp2: tai;
  10376. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10377. { Store list of found instructions so we don't have to call
  10378. GetNextInstructionUsingReg multiple times }
  10379. InstrList: array of taicpu;
  10380. InstrMax, Index: Integer;
  10381. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10382. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10383. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10384. WorkingValue: TCgInt;
  10385. PreMessage: string;
  10386. { Data flow analysis }
  10387. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10388. BitwiseOnly, OrXorUsed,
  10389. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10390. function CheckOverflowConditions: Boolean;
  10391. begin
  10392. Result := True;
  10393. if (TestValSignedMax > SignedUpperLimit) then
  10394. UpperSignedOverflow := True;
  10395. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10396. LowerSignedOverflow := True;
  10397. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10398. LowerUnsignedOverflow := True;
  10399. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10400. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10401. begin
  10402. { Absolute overflow }
  10403. Result := False;
  10404. Exit;
  10405. end;
  10406. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10407. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10408. ShiftDownOverflow := True;
  10409. if (TestValMin < 0) or (TestValMax < 0) then
  10410. begin
  10411. LowerUnsignedOverflow := True;
  10412. UpperUnsignedOverflow := True;
  10413. end;
  10414. end;
  10415. function AdjustInitialLoadAndSize: Boolean;
  10416. begin
  10417. Result := False;
  10418. if not p_removed then
  10419. begin
  10420. if TargetSize = MinSize then
  10421. begin
  10422. { Convert the input MOVZX to a MOV }
  10423. if (taicpu(p).oper[0]^.typ = top_reg) and
  10424. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10425. begin
  10426. { Or remove it completely! }
  10427. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10428. RemoveCurrentP(p);
  10429. p_removed := True;
  10430. end
  10431. else
  10432. begin
  10433. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10434. taicpu(p).opcode := A_MOV;
  10435. taicpu(p).oper[1]^.reg := ThisReg;
  10436. taicpu(p).opsize := TargetSize;
  10437. end;
  10438. Result := True;
  10439. end
  10440. else if TargetSize <> MaxSize then
  10441. begin
  10442. case MaxSize of
  10443. S_L:
  10444. if TargetSize = S_W then
  10445. begin
  10446. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10447. taicpu(p).opsize := S_BW;
  10448. taicpu(p).oper[1]^.reg := ThisReg;
  10449. Result := True;
  10450. end
  10451. else
  10452. InternalError(2020112341);
  10453. S_W:
  10454. if TargetSize = S_L then
  10455. begin
  10456. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10457. taicpu(p).opsize := S_BL;
  10458. taicpu(p).oper[1]^.reg := ThisReg;
  10459. Result := True;
  10460. end
  10461. else
  10462. InternalError(2020112342);
  10463. else
  10464. ;
  10465. end;
  10466. end
  10467. else if not hp1_removed and not RegInUse then
  10468. begin
  10469. { If we have something like:
  10470. movzbl (oper),%regd
  10471. add x, %regd
  10472. movzbl %regb, %regd
  10473. We can reduce the register size to the input of the final
  10474. movzbl instruction. Overflows won't have any effect.
  10475. }
  10476. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10477. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10478. begin
  10479. TargetSize := S_B;
  10480. setsubreg(ThisReg, R_SUBL);
  10481. Result := True;
  10482. end
  10483. else if (taicpu(p).opsize = S_WL) and
  10484. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10485. begin
  10486. TargetSize := S_W;
  10487. setsubreg(ThisReg, R_SUBW);
  10488. Result := True;
  10489. end;
  10490. if Result then
  10491. begin
  10492. { Convert the input MOVZX to a MOV }
  10493. if (taicpu(p).oper[0]^.typ = top_reg) and
  10494. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10495. begin
  10496. { Or remove it completely! }
  10497. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10498. RemoveCurrentP(p);
  10499. p_removed := True;
  10500. end
  10501. else
  10502. begin
  10503. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10504. taicpu(p).opcode := A_MOV;
  10505. taicpu(p).oper[1]^.reg := ThisReg;
  10506. taicpu(p).opsize := TargetSize;
  10507. end;
  10508. end;
  10509. end;
  10510. end;
  10511. end;
  10512. procedure AdjustFinalLoad;
  10513. begin
  10514. if not LowerUnsignedOverflow then
  10515. begin
  10516. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10517. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10518. begin
  10519. { Convert the output MOVZX to a MOV }
  10520. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10521. begin
  10522. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10523. if (MinSize = S_B) or
  10524. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10525. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10526. begin
  10527. { Remove it completely! }
  10528. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10529. { Be careful; if p = hp1 and p was also removed, p
  10530. will become a dangling pointer }
  10531. if p = hp1 then
  10532. begin
  10533. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10534. p_removed := True;
  10535. end
  10536. else
  10537. RemoveInstruction(hp1);
  10538. hp1_removed := True;
  10539. end;
  10540. end
  10541. else
  10542. begin
  10543. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10544. taicpu(hp1).opcode := A_MOV;
  10545. taicpu(hp1).oper[0]^.reg := ThisReg;
  10546. taicpu(hp1).opsize := TargetSize;
  10547. end;
  10548. end
  10549. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10550. begin
  10551. { Need to change the size of the output }
  10552. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10553. taicpu(hp1).oper[0]^.reg := ThisReg;
  10554. taicpu(hp1).opsize := S_BL;
  10555. end;
  10556. end;
  10557. end;
  10558. function CompressInstructions: Boolean;
  10559. var
  10560. LocalIndex: Integer;
  10561. begin
  10562. Result := False;
  10563. { The objective here is to try to find a combination that
  10564. removes one of the MOV/Z instructions. }
  10565. if (
  10566. (taicpu(p).oper[0]^.typ <> top_reg) or
  10567. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10568. ) and
  10569. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10570. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10571. begin
  10572. { Make a preference to remove the second MOVZX instruction }
  10573. case taicpu(hp1).opsize of
  10574. S_BL, S_WL:
  10575. begin
  10576. TargetSize := S_L;
  10577. TargetSubReg := R_SUBD;
  10578. end;
  10579. S_BW:
  10580. begin
  10581. TargetSize := S_W;
  10582. TargetSubReg := R_SUBW;
  10583. end;
  10584. else
  10585. InternalError(2020112302);
  10586. end;
  10587. end
  10588. else
  10589. begin
  10590. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10591. begin
  10592. { Exceeded lower bound but not upper bound }
  10593. TargetSize := MaxSize;
  10594. end
  10595. else if not LowerUnsignedOverflow then
  10596. begin
  10597. { Size didn't exceed lower bound }
  10598. TargetSize := MinSize;
  10599. end
  10600. else
  10601. Exit;
  10602. end;
  10603. case TargetSize of
  10604. S_B:
  10605. TargetSubReg := R_SUBL;
  10606. S_W:
  10607. TargetSubReg := R_SUBW;
  10608. S_L:
  10609. TargetSubReg := R_SUBD;
  10610. else
  10611. InternalError(2020112350);
  10612. end;
  10613. { Update the register to its new size }
  10614. setsubreg(ThisReg, TargetSubReg);
  10615. RegInUse := False;
  10616. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10617. begin
  10618. { Check to see if the active register is used afterwards;
  10619. if not, we can change it and make a saving. }
  10620. TransferUsedRegs(TmpUsedRegs);
  10621. { The target register may be marked as in use to cross
  10622. a jump to a distant label, so exclude it }
  10623. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10624. hp2 := p;
  10625. repeat
  10626. { Explicitly check for the excluded register (don't include the first
  10627. instruction as it may be reading from here }
  10628. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10629. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10630. begin
  10631. RegInUse := True;
  10632. Break;
  10633. end;
  10634. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10635. if not GetNextInstruction(hp2, hp2) then
  10636. InternalError(2020112340);
  10637. until (hp2 = hp1);
  10638. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10639. { We might still be able to get away with this }
  10640. RegInUse := not
  10641. (
  10642. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10643. (hp2.typ = ait_instruction) and
  10644. (
  10645. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10646. instruction that doesn't actually contain ThisReg }
  10647. (cs_opt_level3 in current_settings.optimizerswitches) or
  10648. RegInInstruction(ThisReg, hp2)
  10649. ) and
  10650. RegLoadedWithNewValue(ThisReg, hp2)
  10651. );
  10652. if not RegInUse then
  10653. begin
  10654. { Force the register size to the same as this instruction so it can be removed}
  10655. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10656. begin
  10657. TargetSize := S_L;
  10658. TargetSubReg := R_SUBD;
  10659. end
  10660. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10661. begin
  10662. TargetSize := S_W;
  10663. TargetSubReg := R_SUBW;
  10664. end;
  10665. ThisReg := taicpu(hp1).oper[1]^.reg;
  10666. setsubreg(ThisReg, TargetSubReg);
  10667. RegChanged := True;
  10668. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10669. TransferUsedRegs(TmpUsedRegs);
  10670. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10671. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10672. if p = hp1 then
  10673. begin
  10674. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10675. p_removed := True;
  10676. end
  10677. else
  10678. RemoveInstruction(hp1);
  10679. hp1_removed := True;
  10680. { Instruction will become "mov %reg,%reg" }
  10681. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10682. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10683. begin
  10684. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10685. RemoveCurrentP(p);
  10686. p_removed := True;
  10687. end
  10688. else
  10689. taicpu(p).oper[1]^.reg := ThisReg;
  10690. Result := True;
  10691. end
  10692. else
  10693. begin
  10694. if TargetSize <> MaxSize then
  10695. begin
  10696. { Since the register is in use, we have to force it to
  10697. MaxSize otherwise part of it may become undefined later on }
  10698. TargetSize := MaxSize;
  10699. case TargetSize of
  10700. S_B:
  10701. TargetSubReg := R_SUBL;
  10702. S_W:
  10703. TargetSubReg := R_SUBW;
  10704. S_L:
  10705. TargetSubReg := R_SUBD;
  10706. else
  10707. InternalError(2020112351);
  10708. end;
  10709. setsubreg(ThisReg, TargetSubReg);
  10710. end;
  10711. AdjustFinalLoad;
  10712. end;
  10713. end
  10714. else
  10715. AdjustFinalLoad;
  10716. Result := AdjustInitialLoadAndSize or Result;
  10717. { Now go through every instruction we found and change the
  10718. size. If TargetSize = MaxSize, then almost no changes are
  10719. needed and Result can remain False if it hasn't been set
  10720. yet.
  10721. If RegChanged is True, then the register requires changing
  10722. and so the point about TargetSize = MaxSize doesn't apply. }
  10723. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10724. begin
  10725. for LocalIndex := 0 to InstrMax do
  10726. begin
  10727. { If p_removed is true, then the original MOV/Z was removed
  10728. and removing the AND instruction may not be safe if it
  10729. appears first }
  10730. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10731. InternalError(2020112310);
  10732. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10733. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10734. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10735. InstrList[LocalIndex].opsize := TargetSize;
  10736. end;
  10737. Result := True;
  10738. end;
  10739. end;
  10740. begin
  10741. Result := False;
  10742. p_removed := False;
  10743. hp1_removed := False;
  10744. ThisReg := taicpu(p).oper[1]^.reg;
  10745. { Check for:
  10746. movs/z ###,%ecx (or %cx or %rcx)
  10747. ...
  10748. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10749. (dealloc %ecx)
  10750. Change to:
  10751. mov ###,%cl (if ### = %cl, then remove completely)
  10752. ...
  10753. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10754. }
  10755. if (getsupreg(ThisReg) = RS_ECX) and
  10756. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10757. (hp1.typ = ait_instruction) and
  10758. (
  10759. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10760. instruction that doesn't actually contain ECX }
  10761. (cs_opt_level3 in current_settings.optimizerswitches) or
  10762. RegInInstruction(NR_ECX, hp1) or
  10763. (
  10764. { It's common for the shift/rotate's read/write register to be
  10765. initialised in between, so under -O2 and under, search ahead
  10766. one more instruction
  10767. }
  10768. GetNextInstruction(hp1, hp1) and
  10769. (hp1.typ = ait_instruction) and
  10770. RegInInstruction(NR_ECX, hp1)
  10771. )
  10772. ) and
  10773. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10774. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10775. begin
  10776. TransferUsedRegs(TmpUsedRegs);
  10777. hp2 := p;
  10778. repeat
  10779. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10780. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10781. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10782. begin
  10783. case taicpu(p).opsize of
  10784. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10785. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10786. begin
  10787. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10788. RemoveCurrentP(p);
  10789. end
  10790. else
  10791. begin
  10792. taicpu(p).opcode := A_MOV;
  10793. taicpu(p).opsize := S_B;
  10794. taicpu(p).oper[1]^.reg := NR_CL;
  10795. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10796. end;
  10797. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10798. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10799. begin
  10800. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10801. RemoveCurrentP(p);
  10802. end
  10803. else
  10804. begin
  10805. taicpu(p).opcode := A_MOV;
  10806. taicpu(p).opsize := S_W;
  10807. taicpu(p).oper[1]^.reg := NR_CX;
  10808. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10809. end;
  10810. {$ifdef x86_64}
  10811. S_LQ:
  10812. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10813. begin
  10814. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10815. RemoveCurrentP(p);
  10816. end
  10817. else
  10818. begin
  10819. taicpu(p).opcode := A_MOV;
  10820. taicpu(p).opsize := S_L;
  10821. taicpu(p).oper[1]^.reg := NR_ECX;
  10822. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10823. end;
  10824. {$endif x86_64}
  10825. else
  10826. InternalError(2021120401);
  10827. end;
  10828. Result := True;
  10829. Exit;
  10830. end;
  10831. end;
  10832. { This is anything but quick! }
  10833. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10834. Exit;
  10835. SetLength(InstrList, 0);
  10836. InstrMax := -1;
  10837. case taicpu(p).opsize of
  10838. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10839. begin
  10840. {$if defined(i386) or defined(i8086)}
  10841. { If the target size is 8-bit, make sure we can actually encode it }
  10842. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10843. Exit;
  10844. {$endif i386 or i8086}
  10845. LowerLimit := $FF;
  10846. SignedLowerLimit := $7F;
  10847. SignedLowerLimitBottom := -128;
  10848. MinSize := S_B;
  10849. if taicpu(p).opsize = S_BW then
  10850. begin
  10851. MaxSize := S_W;
  10852. UpperLimit := $FFFF;
  10853. SignedUpperLimit := $7FFF;
  10854. SignedUpperLimitBottom := -32768;
  10855. end
  10856. else
  10857. begin
  10858. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10859. MaxSize := S_L;
  10860. UpperLimit := $FFFFFFFF;
  10861. SignedUpperLimit := $7FFFFFFF;
  10862. SignedUpperLimitBottom := -2147483648;
  10863. end;
  10864. end;
  10865. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10866. begin
  10867. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10868. LowerLimit := $FFFF;
  10869. SignedLowerLimit := $7FFF;
  10870. SignedLowerLimitBottom := -32768;
  10871. UpperLimit := $FFFFFFFF;
  10872. SignedUpperLimit := $7FFFFFFF;
  10873. SignedUpperLimitBottom := -2147483648;
  10874. MinSize := S_W;
  10875. MaxSize := S_L;
  10876. end;
  10877. {$ifdef x86_64}
  10878. S_LQ:
  10879. begin
  10880. { Both the lower and upper limits are set to 32-bit. If a limit
  10881. is breached, then optimisation is impossible }
  10882. LowerLimit := $FFFFFFFF;
  10883. SignedLowerLimit := $7FFFFFFF;
  10884. SignedLowerLimitBottom := -2147483648;
  10885. UpperLimit := $FFFFFFFF;
  10886. SignedUpperLimit := $7FFFFFFF;
  10887. SignedUpperLimitBottom := -2147483648;
  10888. MinSize := S_L;
  10889. MaxSize := S_L;
  10890. end;
  10891. {$endif x86_64}
  10892. else
  10893. InternalError(2020112301);
  10894. end;
  10895. TestValMin := 0;
  10896. TestValMax := LowerLimit;
  10897. TestValSignedMax := SignedLowerLimit;
  10898. TryShiftDownLimit := LowerLimit;
  10899. TryShiftDown := S_NO;
  10900. ShiftDownOverflow := False;
  10901. RegChanged := False;
  10902. BitwiseOnly := True;
  10903. OrXorUsed := False;
  10904. UpperSignedOverflow := False;
  10905. LowerSignedOverflow := False;
  10906. UpperUnsignedOverflow := False;
  10907. LowerUnsignedOverflow := False;
  10908. hp1 := p;
  10909. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10910. (hp1.typ = ait_instruction) and
  10911. (
  10912. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10913. instruction that doesn't actually contain ThisReg }
  10914. (cs_opt_level3 in current_settings.optimizerswitches) or
  10915. { This allows this Movx optimisation to work through the SETcc instructions
  10916. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10917. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10918. skip over these SETcc instructions). }
  10919. (taicpu(hp1).opcode = A_SETcc) or
  10920. RegInInstruction(ThisReg, hp1)
  10921. ) do
  10922. begin
  10923. case taicpu(hp1).opcode of
  10924. A_INC,A_DEC:
  10925. begin
  10926. { Has to be an exact match on the register }
  10927. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10928. Break;
  10929. if taicpu(hp1).opcode = A_INC then
  10930. begin
  10931. Inc(TestValMin);
  10932. Inc(TestValMax);
  10933. Inc(TestValSignedMax);
  10934. end
  10935. else
  10936. begin
  10937. Dec(TestValMin);
  10938. Dec(TestValMax);
  10939. Dec(TestValSignedMax);
  10940. end;
  10941. end;
  10942. A_TEST, A_CMP:
  10943. begin
  10944. if (
  10945. { Too high a risk of non-linear behaviour that breaks DFA
  10946. here, unless it's cmp $0,%reg, which is equivalent to
  10947. test %reg,%reg }
  10948. OrXorUsed and
  10949. (taicpu(hp1).opcode = A_CMP) and
  10950. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10951. ) or
  10952. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10953. { Has to be an exact match on the register }
  10954. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10955. (
  10956. { Permit "test %reg,%reg" }
  10957. (taicpu(hp1).opcode = A_TEST) and
  10958. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10959. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10960. ) or
  10961. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10962. { Make sure the comparison value is not smaller than the
  10963. smallest allowed signed value for the minimum size (e.g.
  10964. -128 for 8-bit) }
  10965. not (
  10966. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10967. { Is it in the negative range? }
  10968. (
  10969. (taicpu(hp1).oper[0]^.val < 0) and
  10970. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10971. )
  10972. ) then
  10973. Break;
  10974. { Check to see if the active register is used afterwards }
  10975. TransferUsedRegs(TmpUsedRegs);
  10976. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10977. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10978. begin
  10979. { Make sure the comparison or any previous instructions
  10980. hasn't pushed the test values outside of the range of
  10981. MinSize }
  10982. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10983. begin
  10984. { Exceeded lower bound but not upper bound }
  10985. Exit;
  10986. end
  10987. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10988. begin
  10989. { Size didn't exceed lower bound }
  10990. TargetSize := MinSize;
  10991. end
  10992. else
  10993. Break;
  10994. case TargetSize of
  10995. S_B:
  10996. TargetSubReg := R_SUBL;
  10997. S_W:
  10998. TargetSubReg := R_SUBW;
  10999. S_L:
  11000. TargetSubReg := R_SUBD;
  11001. else
  11002. InternalError(2021051002);
  11003. end;
  11004. if TargetSize <> MaxSize then
  11005. begin
  11006. { Update the register to its new size }
  11007. setsubreg(ThisReg, TargetSubReg);
  11008. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  11009. taicpu(hp1).oper[1]^.reg := ThisReg;
  11010. taicpu(hp1).opsize := TargetSize;
  11011. { Convert the input MOVZX to a MOV if necessary }
  11012. AdjustInitialLoadAndSize;
  11013. if (InstrMax >= 0) then
  11014. begin
  11015. for Index := 0 to InstrMax do
  11016. begin
  11017. { If p_removed is true, then the original MOV/Z was removed
  11018. and removing the AND instruction may not be safe if it
  11019. appears first }
  11020. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  11021. InternalError(2020112311);
  11022. if InstrList[Index].oper[0]^.typ = top_reg then
  11023. InstrList[Index].oper[0]^.reg := ThisReg;
  11024. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  11025. InstrList[Index].opsize := MinSize;
  11026. end;
  11027. end;
  11028. Result := True;
  11029. end;
  11030. Exit;
  11031. end;
  11032. end;
  11033. A_SETcc:
  11034. begin
  11035. { This allows this Movx optimisation to work through the SETcc instructions
  11036. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  11037. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  11038. skip over these SETcc instructions). }
  11039. if (cs_opt_level3 in current_settings.optimizerswitches) or
  11040. { Of course, break out if the current register is used }
  11041. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  11042. Break
  11043. else
  11044. { We must use Continue so the instruction doesn't get added
  11045. to InstrList }
  11046. Continue;
  11047. end;
  11048. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  11049. begin
  11050. if
  11051. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  11052. { Has to be an exact match on the register }
  11053. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  11054. (
  11055. (
  11056. (taicpu(hp1).oper[0]^.typ = top_const) and
  11057. (
  11058. (
  11059. (taicpu(hp1).opcode = A_SHL) and
  11060. (
  11061. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  11062. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  11063. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  11064. )
  11065. ) or (
  11066. (taicpu(hp1).opcode <> A_SHL) and
  11067. (
  11068. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11069. { Is it in the negative range? }
  11070. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  11071. )
  11072. )
  11073. )
  11074. ) or (
  11075. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  11076. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  11077. )
  11078. ) then
  11079. Break;
  11080. { Only process OR and XOR if there are only bitwise operations,
  11081. since otherwise they can too easily fool the data flow
  11082. analysis (they can cause non-linear behaviour) }
  11083. case taicpu(hp1).opcode of
  11084. A_ADD:
  11085. begin
  11086. if OrXorUsed then
  11087. { Too high a risk of non-linear behaviour that breaks DFA here }
  11088. Break
  11089. else
  11090. BitwiseOnly := False;
  11091. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11092. begin
  11093. TestValMin := TestValMin * 2;
  11094. TestValMax := TestValMax * 2;
  11095. TestValSignedMax := TestValSignedMax * 2;
  11096. end
  11097. else
  11098. begin
  11099. WorkingValue := taicpu(hp1).oper[0]^.val;
  11100. TestValMin := TestValMin + WorkingValue;
  11101. TestValMax := TestValMax + WorkingValue;
  11102. TestValSignedMax := TestValSignedMax + WorkingValue;
  11103. end;
  11104. end;
  11105. A_SUB:
  11106. begin
  11107. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11108. begin
  11109. TestValMin := 0;
  11110. TestValMax := 0;
  11111. TestValSignedMax := 0;
  11112. end
  11113. else
  11114. begin
  11115. if OrXorUsed then
  11116. { Too high a risk of non-linear behaviour that breaks DFA here }
  11117. Break
  11118. else
  11119. BitwiseOnly := False;
  11120. WorkingValue := taicpu(hp1).oper[0]^.val;
  11121. TestValMin := TestValMin - WorkingValue;
  11122. TestValMax := TestValMax - WorkingValue;
  11123. TestValSignedMax := TestValSignedMax - WorkingValue;
  11124. end;
  11125. end;
  11126. A_AND:
  11127. if (taicpu(hp1).oper[0]^.typ = top_const) then
  11128. begin
  11129. { we might be able to go smaller if AND appears first }
  11130. if InstrMax = -1 then
  11131. case MinSize of
  11132. S_B:
  11133. ;
  11134. S_W:
  11135. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  11136. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  11137. begin
  11138. TryShiftDown := S_B;
  11139. TryShiftDownLimit := $FF;
  11140. end;
  11141. S_L:
  11142. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  11143. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  11144. begin
  11145. TryShiftDown := S_B;
  11146. TryShiftDownLimit := $FF;
  11147. end
  11148. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  11149. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  11150. begin
  11151. TryShiftDown := S_W;
  11152. TryShiftDownLimit := $FFFF;
  11153. end;
  11154. else
  11155. InternalError(2020112320);
  11156. end;
  11157. WorkingValue := taicpu(hp1).oper[0]^.val;
  11158. TestValMin := TestValMin and WorkingValue;
  11159. TestValMax := TestValMax and WorkingValue;
  11160. TestValSignedMax := TestValSignedMax and WorkingValue;
  11161. end;
  11162. A_OR:
  11163. begin
  11164. if not BitwiseOnly then
  11165. Break;
  11166. OrXorUsed := True;
  11167. WorkingValue := taicpu(hp1).oper[0]^.val;
  11168. TestValMin := TestValMin or WorkingValue;
  11169. TestValMax := TestValMax or WorkingValue;
  11170. TestValSignedMax := TestValSignedMax or WorkingValue;
  11171. end;
  11172. A_XOR:
  11173. begin
  11174. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11175. begin
  11176. TestValMin := 0;
  11177. TestValMax := 0;
  11178. TestValSignedMax := 0;
  11179. end
  11180. else
  11181. begin
  11182. if not BitwiseOnly then
  11183. Break;
  11184. OrXorUsed := True;
  11185. WorkingValue := taicpu(hp1).oper[0]^.val;
  11186. TestValMin := TestValMin xor WorkingValue;
  11187. TestValMax := TestValMax xor WorkingValue;
  11188. TestValSignedMax := TestValSignedMax xor WorkingValue;
  11189. end;
  11190. end;
  11191. A_SHL:
  11192. begin
  11193. BitwiseOnly := False;
  11194. WorkingValue := taicpu(hp1).oper[0]^.val;
  11195. TestValMin := TestValMin shl WorkingValue;
  11196. TestValMax := TestValMax shl WorkingValue;
  11197. TestValSignedMax := TestValSignedMax shl WorkingValue;
  11198. end;
  11199. A_SHR,
  11200. { The first instruction was MOVZX, so the value won't be negative }
  11201. A_SAR:
  11202. begin
  11203. if InstrMax <> -1 then
  11204. BitwiseOnly := False
  11205. else
  11206. { we might be able to go smaller if SHR appears first }
  11207. case MinSize of
  11208. S_B:
  11209. ;
  11210. S_W:
  11211. if (taicpu(hp1).oper[0]^.val >= 8) then
  11212. begin
  11213. TryShiftDown := S_B;
  11214. TryShiftDownLimit := $FF;
  11215. TryShiftDownSignedLimit := $7F;
  11216. TryShiftDownSignedLimitLower := -128;
  11217. end;
  11218. S_L:
  11219. if (taicpu(hp1).oper[0]^.val >= 24) then
  11220. begin
  11221. TryShiftDown := S_B;
  11222. TryShiftDownLimit := $FF;
  11223. TryShiftDownSignedLimit := $7F;
  11224. TryShiftDownSignedLimitLower := -128;
  11225. end
  11226. else if (taicpu(hp1).oper[0]^.val >= 16) then
  11227. begin
  11228. TryShiftDown := S_W;
  11229. TryShiftDownLimit := $FFFF;
  11230. TryShiftDownSignedLimit := $7FFF;
  11231. TryShiftDownSignedLimitLower := -32768;
  11232. end;
  11233. else
  11234. InternalError(2020112321);
  11235. end;
  11236. WorkingValue := taicpu(hp1).oper[0]^.val;
  11237. if taicpu(hp1).opcode = A_SAR then
  11238. begin
  11239. TestValMin := SarInt64(TestValMin, WorkingValue);
  11240. TestValMax := SarInt64(TestValMax, WorkingValue);
  11241. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  11242. end
  11243. else
  11244. begin
  11245. TestValMin := TestValMin shr WorkingValue;
  11246. TestValMax := TestValMax shr WorkingValue;
  11247. TestValSignedMax := TestValSignedMax shr WorkingValue;
  11248. end;
  11249. end;
  11250. else
  11251. InternalError(2020112303);
  11252. end;
  11253. end;
  11254. (*
  11255. A_IMUL:
  11256. case taicpu(hp1).ops of
  11257. 2:
  11258. begin
  11259. if not MatchOpType(hp1, top_reg, top_reg) or
  11260. { Has to be an exact match on the register }
  11261. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  11262. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  11263. Break;
  11264. TestValMin := TestValMin * TestValMin;
  11265. TestValMax := TestValMax * TestValMax;
  11266. TestValSignedMax := TestValSignedMax * TestValMax;
  11267. end;
  11268. 3:
  11269. begin
  11270. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11271. { Has to be an exact match on the register }
  11272. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11273. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11274. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11275. { Is it in the negative range? }
  11276. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11277. Break;
  11278. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  11279. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  11280. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  11281. end;
  11282. else
  11283. Break;
  11284. end;
  11285. A_IDIV:
  11286. case taicpu(hp1).ops of
  11287. 3:
  11288. begin
  11289. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  11290. { Has to be an exact match on the register }
  11291. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  11292. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  11293. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  11294. { Is it in the negative range? }
  11295. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  11296. Break;
  11297. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  11298. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  11299. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  11300. end;
  11301. else
  11302. Break;
  11303. end;
  11304. *)
  11305. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11306. begin
  11307. { If there are no instructions in between, then we might be able to make a saving }
  11308. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  11309. Break;
  11310. { We have something like:
  11311. movzbw %dl,%dx
  11312. ...
  11313. movswl %dx,%edx
  11314. Change the latter to a zero-extension then enter the
  11315. A_MOVZX case branch.
  11316. }
  11317. {$ifdef x86_64}
  11318. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11319. begin
  11320. { this becomes a zero extension from 32-bit to 64-bit, but
  11321. the upper 32 bits are already zero, so just delete the
  11322. instruction }
  11323. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11324. RemoveInstruction(hp1);
  11325. Result := True;
  11326. Exit;
  11327. end
  11328. else
  11329. {$endif x86_64}
  11330. begin
  11331. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11332. taicpu(hp1).opcode := A_MOVZX;
  11333. {$ifdef x86_64}
  11334. case taicpu(hp1).opsize of
  11335. S_BQ:
  11336. begin
  11337. taicpu(hp1).opsize := S_BL;
  11338. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11339. end;
  11340. S_WQ:
  11341. begin
  11342. taicpu(hp1).opsize := S_WL;
  11343. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11344. end;
  11345. S_LQ:
  11346. begin
  11347. taicpu(hp1).opcode := A_MOV;
  11348. taicpu(hp1).opsize := S_L;
  11349. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11350. { In this instance, we need to break out because the
  11351. instruction is no longer MOVZX or MOVSXD }
  11352. Result := True;
  11353. Exit;
  11354. end;
  11355. else
  11356. ;
  11357. end;
  11358. {$endif x86_64}
  11359. Result := CompressInstructions;
  11360. Exit;
  11361. end;
  11362. end;
  11363. A_MOVZX:
  11364. begin
  11365. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11366. Break;
  11367. if (InstrMax = -1) then
  11368. begin
  11369. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11370. begin
  11371. { Optimise around i40003 }
  11372. { Check to see if the active register is used afterwards }
  11373. TransferUsedRegs(TmpUsedRegs);
  11374. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  11375. if (
  11376. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) or
  11377. not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs)
  11378. ) and
  11379. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11380. {$ifndef x86_64}
  11381. and (
  11382. (taicpu(p).oper[0]^.typ <> top_reg) or
  11383. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11384. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11385. )
  11386. {$endif not x86_64}
  11387. then
  11388. begin
  11389. if (taicpu(p).oper[0]^.typ = top_reg) then
  11390. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11391. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11392. taicpu(p).opsize := S_BL;
  11393. { Only remove if the active register is overwritten }
  11394. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11395. begin
  11396. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11397. RemoveInstruction(hp1);
  11398. end;
  11399. Result := True;
  11400. Exit;
  11401. end;
  11402. end
  11403. else
  11404. begin
  11405. { Will return false if the second parameter isn't ThisReg
  11406. (can happen on -O2 and under) }
  11407. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11408. begin
  11409. { The two MOVZX instructions are adjacent, so remove the first one }
  11410. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11411. RemoveCurrentP(p);
  11412. Result := True;
  11413. Exit;
  11414. end;
  11415. Break;
  11416. end;
  11417. end;
  11418. Result := CompressInstructions;
  11419. Exit;
  11420. end;
  11421. else
  11422. { This includes ADC, SBB and IDIV }
  11423. Break;
  11424. end;
  11425. if not CheckOverflowConditions then
  11426. Break;
  11427. { Contains highest index (so instruction count - 1) }
  11428. Inc(InstrMax);
  11429. if InstrMax > High(InstrList) then
  11430. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11431. InstrList[InstrMax] := taicpu(hp1);
  11432. end;
  11433. end;
  11434. {$pop}
  11435. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11436. var
  11437. hp1 : tai;
  11438. begin
  11439. Result:=false;
  11440. if (taicpu(p).ops >= 2) and
  11441. ((taicpu(p).oper[0]^.typ = top_const) or
  11442. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11443. (taicpu(p).oper[1]^.typ = top_reg) and
  11444. ((taicpu(p).ops = 2) or
  11445. ((taicpu(p).oper[2]^.typ = top_reg) and
  11446. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11447. GetLastInstruction(p,hp1) and
  11448. MatchInstruction(hp1,A_MOV,[]) and
  11449. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11450. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11451. begin
  11452. TransferUsedRegs(TmpUsedRegs);
  11453. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11454. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11455. { change
  11456. mov reg1,reg2
  11457. imul y,reg2 to imul y,reg1,reg2 }
  11458. begin
  11459. taicpu(p).ops := 3;
  11460. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11461. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11462. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11463. RemoveInstruction(hp1);
  11464. result:=true;
  11465. end;
  11466. end;
  11467. end;
  11468. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11469. var
  11470. ThisLabel: TAsmLabel;
  11471. begin
  11472. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11473. ThisLabel.decrefs;
  11474. taicpu(p).condition := C_None;
  11475. taicpu(p).opcode := A_RET;
  11476. taicpu(p).is_jmp := false;
  11477. taicpu(p).ops := taicpu(ret_p).ops;
  11478. case taicpu(ret_p).ops of
  11479. 0:
  11480. taicpu(p).clearop(0);
  11481. 1:
  11482. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11483. else
  11484. internalerror(2016041301);
  11485. end;
  11486. { If the original label is now dead, it might turn out that the label
  11487. immediately follows p. As a result, everything beyond it, which will
  11488. be just some final register configuration and a RET instruction, is
  11489. now dead code. [Kit] }
  11490. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11491. running RemoveDeadCodeAfterJump for each RET instruction, because
  11492. this optimisation rarely happens and most RETs appear at the end of
  11493. routines where there is nothing that can be stripped. [Kit] }
  11494. if not ThisLabel.is_used then
  11495. RemoveDeadCodeAfterJump(p);
  11496. end;
  11497. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11498. var
  11499. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11500. Unconditional, PotentialModified: Boolean;
  11501. OperPtr: POper;
  11502. NewRef: TReference;
  11503. InstrList: array of taicpu;
  11504. InstrMax, Index: Integer;
  11505. const
  11506. {$ifdef DEBUG_AOPTCPU}
  11507. SNoFlags: shortstring = ' so the flags aren''t modified';
  11508. {$else DEBUG_AOPTCPU}
  11509. SNoFlags = '';
  11510. {$endif DEBUG_AOPTCPU}
  11511. begin
  11512. Result:=false;
  11513. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11514. begin
  11515. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11516. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11517. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11518. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11519. GetNextInstruction(hp1, hp2) and
  11520. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11521. { Change from: To:
  11522. set(C) %reg j(~C) label
  11523. test %reg,%reg/cmp $0,%reg
  11524. je label
  11525. set(C) %reg j(C) label
  11526. test %reg,%reg/cmp $0,%reg
  11527. jne label
  11528. (Also do something similar with sete/setne instead of je/jne)
  11529. }
  11530. begin
  11531. { Before we do anything else, we need to check the instructions
  11532. in between SETcc and TEST to make sure they don't modify the
  11533. FLAGS register - if -O2 or under, there won't be any
  11534. instructions between SET and TEST }
  11535. TransferUsedRegs(TmpUsedRegs);
  11536. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11537. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11538. begin
  11539. next := p;
  11540. SetLength(InstrList, 0);
  11541. InstrMax := -1;
  11542. PotentialModified := False;
  11543. { Make a note of every instruction that modifies the FLAGS
  11544. register }
  11545. while GetNextInstruction(next, next) and (next <> hp1) do
  11546. begin
  11547. if next.typ <> ait_instruction then
  11548. { GetNextInstructionUsingReg should have returned False }
  11549. InternalError(2021051701);
  11550. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11551. begin
  11552. case taicpu(next).opcode of
  11553. A_SETcc,
  11554. A_CMOVcc,
  11555. A_Jcc:
  11556. begin
  11557. if PotentialModified then
  11558. { Not safe because the flags were modified earlier }
  11559. Exit
  11560. else
  11561. { Condition is the same as the initial SETcc, so this is safe
  11562. (don't add to instruction list though) }
  11563. Continue;
  11564. end;
  11565. A_ADD:
  11566. begin
  11567. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11568. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11569. (taicpu(next).oper[1]^.typ <> top_reg) or
  11570. { Must write to a register }
  11571. (taicpu(next).oper[0]^.typ = top_ref) then
  11572. { Require a constant or a register }
  11573. Exit;
  11574. PotentialModified := True;
  11575. end;
  11576. A_SUB:
  11577. begin
  11578. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11579. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11580. (taicpu(next).oper[1]^.typ <> top_reg) or
  11581. { Must write to a register }
  11582. (taicpu(next).oper[0]^.typ <> top_const) or
  11583. (taicpu(next).oper[0]^.val = $80000000) then
  11584. { Can't subtract a register with LEA - also
  11585. check that the value isn't -2^31, as this
  11586. can't be negated }
  11587. Exit;
  11588. PotentialModified := True;
  11589. end;
  11590. A_SAL,
  11591. A_SHL:
  11592. begin
  11593. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11594. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11595. (taicpu(next).oper[1]^.typ <> top_reg) or
  11596. { Must write to a register }
  11597. (taicpu(next).oper[0]^.typ <> top_const) or
  11598. (taicpu(next).oper[0]^.val < 0) or
  11599. (taicpu(next).oper[0]^.val > 3) then
  11600. Exit;
  11601. PotentialModified := True;
  11602. end;
  11603. A_IMUL:
  11604. begin
  11605. if (taicpu(next).ops <> 3) or
  11606. (taicpu(next).oper[1]^.typ <> top_reg) or
  11607. { Must write to a register }
  11608. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11609. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11610. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11611. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11612. Exit
  11613. else
  11614. PotentialModified := True;
  11615. end;
  11616. else
  11617. { Don't know how to change this, so abort }
  11618. Exit;
  11619. end;
  11620. { Contains highest index (so instruction count - 1) }
  11621. Inc(InstrMax);
  11622. if InstrMax > High(InstrList) then
  11623. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11624. InstrList[InstrMax] := taicpu(next);
  11625. end;
  11626. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11627. end;
  11628. if not Assigned(next) or (next <> hp1) then
  11629. { It should be equal to hp1 }
  11630. InternalError(2021051702);
  11631. { Cycle through each instruction and check to see if we can
  11632. change them to versions that don't modify the flags }
  11633. if (InstrMax >= 0) then
  11634. begin
  11635. for Index := 0 to InstrMax do
  11636. case InstrList[Index].opcode of
  11637. A_ADD:
  11638. begin
  11639. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11640. InstrList[Index].opcode := A_LEA;
  11641. reference_reset(NewRef, 1, []);
  11642. NewRef.base := InstrList[Index].oper[1]^.reg;
  11643. if InstrList[Index].oper[0]^.typ = top_reg then
  11644. begin
  11645. NewRef.index := InstrList[Index].oper[0]^.reg;
  11646. NewRef.scalefactor := 1;
  11647. end
  11648. else
  11649. NewRef.offset := InstrList[Index].oper[0]^.val;
  11650. InstrList[Index].loadref(0, NewRef);
  11651. end;
  11652. A_SUB:
  11653. begin
  11654. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11655. InstrList[Index].opcode := A_LEA;
  11656. reference_reset(NewRef, 1, []);
  11657. NewRef.base := InstrList[Index].oper[1]^.reg;
  11658. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11659. InstrList[Index].loadref(0, NewRef);
  11660. end;
  11661. A_SHL,
  11662. A_SAL:
  11663. begin
  11664. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11665. InstrList[Index].opcode := A_LEA;
  11666. reference_reset(NewRef, 1, []);
  11667. NewRef.index := InstrList[Index].oper[1]^.reg;
  11668. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11669. InstrList[Index].loadref(0, NewRef);
  11670. end;
  11671. A_IMUL:
  11672. begin
  11673. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11674. InstrList[Index].opcode := A_LEA;
  11675. reference_reset(NewRef, 1, []);
  11676. NewRef.index := InstrList[Index].oper[1]^.reg;
  11677. case InstrList[Index].oper[0]^.val of
  11678. 2, 4, 8:
  11679. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11680. else {3, 5 and 9}
  11681. begin
  11682. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11683. NewRef.base := InstrList[Index].oper[1]^.reg;
  11684. end;
  11685. end;
  11686. InstrList[Index].loadref(0, NewRef);
  11687. end;
  11688. else
  11689. InternalError(2021051710);
  11690. end;
  11691. end;
  11692. { Mark the FLAGS register as used across this whole block }
  11693. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11694. end;
  11695. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11696. JumpC := taicpu(hp2).condition;
  11697. Unconditional := False;
  11698. if conditions_equal(JumpC, C_E) then
  11699. SetC := inverse_cond(taicpu(p).condition)
  11700. else if conditions_equal(JumpC, C_NE) then
  11701. SetC := taicpu(p).condition
  11702. else
  11703. { We've got something weird here (and inefficent) }
  11704. begin
  11705. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11706. SetC := C_NONE;
  11707. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11708. if condition_in(C_AE, JumpC) then
  11709. Unconditional := True
  11710. else
  11711. { Not sure what to do with this jump - drop out }
  11712. Exit;
  11713. end;
  11714. RemoveInstruction(hp1);
  11715. if Unconditional then
  11716. MakeUnconditional(taicpu(hp2))
  11717. else
  11718. begin
  11719. if SetC = C_NONE then
  11720. InternalError(2018061402);
  11721. taicpu(hp2).SetCondition(SetC);
  11722. end;
  11723. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11724. TmpUsedRegs }
  11725. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11726. begin
  11727. RemoveCurrentp(p, hp2);
  11728. if taicpu(hp2).opcode = A_SETcc then
  11729. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11730. else
  11731. begin
  11732. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11733. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11734. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11735. end;
  11736. end
  11737. else
  11738. if taicpu(hp2).opcode = A_SETcc then
  11739. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11740. else
  11741. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11742. Result := True;
  11743. end
  11744. else if
  11745. { Make sure the instructions are adjacent }
  11746. (
  11747. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11748. GetNextInstruction(p, hp1)
  11749. ) and
  11750. MatchInstruction(hp1, A_MOV, [S_B]) and
  11751. { Writing to memory is allowed }
  11752. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11753. begin
  11754. {
  11755. Watch out for sequences such as:
  11756. set(c)b %regb
  11757. movb %regb,(ref)
  11758. movb $0,1(ref)
  11759. movb $0,2(ref)
  11760. movb $0,3(ref)
  11761. Much more efficient to turn it into:
  11762. movl $0,%regl
  11763. set(c)b %regb
  11764. movl %regl,(ref)
  11765. Or:
  11766. set(c)b %regb
  11767. movzbl %regb,%regl
  11768. movl %regl,(ref)
  11769. }
  11770. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11771. GetNextInstruction(hp1, hp2) and
  11772. MatchInstruction(hp2, A_MOV, [S_B]) and
  11773. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11774. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11775. begin
  11776. { Don't do anything else except set Result to True }
  11777. end
  11778. else
  11779. begin
  11780. if taicpu(p).oper[0]^.typ = top_reg then
  11781. begin
  11782. TransferUsedRegs(TmpUsedRegs);
  11783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11784. end;
  11785. { If it's not a register, it's a memory address }
  11786. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11787. begin
  11788. { Even if the register is still in use, we can minimise the
  11789. pipeline stall by changing the MOV into another SETcc. }
  11790. taicpu(hp1).opcode := A_SETcc;
  11791. taicpu(hp1).condition := taicpu(p).condition;
  11792. if taicpu(hp1).oper[1]^.typ = top_ref then
  11793. begin
  11794. { Swapping the operand pointers like this is probably a
  11795. bit naughty, but it is far faster than using loadoper
  11796. to transfer the reference from oper[1] to oper[0] if
  11797. you take into account the extra procedure calls and
  11798. the memory allocation and deallocation required }
  11799. OperPtr := taicpu(hp1).oper[1];
  11800. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11801. taicpu(hp1).oper[0] := OperPtr;
  11802. end
  11803. else
  11804. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11805. taicpu(hp1).clearop(1);
  11806. taicpu(hp1).ops := 1;
  11807. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11808. end
  11809. else
  11810. begin
  11811. if taicpu(hp1).oper[1]^.typ = top_reg then
  11812. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11813. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11814. RemoveInstruction(hp1);
  11815. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11816. end
  11817. end;
  11818. Result := True;
  11819. end;
  11820. end;
  11821. end;
  11822. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11823. var
  11824. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11825. TargetReg: TRegister;
  11826. condition, inverted_condition: TAsmCond;
  11827. FoundMOV: Boolean;
  11828. begin
  11829. Result := False;
  11830. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11831. create the most optimial instructions possible due to limited
  11832. register availability, and there are situations where two
  11833. complementary "simple" CMOV blocks are created which, after the fact
  11834. can be merged into a "double" block. For example:
  11835. movw $257,%ax
  11836. movw $2,%r8w
  11837. xorl r9d,%r9d
  11838. testw $16,18(%rcx)
  11839. cmovew %ax,%dx
  11840. cmovew %r8w,%bx
  11841. cmovel %r9d,%r14d
  11842. movw $1283,%ax
  11843. movw $4,%r8w
  11844. movl $9,%r9d
  11845. cmovnew %ax,%dx
  11846. cmovnew %r8w,%bx
  11847. cmovnel %r9d,%r14d
  11848. The CMOVNE instructions at the end can be removed, and the
  11849. destination registers copied into the MOV instructions directly
  11850. above them, before finally being moved to before the first CMOVE
  11851. instructions, to produce:
  11852. movw $257,%ax
  11853. movw $2,%r8w
  11854. xorl r9d,%r9d
  11855. testw $16,18(%rcx)
  11856. movw $1283,%dx
  11857. movw $4,%bx
  11858. movl $9,%r14d
  11859. cmovew %ax,%dx
  11860. cmovew %r8w,%bx
  11861. cmovel %r9d,%r14d
  11862. Which can then be later optimised to:
  11863. movw $257,%ax
  11864. movw $2,%r8w
  11865. xorl r9d,%r9d
  11866. movw $1283,%dx
  11867. movw $4,%bx
  11868. movl $9,%r14d
  11869. testw $16,18(%rcx)
  11870. cmovew %ax,%dx
  11871. cmovew %r8w,%bx
  11872. cmovel %r9d,%r14d
  11873. }
  11874. TargetReg := taicpu(hp1).oper[1]^.reg;
  11875. condition := taicpu(hp1).condition;
  11876. inverted_condition := inverse_cond(condition);
  11877. pFirstMov := nil;
  11878. pLastMov := nil;
  11879. pCMOV := nil;
  11880. if (p.typ = ait_instruction) then
  11881. pCond := p
  11882. else if not GetNextInstruction(p, pCond) then
  11883. InternalError(2024012501);
  11884. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11885. { We should get the CMP or TEST instructeion }
  11886. InternalError(2024012502);
  11887. if (
  11888. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11889. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11890. ) then
  11891. begin
  11892. { We have to tread carefully here, hence why we're not using
  11893. GetNextInstructionUsingReg... we can only accept MOV and other
  11894. CMOV instructions. Anything else and we must drop out}
  11895. hp2 := hp1;
  11896. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11897. begin
  11898. if (hp2.typ <> ait_instruction) then
  11899. Exit;
  11900. case taicpu(hp2).opcode of
  11901. A_MOV:
  11902. begin
  11903. if not Assigned(pFirstMov) then
  11904. pFirstMov := hp2;
  11905. pLastMOV := hp2;
  11906. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11907. { Something different - drop out }
  11908. Exit;
  11909. { Otherwise, leave it for now }
  11910. end;
  11911. A_CMOVcc:
  11912. begin
  11913. if taicpu(hp2).condition = inverted_condition then
  11914. begin
  11915. { We found what we're looking for }
  11916. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11917. begin
  11918. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11919. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11920. begin
  11921. pCMOV := hp2;
  11922. Break;
  11923. end
  11924. else
  11925. { Unsafe reference - drop out }
  11926. Exit;
  11927. end;
  11928. end
  11929. else if taicpu(hp2).condition <> condition then
  11930. { Something weird - drop out }
  11931. Exit;
  11932. end;
  11933. else
  11934. { Invalid }
  11935. Exit;
  11936. end;
  11937. end;
  11938. if not Assigned(pCMOV) then
  11939. { No complementary CMOV found }
  11940. Exit;
  11941. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11942. begin
  11943. { Don't need to do anything special or search for a matching MOV }
  11944. Asml.Remove(pCMOV);
  11945. if RegInInstruction(TargetReg, pCond) then
  11946. { Make sure we don't overwrite the register if it's being used in the condition }
  11947. Asml.InsertAfter(pCMOV, pCond)
  11948. else
  11949. Asml.InsertBefore(pCMOV, pCond);
  11950. taicpu(pCMOV).opcode := A_MOV;
  11951. taicpu(pCMOV).condition := C_None;
  11952. { Don't need to worry about allocating new registers in these cases }
  11953. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11954. Result := True;
  11955. Exit;
  11956. end
  11957. else
  11958. begin
  11959. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11960. FoundMOV := False;
  11961. { Search for the MOV that sets the target register }
  11962. hp2 := pFirstMov;
  11963. repeat
  11964. if (taicpu(hp2).opcode = A_MOV) and
  11965. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11966. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11967. begin
  11968. { Change the destination }
  11969. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11970. if not FoundMOV then
  11971. begin
  11972. FoundMOV := True;
  11973. { Make sure the register is allocated }
  11974. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11975. end;
  11976. hp1 := tai(hp2.Previous);
  11977. Asml.Remove(hp2);
  11978. if RegInInstruction(TargetReg, pCond) then
  11979. { Make sure we don't overwrite the register if it's being used in the condition }
  11980. Asml.InsertAfter(hp2, pCond)
  11981. else
  11982. Asml.InsertBefore(hp2, pCond);
  11983. if (hp2 = pLastMov) then
  11984. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11985. Break;
  11986. hp2 := hp1;
  11987. end;
  11988. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11989. if FoundMOV then
  11990. { Delete the CMOV }
  11991. RemoveInstruction(pCMOV)
  11992. else
  11993. begin
  11994. { If no MOV was found, we have to actually move and transmute the CMOV }
  11995. Asml.Remove(pCMOV);
  11996. if RegInInstruction(TargetReg, pCond) then
  11997. { Make sure we don't overwrite the register if it's being used in the condition }
  11998. Asml.InsertAfter(pCMOV, pCond)
  11999. else
  12000. Asml.InsertBefore(pCMOV, pCond);
  12001. taicpu(pCMOV).opcode := A_MOV;
  12002. taicpu(pCMOV).condition := C_None;
  12003. end;
  12004. Result := True;
  12005. Exit;
  12006. end;
  12007. end;
  12008. end;
  12009. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  12010. var
  12011. hp1, hp2, pCond: tai;
  12012. begin
  12013. Result := False;
  12014. { Search ahead for CMOV instructions }
  12015. if (cs_opt_level2 in current_settings.optimizerswitches) then
  12016. begin
  12017. hp1 := p;
  12018. hp2 := p;
  12019. pCond := nil; { To prevent compiler warnings }
  12020. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  12021. DEFAULTFLAGS }
  12022. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  12023. (tai_regalloc(pCond).ratype = ra_dealloc) then
  12024. pCond := p;
  12025. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  12026. begin
  12027. if (hp1.typ <> ait_instruction) then
  12028. { Break out on markers and labels etc. }
  12029. Break;
  12030. case taicpu(hp1).opcode of
  12031. A_MOV:
  12032. { Ignore regular MOVs unless they are obviously not related
  12033. to a CMOV block }
  12034. if taicpu(hp1).oper[1]^.typ <> top_reg then
  12035. Break;
  12036. A_CMOVcc:
  12037. if TryCmpCMovOpts(pCond, hp1) then
  12038. begin
  12039. hp1 := hp2;
  12040. { p itself isn't changed, and we're still inside a
  12041. while loop to catch subsequent CMOVs, so just flag
  12042. a new iteration }
  12043. Include(OptsToCheck, aoc_ForceNewIteration);
  12044. Continue;
  12045. end;
  12046. else
  12047. { Drop out if we find anything else }
  12048. Break;
  12049. end;
  12050. hp2 := hp1;
  12051. end;
  12052. end;
  12053. end;
  12054. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  12055. var
  12056. hp1, hp2, pCond: tai;
  12057. SourceReg, TargetReg: TRegister;
  12058. begin
  12059. Result := False;
  12060. { In some situations, we end up with an inefficient arrangement of
  12061. instructions in the form of:
  12062. or %reg1,%reg2
  12063. (%reg1 deallocated)
  12064. test %reg2,%reg2
  12065. mov x,%reg2
  12066. we may be able to swap and rearrange the registers to produce:
  12067. or %reg2,%reg1
  12068. mov x,%reg2
  12069. test %reg1,%reg1
  12070. (%reg1 deallocated)
  12071. }
  12072. if (cs_opt_level3 in current_settings.optimizerswitches) and
  12073. (taicpu(p).oper[1]^.typ = top_reg) and
  12074. (
  12075. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  12076. MatchOperand(taicpu(p).oper[0]^, -1)
  12077. ) and
  12078. GetNextInstruction(p, hp1) and
  12079. MatchInstruction(hp1, A_MOV, []) and
  12080. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12081. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12082. begin
  12083. TargetReg := taicpu(p).oper[1]^.reg;
  12084. { Now look backwards to find a simple commutative operation: ADD,
  12085. IMUL (2-register version), OR, AND or XOR - whose destination
  12086. register is the same as TEST }
  12087. hp2 := p;
  12088. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  12089. if RegInInstruction(TargetReg, hp2) then
  12090. begin
  12091. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  12092. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12093. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  12094. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  12095. begin
  12096. SourceReg := taicpu(hp2).oper[0]^.reg;
  12097. if
  12098. { Make sure the MOV doesn't use the other register }
  12099. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  12100. { And make sure the source register is not used afterwards }
  12101. not RegInUsedRegs(SourceReg, UsedRegs) then
  12102. begin
  12103. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  12104. taicpu(hp2).oper[0]^.reg := TargetReg;
  12105. taicpu(hp2).oper[1]^.reg := SourceReg;
  12106. if taicpu(p).oper[0]^.typ = top_reg then
  12107. taicpu(p).oper[0]^.reg := SourceReg;
  12108. taicpu(p).oper[1]^.reg := SourceReg;
  12109. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  12110. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  12111. Include(OptsToCheck, aoc_ForceNewIteration);
  12112. { We can still check the following optimisations since
  12113. the instruction is still a TEST }
  12114. end;
  12115. end;
  12116. Break;
  12117. end;
  12118. end;
  12119. { Search ahead3 for CMOV instructions }
  12120. if (cs_opt_level2 in current_settings.optimizerswitches) then
  12121. begin
  12122. hp1 := p;
  12123. hp2 := p;
  12124. pCond := nil; { To prevent compiler warnings }
  12125. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  12126. DEFAULTFLAGS }
  12127. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  12128. (tai_regalloc(pCond).ratype = ra_dealloc) then
  12129. pCond := p;
  12130. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  12131. begin
  12132. if (hp1.typ <> ait_instruction) then
  12133. { Break out on markers and labels etc. }
  12134. Break;
  12135. case taicpu(hp1).opcode of
  12136. A_MOV:
  12137. { Ignore regular MOVs unless they are obviously not related
  12138. to a CMOV block }
  12139. if taicpu(hp1).oper[1]^.typ <> top_reg then
  12140. Break;
  12141. A_CMOVcc:
  12142. if TryCmpCMovOpts(pCond, hp1) then
  12143. begin
  12144. hp1 := hp2;
  12145. { p itself isn't changed, and we're still inside a
  12146. while loop to catch subsequent CMOVs, so just flag
  12147. a new iteration }
  12148. Include(OptsToCheck, aoc_ForceNewIteration);
  12149. Continue;
  12150. end;
  12151. else
  12152. { Drop out if we find anything else }
  12153. Break;
  12154. end;
  12155. hp2 := hp1;
  12156. end;
  12157. end;
  12158. end;
  12159. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  12160. var
  12161. hp1: tai;
  12162. Count: Integer;
  12163. OrigLabel: TAsmLabel;
  12164. begin
  12165. result := False;
  12166. { Sometimes, the optimisations below can permit this }
  12167. RemoveDeadCodeAfterJump(p);
  12168. 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
  12169. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  12170. begin
  12171. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12172. { Also a side-effect of optimisations }
  12173. if CollapseZeroDistJump(p, OrigLabel) then
  12174. begin
  12175. Result := True;
  12176. Exit;
  12177. end;
  12178. hp1 := GetLabelWithSym(OrigLabel);
  12179. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  12180. begin
  12181. if taicpu(hp1).opcode = A_RET then
  12182. begin
  12183. {
  12184. change
  12185. jmp .L1
  12186. ...
  12187. .L1:
  12188. ret
  12189. into
  12190. ret
  12191. }
  12192. begin
  12193. ConvertJumpToRET(p, hp1);
  12194. result:=true;
  12195. end;
  12196. end
  12197. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  12198. not (cs_opt_size in current_settings.optimizerswitches) and
  12199. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  12200. begin
  12201. Result := True;
  12202. Exit;
  12203. end;
  12204. end;
  12205. end;
  12206. end;
  12207. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  12208. begin
  12209. Result := assigned(p) and
  12210. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  12211. (taicpu(p).oper[1]^.typ = top_reg) and
  12212. (
  12213. (taicpu(p).oper[0]^.typ = top_reg) or
  12214. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  12215. it is not expected that this can cause a seg. violation }
  12216. (
  12217. (taicpu(p).oper[0]^.typ = top_ref) and
  12218. { TODO: Can we detect which references become constants at this
  12219. stage so we don't have to do a blanket ban? }
  12220. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  12221. (
  12222. IsRefSafe(taicpu(p).oper[0]^.ref) or
  12223. (
  12224. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  12225. not RefModified and
  12226. { If the reference also appears in the condition, then we know it's safe, otherwise
  12227. any kind of access violation would have occurred already }
  12228. Assigned(cond_p) and
  12229. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12230. (cond_p.typ = ait_instruction) and
  12231. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  12232. { Just consider 2-operand comparison instructions for now to be safe }
  12233. (taicpu(cond_p).ops = 2) and
  12234. (
  12235. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  12236. (
  12237. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  12238. { Don't risk identical registers but different offsets, as we may have constructs
  12239. such as buffer streams with things like length fields that indicate whether
  12240. any more data follows. And there are probably some contrived examples where
  12241. writing to offsets behind the one being read also lead to access violations }
  12242. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  12243. (
  12244. { Check that we're not modifying a register that appears in the reference }
  12245. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  12246. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  12247. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  12248. )
  12249. )
  12250. )
  12251. )
  12252. )
  12253. )
  12254. );
  12255. end;
  12256. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  12257. begin
  12258. { Update integer registers, ignoring deallocations }
  12259. repeat
  12260. while assigned(p) and
  12261. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  12262. (p.typ = ait_label) or
  12263. ((p.typ = ait_marker) and
  12264. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  12265. p := tai(p.next);
  12266. while assigned(p) and
  12267. (p.typ=ait_RegAlloc) Do
  12268. begin
  12269. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  12270. begin
  12271. case tai_regalloc(p).ratype of
  12272. ra_alloc :
  12273. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  12274. else
  12275. ;
  12276. end;
  12277. end;
  12278. p := tai(p.next);
  12279. end;
  12280. until not(assigned(p)) or
  12281. (not(p.typ in SkipInstr) and
  12282. not((p.typ = ait_label) and
  12283. labelCanBeSkipped(tai_label(p))));
  12284. end;
  12285. {$ifndef 8086}
  12286. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  12287. begin
  12288. Result := False;
  12289. EndJump := nil;
  12290. BlockStop := nil;
  12291. while (BlockStart <> fOptimizer.BlockEnd) and
  12292. { stop on labels }
  12293. (BlockStart.typ <> ait_label) do
  12294. begin
  12295. { Keep track of all integer registers that are used }
  12296. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  12297. if BlockStart.typ = ait_instruction then
  12298. begin
  12299. if (taicpu(BlockStart).opcode = A_JMP) then
  12300. begin
  12301. if not IsJumpToLabel(taicpu(BlockStart)) or
  12302. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  12303. Exit;
  12304. EndJump := BlockStart;
  12305. Break;
  12306. end
  12307. { Check to see if we have a valid MOV instruction instead }
  12308. else if (taicpu(BlockStart).opcode <> A_MOV) or
  12309. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  12310. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12311. begin
  12312. Exit;
  12313. end
  12314. else
  12315. { This will be a valid MOV }
  12316. fAllocationRange := BlockStart;
  12317. end;
  12318. OneBeforeBlock := BlockStart;
  12319. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  12320. end;
  12321. if (BlockStart = fOptimizer.BlockEnd) then
  12322. Exit;
  12323. BlockStop := BlockStart;
  12324. Result := True;
  12325. end;
  12326. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12327. var
  12328. hp1: tai;
  12329. RefModified: Boolean;
  12330. begin
  12331. Result := 0;
  12332. hp1 := BlockStart;
  12333. RefModified := False; { As long as the condition is inverted, this can be reset }
  12334. while assigned(hp1) and
  12335. (hp1 <> BlockStop) do
  12336. begin
  12337. case hp1.typ of
  12338. ait_instruction:
  12339. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12340. begin
  12341. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12342. begin
  12343. Inc(Result);
  12344. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12345. Assigned(fCondition) and
  12346. { Will have 2 operands }
  12347. (
  12348. (
  12349. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12350. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12351. ) or
  12352. (
  12353. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12354. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12355. )
  12356. ) then
  12357. { It is no longer safe to use the reference in the condition.
  12358. this prevents problems such as:
  12359. mov (%reg),%reg
  12360. mov (%reg),...
  12361. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12362. (fixes #40165)
  12363. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12364. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12365. }
  12366. RefModified := True;
  12367. end
  12368. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12369. { CMOV with constants grows the code size }
  12370. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12371. begin
  12372. { Register was reserved by TryCMOVConst and
  12373. stored on ConstRegs }
  12374. end
  12375. else
  12376. begin
  12377. Result := -1;
  12378. Exit;
  12379. end;
  12380. end
  12381. else
  12382. begin
  12383. Result := -1;
  12384. Exit;
  12385. end;
  12386. else
  12387. { Most likely an align };
  12388. end;
  12389. fOptimizer.GetNextInstruction(hp1, hp1);
  12390. end;
  12391. end;
  12392. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12393. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12394. (this is done as a separate stage because the double types are extensions of the branching type,
  12395. but we can't discount the conditional jump until the last step) }
  12396. procedure EvaluateBranchingType;
  12397. begin
  12398. Inc(CMOVScore);
  12399. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12400. { Too many instructions to be worthwhile }
  12401. fState := tsInvalid;
  12402. end;
  12403. var
  12404. hp1: tai;
  12405. Count: Integer;
  12406. begin
  12407. { Table of valid CMOV block types
  12408. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12409. ---------- --------- --------- --------- --------- ---------
  12410. tsSimple X Yes X X X
  12411. tsDetour = 1st X X X X
  12412. tsBranching <> Mid Yes X X X
  12413. tsDouble End-label Yes * Yes X Yes
  12414. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12415. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12416. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12417. * Only one reference allowed
  12418. }
  12419. hp1 := nil; { To prevent compiler warnings }
  12420. Optimizer.CopyUsedRegs(RegisterTracking);
  12421. fOptimizer := Optimizer;
  12422. fLabel := AFirstLabel;
  12423. CMOVScore := 0;
  12424. ConstCount := 0;
  12425. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12426. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12427. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12428. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12429. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12430. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12431. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12432. fInsertionPoint := p_initialjump;
  12433. fCondition := nil;
  12434. fInitialJump := p_initialjump;
  12435. fFirstMovBlock := p_initialmov;
  12436. fFirstMovBlockStop := nil;
  12437. fSecondJump := nil;
  12438. fSecondMovBlock := nil;
  12439. fSecondMovBlockStop := nil;
  12440. fMidLabel := nil;
  12441. fSecondJump := nil;
  12442. fSecondMovBlock := nil;
  12443. fEndLabel := nil;
  12444. fAllocationRange := nil;
  12445. { Assume it all goes horribly wrong! }
  12446. fState := tsInvalid;
  12447. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12448. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12449. 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
  12450. begin
  12451. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12452. for Count := 0 to 1 do
  12453. with taicpu(fCondition).oper[Count]^ do
  12454. case typ of
  12455. top_reg:
  12456. if getregtype(reg) = R_INTREGISTER then
  12457. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12458. top_ref:
  12459. begin
  12460. if
  12461. {$ifdef x86_64}
  12462. (ref^.base <> NR_RIP) and
  12463. {$endif x86_64}
  12464. (ref^.base <> NR_NO) then
  12465. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12466. if (ref^.index <> NR_NO) then
  12467. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12468. end
  12469. else
  12470. ;
  12471. end;
  12472. { When inserting instructions before hp_prev, try to insert them
  12473. before the allocation of the FLAGS register }
  12474. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12475. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12476. { If not found, set it equal to the condition so it's something sensible }
  12477. fInsertionPoint := fCondition;
  12478. { When dealing with a comparison against zero, take note of the
  12479. instruction before it to see if we can move instructions further
  12480. back in order to benefit PostPeepholeOptTestOr.
  12481. }
  12482. if (
  12483. (
  12484. (taicpu(fCondition).opcode = A_CMP) and
  12485. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12486. ) or
  12487. (
  12488. (taicpu(fCondition).opcode = A_TEST) and
  12489. (
  12490. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12491. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12492. )
  12493. )
  12494. ) and
  12495. Optimizer.GetLastInstruction(fCondition, hp1) then
  12496. begin
  12497. { These instructions set the zero flag if the result is zero }
  12498. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12499. begin
  12500. fInsertionPoint := hp1;
  12501. { Also mark all the registers in this previous instruction
  12502. as 'in use', even if they've just been deallocated }
  12503. for Count := 0 to 1 do
  12504. with taicpu(hp1).oper[Count]^ do
  12505. case typ of
  12506. top_reg:
  12507. if getregtype(reg) = R_INTREGISTER then
  12508. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12509. top_ref:
  12510. begin
  12511. if
  12512. {$ifdef x86_64}
  12513. (ref^.base <> NR_RIP) and
  12514. {$endif x86_64}
  12515. (ref^.base <> NR_NO) then
  12516. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12517. if (ref^.index <> NR_NO) then
  12518. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12519. end
  12520. else
  12521. ;
  12522. end;
  12523. end;
  12524. end;
  12525. end
  12526. else
  12527. fCondition := nil;
  12528. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12529. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12530. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12531. { If not found, set it equal to p so it's something sensible }
  12532. fInsertionPoint := hp1;
  12533. hp1 := p_initialmov;
  12534. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12535. Exit;
  12536. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12537. if (hp1.typ <> ait_label) then { should be on a jump }
  12538. begin
  12539. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12540. { Need a label afterwards }
  12541. Exit;
  12542. end
  12543. else
  12544. fMidLabel := hp1;
  12545. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12546. { Not the correct label }
  12547. fMidLabel := nil;
  12548. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12549. { If there's neither a 2nd jump nor correct label, then it's invalid
  12550. (see above table) }
  12551. Exit;
  12552. { Analyse the first block of MOVs more closely }
  12553. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12554. if Assigned(fSecondJump) then
  12555. begin
  12556. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12557. begin
  12558. fState := tsDetour
  12559. end
  12560. else
  12561. begin
  12562. { Need the correct mid-label for this one }
  12563. if not Assigned(fMidLabel) then
  12564. Exit;
  12565. fState := tsBranching;
  12566. end;
  12567. end
  12568. else
  12569. { No jump. but mid-label is present }
  12570. fState := tsSimple;
  12571. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12572. begin
  12573. { Invalid or too many instructions to be worthwhile }
  12574. fState := tsInvalid;
  12575. Exit;
  12576. end;
  12577. { check further for
  12578. jCC xxx
  12579. <several movs 1>
  12580. jmp yyy
  12581. xxx:
  12582. <several movs 2>
  12583. yyy:
  12584. etc.
  12585. }
  12586. if (fState = tsBranching) and
  12587. { Estimate for required savings for extra jump }
  12588. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12589. { Only one reference is allowed for double blocks }
  12590. (AFirstLabel.getrefs = 1) then
  12591. begin
  12592. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12593. fSecondMovBlock := hp1;
  12594. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12595. begin
  12596. EvaluateBranchingType;
  12597. Exit;
  12598. end;
  12599. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12600. if (hp1.typ <> ait_label) then { should be on a jump }
  12601. begin
  12602. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12603. begin
  12604. { Need a label afterwards }
  12605. EvaluateBranchingType;
  12606. Exit;
  12607. end;
  12608. end
  12609. else
  12610. fEndLabel := hp1;
  12611. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12612. { Second jump doesn't go to the end }
  12613. fEndLabel := nil;
  12614. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12615. begin
  12616. { If there's neither a 3rd jump nor correct end label, then it's
  12617. not a invalid double block, but is a valid single branching
  12618. block (see above table) }
  12619. EvaluateBranchingType;
  12620. Exit;
  12621. end;
  12622. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12623. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12624. { Invalid or too many instructions to be worthwhile }
  12625. Exit;
  12626. Inc(CMOVScore, Count);
  12627. if Assigned(fThirdJump) then
  12628. begin
  12629. if not Assigned(fSecondJump) then
  12630. fState := tsDoubleSecondBranching
  12631. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12632. fState := tsDoubleBranchSame
  12633. else
  12634. fState := tsDoubleBranchDifferent;
  12635. end
  12636. else
  12637. fState := tsDouble;
  12638. end;
  12639. if fState = tsBranching then
  12640. EvaluateBranchingType;
  12641. end;
  12642. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12643. new register to store the constant }
  12644. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12645. var
  12646. RegSize: TSubRegister;
  12647. CurrentVal: TCGInt;
  12648. ANewReg: TRegister;
  12649. X: ShortInt;
  12650. begin
  12651. Result := False;
  12652. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12653. Exit;
  12654. if ConstCount >= MAX_CMOV_REGISTERS then
  12655. { Arrays are full }
  12656. Exit;
  12657. { Remember that CMOV can't encode 8-bit registers }
  12658. case taicpu(p).opsize of
  12659. S_W:
  12660. RegSize := R_SUBW;
  12661. S_L:
  12662. RegSize := R_SUBD;
  12663. {$ifdef x86_64}
  12664. S_Q:
  12665. RegSize := R_SUBQ;
  12666. {$endif x86_64}
  12667. else
  12668. InternalError(2021100401);
  12669. end;
  12670. { See if the value has already been reserved for another CMOV instruction }
  12671. CurrentVal := taicpu(p).oper[0]^.val;
  12672. for X := 0 to ConstCount - 1 do
  12673. if ConstVals[X] = CurrentVal then
  12674. begin
  12675. ConstRegs[ConstCount] := ConstRegs[X];
  12676. ConstSizes[ConstCount] := RegSize;
  12677. ConstVals[ConstCount] := CurrentVal;
  12678. Inc(ConstCount);
  12679. Inc(Count);
  12680. Result := True;
  12681. Exit;
  12682. end;
  12683. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12684. if ANewReg = NR_NO then
  12685. { No free registers }
  12686. Exit;
  12687. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12688. up vying for the same register }
  12689. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12690. ConstRegs[ConstCount] := ANewReg;
  12691. ConstSizes[ConstCount] := RegSize;
  12692. ConstVals[ConstCount] := CurrentVal;
  12693. Inc(ConstCount);
  12694. Inc(Count);
  12695. Result := True;
  12696. end;
  12697. destructor TCMOVTracking.Done;
  12698. begin
  12699. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12700. end;
  12701. procedure TCMOVTracking.Process(out new_p: tai);
  12702. var
  12703. Count, Writes: LongInt;
  12704. RegMatch: Boolean;
  12705. hp1, hp_new: tai;
  12706. inverted_condition, condition: TAsmCond;
  12707. begin
  12708. if (fState in [tsInvalid, tsProcessed]) then
  12709. InternalError(2023110701);
  12710. { Repurpose RegisterTracking to mark registers that we've defined }
  12711. RegisterTracking[R_INTREGISTER].Clear;
  12712. Count := 0;
  12713. Writes := 0;
  12714. condition := taicpu(fInitialJump).condition;
  12715. inverted_condition := inverse_cond(condition);
  12716. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12717. doesn't get CMOVs in this case }
  12718. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12719. begin
  12720. { Include the jump in the flag tracking }
  12721. if Assigned(fThirdJump) then
  12722. begin
  12723. if (fState = tsDoubleBranchSame) then
  12724. begin
  12725. { Will be an unconditional jump, so track to the instruction before it }
  12726. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12727. InternalError(2023110710);
  12728. end
  12729. else
  12730. hp1 := fThirdJump;
  12731. end
  12732. else
  12733. hp1 := fSecondMovBlockStop;
  12734. end
  12735. else
  12736. begin
  12737. { Include a conditional jump in the flag tracking }
  12738. if Assigned(fSecondJump) then
  12739. begin
  12740. if (fState = tsDetour) then
  12741. begin
  12742. { Will be an unconditional jump, so track to the instruction before it }
  12743. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12744. InternalError(2023110711);
  12745. end
  12746. else
  12747. hp1 := fSecondJump;
  12748. end
  12749. else
  12750. hp1 := fFirstMovBlockStop;
  12751. end;
  12752. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12753. { Process the second set of MOVs first, because if a destination
  12754. register is shared between the first and second MOV sets, it is more
  12755. efficient to turn the first one into a MOV instruction and place it
  12756. before the CMP if possible, but we won't know which registers are
  12757. shared until we've processed at least one list, so we might as well
  12758. make it the second one since that won't be modified again. }
  12759. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12760. begin
  12761. hp1 := fSecondMovBlock;
  12762. repeat
  12763. if not Assigned(hp1) then
  12764. InternalError(2018062902);
  12765. if (hp1.typ = ait_instruction) then
  12766. begin
  12767. { Extra safeguard }
  12768. if (taicpu(hp1).opcode <> A_MOV) then
  12769. InternalError(2018062903);
  12770. { Note: tsDoubleBranchDifferent is essentially identical to
  12771. tsBranching and the 2nd block is best left largely
  12772. untouched, but we need to evaluate which registers the MOVs
  12773. write to in order to track what would be complementary CMOV
  12774. pairs that can be further optimised. [Kit] }
  12775. if fState <> tsDoubleBranchDifferent then
  12776. begin
  12777. if taicpu(hp1).oper[0]^.typ = top_const then
  12778. begin
  12779. RegMatch := False;
  12780. for Count := 0 to ConstCount - 1 do
  12781. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12782. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12783. begin
  12784. RegMatch := True;
  12785. { If it's in RegisterTracking, then this register
  12786. is being used more than once and hence has
  12787. already had its value defined (it gets added to
  12788. UsedRegs through AllocRegBetween below) }
  12789. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12790. begin
  12791. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12792. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12793. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12794. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12795. ConstMovs[Count] := hp_new;
  12796. end
  12797. else
  12798. { We just need an instruction between hp_prev and hp1
  12799. where we know the register is marked as in use }
  12800. hp_new := fSecondMovBlock;
  12801. { Keep track of largest write for this register so it can be optimised later }
  12802. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12803. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12804. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12805. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12806. Break;
  12807. end;
  12808. if not RegMatch then
  12809. InternalError(2021100411);
  12810. end;
  12811. taicpu(hp1).opcode := A_CMOVcc;
  12812. taicpu(hp1).condition := condition;
  12813. end;
  12814. { Store these writes to search for duplicates later on }
  12815. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12816. Inc(Writes);
  12817. end;
  12818. fOptimizer.GetNextInstruction(hp1, hp1);
  12819. until (hp1 = fSecondMovBlockStop);
  12820. end;
  12821. { Now do the first set of MOVs }
  12822. hp1 := fFirstMovBlock;
  12823. repeat
  12824. if not Assigned(hp1) then
  12825. InternalError(2018062904);
  12826. if (hp1.typ = ait_instruction) then
  12827. begin
  12828. RegMatch := False;
  12829. { Extra safeguard }
  12830. if (taicpu(hp1).opcode <> A_MOV) then
  12831. InternalError(2018062905);
  12832. { Search through the RegWrites list to see if there are any
  12833. opposing CMOV pairs that write to the same register }
  12834. for Count := 0 to Writes - 1 do
  12835. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12836. begin
  12837. { We have a match. Keep this as a MOV }
  12838. { Move ahead in preparation }
  12839. fOptimizer.GetNextInstruction(hp1, hp1);
  12840. RegMatch := True;
  12841. Break;
  12842. end;
  12843. if RegMatch then
  12844. Continue;
  12845. if taicpu(hp1).oper[0]^.typ = top_const then
  12846. begin
  12847. for Count := 0 to ConstCount - 1 do
  12848. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12849. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12850. begin
  12851. RegMatch := True;
  12852. { If it's in RegisterTracking, then this register is
  12853. being used more than once and hence has already had
  12854. its value defined (it gets added to UsedRegs through
  12855. AllocRegBetween below) }
  12856. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12857. begin
  12858. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12859. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12860. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12861. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12862. ConstMovs[Count] := hp_new;
  12863. end
  12864. else
  12865. { We just need an instruction between hp_prev and hp1
  12866. where we know the register is marked as in use }
  12867. hp_new := fFirstMovBlock;
  12868. { Keep track of largest write for this register so it can be optimised later }
  12869. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12870. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12871. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12872. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12873. Break;
  12874. end;
  12875. if not RegMatch then
  12876. InternalError(2021100412);
  12877. end;
  12878. taicpu(hp1).opcode := A_CMOVcc;
  12879. taicpu(hp1).condition := inverted_condition;
  12880. if (fState = tsDoubleBranchDifferent) then
  12881. begin
  12882. { Store these writes to search for duplicates later on }
  12883. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12884. Inc(Writes);
  12885. end;
  12886. end;
  12887. fOptimizer.GetNextInstruction(hp1, hp1);
  12888. until (hp1 = fFirstMovBlockStop);
  12889. { Update initialisation MOVs to the smallest possible size }
  12890. for Count := 0 to ConstCount - 1 do
  12891. if Assigned(ConstMovs[Count]) then
  12892. begin
  12893. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12894. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12895. end;
  12896. case fState of
  12897. tsSimple:
  12898. begin
  12899. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12900. { No branch to delete }
  12901. end;
  12902. tsDetour:
  12903. begin
  12904. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12905. { Preserve jump }
  12906. end;
  12907. tsBranching, tsDoubleBranchDifferent:
  12908. begin
  12909. if (fState = tsBranching) then
  12910. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12911. else
  12912. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12913. taicpu(fSecondJump).opcode := A_JCC;
  12914. taicpu(fSecondJump).condition := inverted_condition;
  12915. end;
  12916. tsDouble, tsDoubleBranchSame:
  12917. begin
  12918. if (fState = tsDouble) then
  12919. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12920. else
  12921. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12922. { Delete second jump }
  12923. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12924. fOptimizer.RemoveInstruction(fSecondJump);
  12925. end;
  12926. tsDoubleSecondBranching:
  12927. begin
  12928. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12929. { Delete second jump, preserve third jump as conditional }
  12930. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12931. fOptimizer.RemoveInstruction(fSecondJump);
  12932. taicpu(fThirdJump).opcode := A_JCC;
  12933. taicpu(fThirdJump).condition := condition;
  12934. end;
  12935. else
  12936. InternalError(2023110720);
  12937. end;
  12938. { Now we can safely decrement the reference count }
  12939. tasmlabel(fLabel).decrefs;
  12940. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12941. { Remove the original jump }
  12942. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12943. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12944. fState := tsProcessed;
  12945. end;
  12946. {$endif 8086}
  12947. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12948. var
  12949. hp1,hp2: tai;
  12950. carryadd_opcode : TAsmOp;
  12951. symbol: TAsmSymbol;
  12952. increg, tmpreg: TRegister;
  12953. {$ifndef i8086}
  12954. CMOVTracking: PCMOVTracking;
  12955. hp3,hp4,hp5: tai;
  12956. {$endif i8086}
  12957. TempBool: Boolean;
  12958. begin
  12959. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12960. DoJumpOptimizations(p, TempBool) then
  12961. Exit(True);
  12962. result:=false;
  12963. if GetNextInstruction(p,hp1) then
  12964. begin
  12965. if (hp1.typ=ait_label) then
  12966. begin
  12967. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12968. Exit;
  12969. end
  12970. else if (hp1.typ<>ait_instruction) then
  12971. Exit;
  12972. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12973. if (
  12974. (
  12975. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12976. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12977. (Taicpu(hp1).oper[0]^.val=1)
  12978. ) or
  12979. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12980. ) and
  12981. GetNextInstruction(hp1,hp2) and
  12982. FindLabel(TAsmLabel(symbol), hp2) then
  12983. { jb @@1 cmc
  12984. inc/dec operand --> adc/sbb operand,0
  12985. @@1:
  12986. ... and ...
  12987. jnb @@1
  12988. inc/dec operand --> adc/sbb operand,0
  12989. @@1: }
  12990. begin
  12991. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12992. begin
  12993. case taicpu(hp1).opcode of
  12994. A_INC,
  12995. A_ADD:
  12996. carryadd_opcode:=A_ADC;
  12997. A_DEC,
  12998. A_SUB:
  12999. carryadd_opcode:=A_SBB;
  13000. else
  13001. InternalError(2021011001);
  13002. end;
  13003. Taicpu(p).clearop(0);
  13004. Taicpu(p).ops:=0;
  13005. Taicpu(p).is_jmp:=false;
  13006. Taicpu(p).opcode:=A_CMC;
  13007. Taicpu(p).condition:=C_NONE;
  13008. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  13009. Taicpu(hp1).ops:=2;
  13010. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  13011. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  13012. else
  13013. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  13014. Taicpu(hp1).loadconst(0,0);
  13015. Taicpu(hp1).opcode:=carryadd_opcode;
  13016. result:=true;
  13017. exit;
  13018. end
  13019. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  13020. begin
  13021. case taicpu(hp1).opcode of
  13022. A_INC,
  13023. A_ADD:
  13024. carryadd_opcode:=A_ADC;
  13025. A_DEC,
  13026. A_SUB:
  13027. carryadd_opcode:=A_SBB;
  13028. else
  13029. InternalError(2021011002);
  13030. end;
  13031. Taicpu(hp1).ops:=2;
  13032. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  13033. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  13034. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  13035. else
  13036. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  13037. Taicpu(hp1).loadconst(0,0);
  13038. Taicpu(hp1).opcode:=carryadd_opcode;
  13039. RemoveCurrentP(p, hp1);
  13040. result:=true;
  13041. exit;
  13042. end
  13043. {
  13044. jcc @@1 setcc tmpreg
  13045. inc/dec/add/sub operand -> (movzx tmpreg)
  13046. @@1: add/sub tmpreg,operand
  13047. While this increases code size slightly, it makes the code much faster if the
  13048. jump is unpredictable
  13049. }
  13050. else if not(cs_opt_size in current_settings.optimizerswitches) then
  13051. begin
  13052. { search for an available register which is volatile }
  13053. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  13054. if increg <> NR_NO then
  13055. begin
  13056. { We don't need to check if tmpreg is in hp1 or not, because
  13057. it will be marked as in use at p (if not, this is
  13058. indictive of a compiler bug). }
  13059. TAsmLabel(symbol).decrefs;
  13060. Taicpu(p).clearop(0);
  13061. Taicpu(p).ops:=1;
  13062. Taicpu(p).is_jmp:=false;
  13063. Taicpu(p).opcode:=A_SETcc;
  13064. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  13065. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  13066. Taicpu(p).loadreg(0,increg);
  13067. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  13068. begin
  13069. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  13070. R_SUBW:
  13071. begin
  13072. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  13073. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  13074. end;
  13075. R_SUBD:
  13076. begin
  13077. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  13078. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  13079. end;
  13080. {$ifdef x86_64}
  13081. R_SUBQ:
  13082. begin
  13083. { MOVZX doesn't have a 64-bit variant, because
  13084. the 32-bit version implicitly zeroes the
  13085. upper 32-bits of the destination register }
  13086. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  13087. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  13088. setsubreg(tmpreg, R_SUBQ);
  13089. end;
  13090. {$endif x86_64}
  13091. else
  13092. Internalerror(2020030601);
  13093. end;
  13094. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  13095. asml.InsertAfter(hp2,p);
  13096. end
  13097. else
  13098. tmpreg := increg;
  13099. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  13100. begin
  13101. Taicpu(hp1).ops:=2;
  13102. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  13103. end;
  13104. Taicpu(hp1).loadreg(0,tmpreg);
  13105. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  13106. Result := True;
  13107. { p is no longer a Jcc instruction, so exit }
  13108. Exit;
  13109. end;
  13110. end;
  13111. end;
  13112. { Detect the following:
  13113. jmp<cond> @Lbl1
  13114. jmp @Lbl2
  13115. ...
  13116. @Lbl1:
  13117. ret
  13118. Change to:
  13119. jmp<inv_cond> @Lbl2
  13120. ret
  13121. }
  13122. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13123. begin
  13124. hp2:=getlabelwithsym(TAsmLabel(symbol));
  13125. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  13126. MatchInstruction(hp2,A_RET,[S_NO]) then
  13127. begin
  13128. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  13129. { Change label address to that of the unconditional jump }
  13130. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  13131. TAsmLabel(symbol).DecRefs;
  13132. taicpu(hp1).opcode := A_RET;
  13133. taicpu(hp1).is_jmp := false;
  13134. taicpu(hp1).ops := taicpu(hp2).ops;
  13135. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  13136. case taicpu(hp2).ops of
  13137. 0:
  13138. taicpu(hp1).clearop(0);
  13139. 1:
  13140. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  13141. else
  13142. internalerror(2016041302);
  13143. end;
  13144. end;
  13145. {$ifndef i8086}
  13146. end
  13147. {
  13148. convert
  13149. j<c> .L1
  13150. mov 1,reg
  13151. jmp .L2
  13152. .L1
  13153. mov 0,reg
  13154. .L2
  13155. into
  13156. mov 0,reg
  13157. set<not(c)> reg
  13158. take care of alignment and that the mov 0,reg is not converted into a xor as this
  13159. would destroy the flag contents
  13160. }
  13161. else if MatchInstruction(hp1,A_MOV,[]) and
  13162. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13163. {$ifdef i386}
  13164. (
  13165. { Under i386, ESI, EDI, EBP and ESP
  13166. don't have an 8-bit representation }
  13167. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  13168. ) and
  13169. {$endif i386}
  13170. (taicpu(hp1).oper[0]^.val=1) and
  13171. GetNextInstruction(hp1,hp2) and
  13172. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  13173. GetNextInstruction(hp2,hp3) and
  13174. (hp3.typ=ait_label) and
  13175. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  13176. (tai_label(hp3).labsym.getrefs=1) and
  13177. GetNextInstruction(hp3,hp4) and
  13178. MatchInstruction(hp4,A_MOV,[]) and
  13179. MatchOpType(taicpu(hp4),top_const,top_reg) and
  13180. (taicpu(hp4).oper[0]^.val=0) and
  13181. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  13182. GetNextInstruction(hp4,hp5) and
  13183. (hp5.typ=ait_label) and
  13184. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  13185. (tai_label(hp5).labsym.getrefs=1) then
  13186. begin
  13187. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  13188. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  13189. { remove last label }
  13190. RemoveInstruction(hp5);
  13191. { remove second label }
  13192. RemoveInstruction(hp3);
  13193. { remove jmp }
  13194. RemoveInstruction(hp2);
  13195. if taicpu(hp1).opsize=S_B then
  13196. RemoveInstruction(hp1)
  13197. else
  13198. taicpu(hp1).loadconst(0,0);
  13199. taicpu(hp4).opcode:=A_SETcc;
  13200. taicpu(hp4).opsize:=S_B;
  13201. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  13202. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  13203. taicpu(hp4).opercnt:=1;
  13204. taicpu(hp4).ops:=1;
  13205. taicpu(hp4).freeop(1);
  13206. RemoveCurrentP(p);
  13207. Result:=true;
  13208. exit;
  13209. end
  13210. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  13211. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  13212. begin
  13213. { check for
  13214. jCC xxx
  13215. <several movs>
  13216. xxx:
  13217. Also spot:
  13218. Jcc xxx
  13219. <several movs>
  13220. jmp xxx
  13221. Change to:
  13222. <several cmovs with inverted condition>
  13223. jmp xxx (only for the 2nd case)
  13224. }
  13225. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  13226. if CMOVTracking^.State <> tsInvalid then
  13227. begin
  13228. CMovTracking^.Process(p);
  13229. Result := True;
  13230. end;
  13231. CMOVTracking^.Done;
  13232. {$endif i8086}
  13233. end;
  13234. end;
  13235. end;
  13236. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  13237. var
  13238. hp1,hp2,hp3: tai;
  13239. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  13240. NewSize: TOpSize;
  13241. NewRegSize: TSubRegister;
  13242. Limit: TCgInt;
  13243. SwapOper: POper;
  13244. begin
  13245. result:=false;
  13246. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  13247. GetNextInstruction(p,hp1) and
  13248. (hp1.typ = ait_instruction);
  13249. if reg_and_hp1_is_instr and
  13250. (
  13251. (taicpu(hp1).opcode <> A_LEA) or
  13252. { If the LEA instruction can be converted into an arithmetic instruction,
  13253. it may be possible to then fold it. }
  13254. (
  13255. { If the flags register is in use, don't change the instruction
  13256. to an ADD otherwise this will scramble the flags. [Kit] }
  13257. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13258. ConvertLEA(taicpu(hp1))
  13259. )
  13260. ) and
  13261. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  13262. GetNextInstruction(hp1,hp2) and
  13263. MatchInstruction(hp2,A_MOV,[]) and
  13264. (taicpu(hp2).oper[0]^.typ = top_reg) and
  13265. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  13266. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  13267. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  13268. {$ifdef i386}
  13269. { not all registers have byte size sub registers on i386 }
  13270. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  13271. {$endif i386}
  13272. (((taicpu(hp1).ops=2) and
  13273. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  13274. ((taicpu(hp1).ops=1) and
  13275. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  13276. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  13277. begin
  13278. { change movsX/movzX reg/ref, reg2
  13279. add/sub/or/... reg3/$const, reg2
  13280. mov reg2 reg/ref
  13281. to add/sub/or/... reg3/$const, reg/ref }
  13282. { by example:
  13283. movswl %si,%eax movswl %si,%eax p
  13284. decl %eax addl %edx,%eax hp1
  13285. movw %ax,%si movw %ax,%si hp2
  13286. ->
  13287. movswl %si,%eax movswl %si,%eax p
  13288. decw %eax addw %edx,%eax hp1
  13289. movw %ax,%si movw %ax,%si hp2
  13290. }
  13291. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  13292. {
  13293. ->
  13294. movswl %si,%eax movswl %si,%eax p
  13295. decw %si addw %dx,%si hp1
  13296. movw %ax,%si movw %ax,%si hp2
  13297. }
  13298. case taicpu(hp1).ops of
  13299. 1:
  13300. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  13301. 2:
  13302. begin
  13303. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  13304. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  13305. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  13306. end;
  13307. else
  13308. internalerror(2008042702);
  13309. end;
  13310. {
  13311. ->
  13312. decw %si addw %dx,%si p
  13313. }
  13314. DebugMsg(SPeepholeOptimization + 'var3',p);
  13315. RemoveCurrentP(p, hp1);
  13316. RemoveInstruction(hp2);
  13317. Result := True;
  13318. Exit;
  13319. end;
  13320. if reg_and_hp1_is_instr and
  13321. (taicpu(hp1).opcode = A_MOV) and
  13322. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13323. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13324. {$ifdef x86_64}
  13325. { check for implicit extension to 64 bit }
  13326. or
  13327. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13328. (taicpu(hp1).opsize=S_Q) and
  13329. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13330. )
  13331. {$endif x86_64}
  13332. )
  13333. then
  13334. begin
  13335. { change
  13336. movx %reg1,%reg2
  13337. mov %reg2,%reg3
  13338. dealloc %reg2
  13339. into
  13340. movx %reg,%reg3
  13341. }
  13342. TransferUsedRegs(TmpUsedRegs);
  13343. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13344. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13345. begin
  13346. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13347. {$ifdef x86_64}
  13348. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13349. (taicpu(hp1).opsize=S_Q) then
  13350. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13351. else
  13352. {$endif x86_64}
  13353. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13354. RemoveInstruction(hp1);
  13355. Result := True;
  13356. Exit;
  13357. end;
  13358. end;
  13359. if reg_and_hp1_is_instr and
  13360. ((taicpu(hp1).opcode=A_MOV) or
  13361. (taicpu(hp1).opcode=A_ADD) or
  13362. (taicpu(hp1).opcode=A_SUB) or
  13363. (taicpu(hp1).opcode=A_CMP) or
  13364. (taicpu(hp1).opcode=A_OR) or
  13365. (taicpu(hp1).opcode=A_XOR) or
  13366. (taicpu(hp1).opcode=A_AND)
  13367. ) and
  13368. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13369. begin
  13370. AndTest := (taicpu(hp1).opcode=A_AND) and
  13371. GetNextInstruction(hp1, hp2) and
  13372. (hp2.typ = ait_instruction) and
  13373. (
  13374. (
  13375. (taicpu(hp2).opcode=A_TEST) and
  13376. (
  13377. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13378. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13379. (
  13380. { If the AND and TEST instructions share a constant, this is also valid }
  13381. (taicpu(hp1).oper[0]^.typ = top_const) and
  13382. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13383. )
  13384. ) and
  13385. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13386. ) or
  13387. (
  13388. (taicpu(hp2).opcode=A_CMP) and
  13389. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13390. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13391. )
  13392. );
  13393. { change
  13394. movx (oper),%reg2
  13395. and $x,%reg2
  13396. test %reg2,%reg2
  13397. dealloc %reg2
  13398. into
  13399. op %reg1,%reg3
  13400. if the second op accesses only the bits stored in reg1
  13401. }
  13402. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13403. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13404. (taicpu(hp1).oper[0]^.typ = top_const) and
  13405. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13406. AndTest then
  13407. begin
  13408. { Check if the AND constant is in range }
  13409. case taicpu(p).opsize of
  13410. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13411. begin
  13412. NewSize := S_B;
  13413. Limit := $FF;
  13414. end;
  13415. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13416. begin
  13417. NewSize := S_W;
  13418. Limit := $FFFF;
  13419. end;
  13420. {$ifdef x86_64}
  13421. S_LQ:
  13422. begin
  13423. NewSize := S_L;
  13424. Limit := $FFFFFFFF;
  13425. end;
  13426. {$endif x86_64}
  13427. else
  13428. InternalError(2021120303);
  13429. end;
  13430. if (
  13431. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13432. { Check for negative operands }
  13433. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13434. ) and
  13435. GetNextInstruction(hp2,hp3) and
  13436. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13437. (taicpu(hp3).condition in [C_E,C_NE]) then
  13438. begin
  13439. TransferUsedRegs(TmpUsedRegs);
  13440. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13441. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13442. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13443. begin
  13444. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13445. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13446. taicpu(hp1).opcode := A_TEST;
  13447. taicpu(hp1).opsize := NewSize;
  13448. RemoveInstruction(hp2);
  13449. RemoveCurrentP(p, hp1);
  13450. Result:=true;
  13451. exit;
  13452. end;
  13453. end;
  13454. end;
  13455. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13456. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13457. (taicpu(hp1).opsize=S_B)) or
  13458. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13459. (taicpu(hp1).opsize=S_W))
  13460. {$ifdef x86_64}
  13461. or ((taicpu(p).opsize=S_LQ) and
  13462. (taicpu(hp1).opsize=S_L))
  13463. {$endif x86_64}
  13464. ) and
  13465. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13466. begin
  13467. { change
  13468. movx %reg1,%reg2
  13469. op %reg2,%reg3
  13470. dealloc %reg2
  13471. into
  13472. op %reg1,%reg3
  13473. if the second op accesses only the bits stored in reg1
  13474. }
  13475. TransferUsedRegs(TmpUsedRegs);
  13476. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13477. if AndTest then
  13478. begin
  13479. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13480. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13481. end
  13482. else
  13483. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13484. if not RegUsed then
  13485. begin
  13486. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13487. if taicpu(p).oper[0]^.typ=top_reg then
  13488. begin
  13489. case taicpu(hp1).opsize of
  13490. S_B:
  13491. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13492. S_W:
  13493. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13494. S_L:
  13495. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13496. else
  13497. Internalerror(2020102301);
  13498. end;
  13499. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13500. end
  13501. else
  13502. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13503. RemoveCurrentP(p);
  13504. if AndTest then
  13505. RemoveInstruction(hp2);
  13506. result:=true;
  13507. exit;
  13508. end;
  13509. end
  13510. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13511. (
  13512. { Bitwise operations only }
  13513. (taicpu(hp1).opcode=A_AND) or
  13514. (taicpu(hp1).opcode=A_TEST) or
  13515. (
  13516. (taicpu(hp1).oper[0]^.typ = top_const) and
  13517. (
  13518. (taicpu(hp1).opcode=A_OR) or
  13519. (taicpu(hp1).opcode=A_XOR)
  13520. )
  13521. )
  13522. ) and
  13523. (
  13524. (taicpu(hp1).oper[0]^.typ = top_const) or
  13525. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13526. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13527. ) then
  13528. begin
  13529. { change
  13530. movx %reg2,%reg2
  13531. op const,%reg2
  13532. into
  13533. op const,%reg2 (smaller version)
  13534. movx %reg2,%reg2
  13535. also change
  13536. movx %reg1,%reg2
  13537. and/test (oper),%reg2
  13538. dealloc %reg2
  13539. into
  13540. and/test (oper),%reg1
  13541. }
  13542. case taicpu(p).opsize of
  13543. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13544. begin
  13545. NewSize := S_B;
  13546. NewRegSize := R_SUBL;
  13547. Limit := $FF;
  13548. end;
  13549. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13550. begin
  13551. NewSize := S_W;
  13552. NewRegSize := R_SUBW;
  13553. Limit := $FFFF;
  13554. end;
  13555. {$ifdef x86_64}
  13556. S_LQ:
  13557. begin
  13558. NewSize := S_L;
  13559. NewRegSize := R_SUBD;
  13560. Limit := $FFFFFFFF;
  13561. end;
  13562. {$endif x86_64}
  13563. else
  13564. Internalerror(2021120302);
  13565. end;
  13566. TransferUsedRegs(TmpUsedRegs);
  13567. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13568. if AndTest then
  13569. begin
  13570. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13571. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13572. end
  13573. else
  13574. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13575. if
  13576. (
  13577. (taicpu(p).opcode = A_MOVZX) and
  13578. (
  13579. (taicpu(hp1).opcode=A_AND) or
  13580. (taicpu(hp1).opcode=A_TEST)
  13581. ) and
  13582. not (
  13583. { If both are references, then the final instruction will have
  13584. both operands as references, which is not allowed }
  13585. (taicpu(p).oper[0]^.typ = top_ref) and
  13586. (taicpu(hp1).oper[0]^.typ = top_ref)
  13587. ) and
  13588. not RegUsed
  13589. ) or
  13590. (
  13591. (
  13592. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13593. not RegUsed
  13594. ) and
  13595. (taicpu(p).oper[0]^.typ = top_reg) and
  13596. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13597. (taicpu(hp1).oper[0]^.typ = top_const) and
  13598. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13599. ) then
  13600. begin
  13601. {$if defined(i386) or defined(i8086)}
  13602. { If the target size is 8-bit, make sure we can actually encode it }
  13603. 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
  13604. Exit;
  13605. {$endif i386 or i8086}
  13606. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13607. taicpu(hp1).opsize := NewSize;
  13608. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13609. if AndTest then
  13610. begin
  13611. RemoveInstruction(hp2);
  13612. if not RegUsed then
  13613. begin
  13614. taicpu(hp1).opcode := A_TEST;
  13615. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13616. begin
  13617. { Make sure the reference is the second operand }
  13618. SwapOper := taicpu(hp1).oper[0];
  13619. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13620. taicpu(hp1).oper[1] := SwapOper;
  13621. end;
  13622. end;
  13623. end;
  13624. case taicpu(hp1).oper[0]^.typ of
  13625. top_reg:
  13626. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13627. top_const:
  13628. { For the AND/TEST case }
  13629. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13630. else
  13631. ;
  13632. end;
  13633. if RegUsed then
  13634. begin
  13635. AsmL.Remove(p);
  13636. AsmL.InsertAfter(p, hp1);
  13637. p := hp1;
  13638. end
  13639. else
  13640. RemoveCurrentP(p, hp1);
  13641. result:=true;
  13642. exit;
  13643. end;
  13644. end;
  13645. end;
  13646. if reg_and_hp1_is_instr and
  13647. (taicpu(p).oper[0]^.typ = top_reg) and
  13648. (
  13649. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13650. ) and
  13651. (taicpu(hp1).oper[0]^.typ = top_const) and
  13652. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13653. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13654. { Minimum shift value allowed is the bit difference between the sizes }
  13655. (taicpu(hp1).oper[0]^.val >=
  13656. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13657. 8 * (
  13658. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13659. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13660. )
  13661. ) then
  13662. begin
  13663. { For:
  13664. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13665. shl/sal ##, %reg1
  13666. Remove the movsx/movzx instruction if the shift overwrites the
  13667. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13668. }
  13669. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13670. RemoveCurrentP(p, hp1);
  13671. Result := True;
  13672. Exit;
  13673. end
  13674. else if reg_and_hp1_is_instr and
  13675. (taicpu(p).oper[0]^.typ = top_reg) and
  13676. (
  13677. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13678. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13679. ) and
  13680. (taicpu(hp1).oper[0]^.typ = top_const) and
  13681. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13682. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13683. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13684. (taicpu(hp1).oper[0]^.val <
  13685. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13686. 8 * (
  13687. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13688. )
  13689. ) then
  13690. begin
  13691. { For:
  13692. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13693. sar ##, %reg1 shr ##, %reg1
  13694. Move the shift to before the movx instruction if the shift value
  13695. is not too large.
  13696. }
  13697. asml.Remove(hp1);
  13698. asml.InsertBefore(hp1, p);
  13699. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13700. case taicpu(p).opsize of
  13701. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13702. taicpu(hp1).opsize := S_B;
  13703. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13704. taicpu(hp1).opsize := S_W;
  13705. {$ifdef x86_64}
  13706. S_LQ:
  13707. taicpu(hp1).opsize := S_L;
  13708. {$endif}
  13709. else
  13710. InternalError(2020112401);
  13711. end;
  13712. if (taicpu(hp1).opcode = A_SHR) then
  13713. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13714. else
  13715. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13716. Result := True;
  13717. end;
  13718. if reg_and_hp1_is_instr and
  13719. (taicpu(p).oper[0]^.typ = top_reg) and
  13720. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13721. (
  13722. (taicpu(hp1).opcode = taicpu(p).opcode)
  13723. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13724. {$ifdef x86_64}
  13725. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13726. {$endif x86_64}
  13727. ) then
  13728. begin
  13729. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13730. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13731. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13732. begin
  13733. {
  13734. For example:
  13735. movzbw %al,%ax
  13736. movzwl %ax,%eax
  13737. Compress into:
  13738. movzbl %al,%eax
  13739. }
  13740. RegUsed := False;
  13741. case taicpu(p).opsize of
  13742. S_BW:
  13743. case taicpu(hp1).opsize of
  13744. S_WL:
  13745. begin
  13746. taicpu(p).opsize := S_BL;
  13747. RegUsed := True;
  13748. end;
  13749. {$ifdef x86_64}
  13750. S_WQ:
  13751. begin
  13752. if taicpu(p).opcode = A_MOVZX then
  13753. begin
  13754. taicpu(p).opsize := S_BL;
  13755. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13756. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13757. end
  13758. else
  13759. taicpu(p).opsize := S_BQ;
  13760. RegUsed := True;
  13761. end;
  13762. {$endif x86_64}
  13763. else
  13764. ;
  13765. end;
  13766. {$ifdef x86_64}
  13767. S_BL:
  13768. case taicpu(hp1).opsize of
  13769. S_LQ:
  13770. begin
  13771. if taicpu(p).opcode = A_MOVZX then
  13772. begin
  13773. taicpu(p).opsize := S_BL;
  13774. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13775. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13776. end
  13777. else
  13778. taicpu(p).opsize := S_BQ;
  13779. RegUsed := True;
  13780. end;
  13781. else
  13782. ;
  13783. end;
  13784. S_WL:
  13785. case taicpu(hp1).opsize of
  13786. S_LQ:
  13787. begin
  13788. if taicpu(p).opcode = A_MOVZX then
  13789. begin
  13790. taicpu(p).opsize := S_WL;
  13791. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13792. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13793. end
  13794. else
  13795. taicpu(p).opsize := S_WQ;
  13796. RegUsed := True;
  13797. end;
  13798. else
  13799. ;
  13800. end;
  13801. {$endif x86_64}
  13802. else
  13803. ;
  13804. end;
  13805. if RegUsed then
  13806. begin
  13807. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13808. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13809. RemoveInstruction(hp1);
  13810. Result := True;
  13811. Exit;
  13812. end;
  13813. end;
  13814. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13815. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13816. GetNextInstruction(hp1, hp2) and
  13817. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13818. (
  13819. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13820. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13821. {$ifdef x86_64}
  13822. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13823. {$endif x86_64}
  13824. ) and
  13825. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13826. (
  13827. (
  13828. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13829. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13830. ) or
  13831. (
  13832. { Only allow the operands in reverse order for TEST instructions }
  13833. (taicpu(hp2).opcode = A_TEST) and
  13834. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13835. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13836. )
  13837. ) then
  13838. begin
  13839. {
  13840. For example:
  13841. movzbl %al,%eax
  13842. movzbl (ref),%edx
  13843. andl %edx,%eax
  13844. (%edx deallocated)
  13845. Change to:
  13846. andb (ref),%al
  13847. movzbl %al,%eax
  13848. Rules are:
  13849. - First two instructions have the same opcode and opsize
  13850. - First instruction's operands are the same super-register
  13851. - Second instruction operates on a different register
  13852. - Third instruction is AND, OR, XOR or TEST
  13853. - Third instruction's operands are the destination registers of the first two instructions
  13854. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13855. - Second instruction's destination register is deallocated afterwards
  13856. }
  13857. TransferUsedRegs(TmpUsedRegs);
  13858. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13859. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13860. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13861. begin
  13862. case taicpu(p).opsize of
  13863. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13864. NewSize := S_B;
  13865. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13866. NewSize := S_W;
  13867. {$ifdef x86_64}
  13868. S_LQ:
  13869. NewSize := S_L;
  13870. {$endif x86_64}
  13871. else
  13872. InternalError(2021120301);
  13873. end;
  13874. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13875. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13876. taicpu(hp2).opsize := NewSize;
  13877. RemoveInstruction(hp1);
  13878. { With TEST, it's best to keep the MOVX instruction at the top }
  13879. if (taicpu(hp2).opcode <> A_TEST) then
  13880. begin
  13881. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13882. asml.Remove(p);
  13883. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13884. asml.InsertAfter(p, hp2);
  13885. p := hp2;
  13886. end
  13887. else
  13888. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13889. Result := True;
  13890. Exit;
  13891. end;
  13892. end;
  13893. end;
  13894. if taicpu(p).opcode=A_MOVZX then
  13895. begin
  13896. { removes superfluous And's after movzx's }
  13897. if reg_and_hp1_is_instr and
  13898. (taicpu(hp1).opcode = A_AND) and
  13899. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13900. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13901. {$ifdef x86_64}
  13902. { check for implicit extension to 64 bit }
  13903. or
  13904. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13905. (taicpu(hp1).opsize=S_Q) and
  13906. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13907. )
  13908. {$endif x86_64}
  13909. )
  13910. then
  13911. begin
  13912. case taicpu(p).opsize Of
  13913. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13914. if (taicpu(hp1).oper[0]^.val = $ff) then
  13915. begin
  13916. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13917. RemoveInstruction(hp1);
  13918. Result:=true;
  13919. exit;
  13920. end;
  13921. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13922. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13923. begin
  13924. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13925. RemoveInstruction(hp1);
  13926. Result:=true;
  13927. exit;
  13928. end;
  13929. {$ifdef x86_64}
  13930. S_LQ:
  13931. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13932. begin
  13933. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13934. RemoveInstruction(hp1);
  13935. Result:=true;
  13936. exit;
  13937. end;
  13938. {$endif x86_64}
  13939. else
  13940. ;
  13941. end;
  13942. { we cannot get rid of the and, but can we get rid of the movz ?}
  13943. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13944. begin
  13945. case taicpu(p).opsize Of
  13946. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13947. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13948. begin
  13949. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13950. RemoveCurrentP(p,hp1);
  13951. Result:=true;
  13952. exit;
  13953. end;
  13954. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13955. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13956. begin
  13957. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13958. RemoveCurrentP(p,hp1);
  13959. Result:=true;
  13960. exit;
  13961. end;
  13962. {$ifdef x86_64}
  13963. S_LQ:
  13964. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13965. begin
  13966. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13967. RemoveCurrentP(p,hp1);
  13968. Result:=true;
  13969. exit;
  13970. end;
  13971. {$endif x86_64}
  13972. else
  13973. ;
  13974. end;
  13975. end;
  13976. end;
  13977. { changes some movzx constructs to faster synonyms (all examples
  13978. are given with eax/ax, but are also valid for other registers)}
  13979. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13980. begin
  13981. case taicpu(p).opsize of
  13982. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13983. (the machine code is equivalent to movzbl %al,%eax), but the
  13984. code generator still generates that assembler instruction and
  13985. it is silently converted. This should probably be checked.
  13986. [Kit] }
  13987. S_BW:
  13988. begin
  13989. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13990. (
  13991. not IsMOVZXAcceptable
  13992. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13993. or (
  13994. (cs_opt_size in current_settings.optimizerswitches) and
  13995. (taicpu(p).oper[1]^.reg = NR_AX)
  13996. )
  13997. ) then
  13998. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13999. begin
  14000. DebugMsg(SPeepholeOptimization + 'var7',p);
  14001. taicpu(p).opcode := A_AND;
  14002. taicpu(p).changeopsize(S_W);
  14003. taicpu(p).loadConst(0,$ff);
  14004. Result := True;
  14005. end
  14006. else if not IsMOVZXAcceptable and
  14007. GetNextInstruction(p, hp1) and
  14008. (tai(hp1).typ = ait_instruction) and
  14009. (taicpu(hp1).opcode = A_AND) and
  14010. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14011. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14012. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  14013. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  14014. begin
  14015. DebugMsg(SPeepholeOptimization + 'var8',p);
  14016. taicpu(p).opcode := A_MOV;
  14017. taicpu(p).changeopsize(S_W);
  14018. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  14019. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14020. Result := True;
  14021. end;
  14022. end;
  14023. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  14024. S_BL:
  14025. if not IsMOVZXAcceptable then
  14026. begin
  14027. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  14028. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  14029. begin
  14030. DebugMsg(SPeepholeOptimization + 'var9',p);
  14031. taicpu(p).opcode := A_AND;
  14032. taicpu(p).changeopsize(S_L);
  14033. taicpu(p).loadConst(0,$ff);
  14034. Result := True;
  14035. end
  14036. else if GetNextInstruction(p, hp1) and
  14037. (tai(hp1).typ = ait_instruction) and
  14038. (taicpu(hp1).opcode = A_AND) and
  14039. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14040. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14041. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  14042. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  14043. begin
  14044. DebugMsg(SPeepholeOptimization + 'var10',p);
  14045. taicpu(p).opcode := A_MOV;
  14046. taicpu(p).changeopsize(S_L);
  14047. { do not use R_SUBWHOLE
  14048. as movl %rdx,%eax
  14049. is invalid in assembler PM }
  14050. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14051. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14052. Result := True;
  14053. end;
  14054. end;
  14055. {$endif i8086}
  14056. S_WL:
  14057. if not IsMOVZXAcceptable then
  14058. begin
  14059. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  14060. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  14061. begin
  14062. DebugMsg(SPeepholeOptimization + 'var11',p);
  14063. taicpu(p).opcode := A_AND;
  14064. taicpu(p).changeopsize(S_L);
  14065. taicpu(p).loadConst(0,$ffff);
  14066. Result := True;
  14067. end
  14068. else if GetNextInstruction(p, hp1) and
  14069. (tai(hp1).typ = ait_instruction) and
  14070. (taicpu(hp1).opcode = A_AND) and
  14071. (taicpu(hp1).oper[0]^.typ = top_const) and
  14072. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14073. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14074. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  14075. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  14076. begin
  14077. DebugMsg(SPeepholeOptimization + 'var12',p);
  14078. taicpu(p).opcode := A_MOV;
  14079. taicpu(p).changeopsize(S_L);
  14080. { do not use R_SUBWHOLE
  14081. as movl %rdx,%eax
  14082. is invalid in assembler PM }
  14083. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14084. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  14085. Result := True;
  14086. end;
  14087. end;
  14088. else
  14089. InternalError(2017050705);
  14090. end;
  14091. end
  14092. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  14093. begin
  14094. if GetNextInstruction(p, hp1) and
  14095. (tai(hp1).typ = ait_instruction) and
  14096. (taicpu(hp1).opcode = A_AND) and
  14097. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14098. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14099. begin
  14100. case taicpu(p).opsize Of
  14101. S_BL:
  14102. if (taicpu(hp1).opsize <> S_L) or
  14103. (taicpu(hp1).oper[0]^.val > $FF) then
  14104. begin
  14105. DebugMsg(SPeepholeOptimization + 'var13',p);
  14106. taicpu(hp1).changeopsize(S_L);
  14107. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14108. Include(OptsToCheck, aoc_ForceNewIteration);
  14109. end;
  14110. S_WL:
  14111. if (taicpu(hp1).opsize <> S_L) or
  14112. (taicpu(hp1).oper[0]^.val > $FFFF) then
  14113. begin
  14114. DebugMsg(SPeepholeOptimization + 'var14',p);
  14115. taicpu(hp1).changeopsize(S_L);
  14116. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  14117. Include(OptsToCheck, aoc_ForceNewIteration);
  14118. end;
  14119. S_BW:
  14120. if (taicpu(hp1).opsize <> S_W) or
  14121. (taicpu(hp1).oper[0]^.val > $FF) then
  14122. begin
  14123. DebugMsg(SPeepholeOptimization + 'var15',p);
  14124. taicpu(hp1).changeopsize(S_W);
  14125. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  14126. Include(OptsToCheck, aoc_ForceNewIteration);
  14127. end;
  14128. else
  14129. Internalerror(2017050704)
  14130. end;
  14131. end;
  14132. end;
  14133. end;
  14134. end;
  14135. {$ifdef x86_64}
  14136. function TX86AsmOptimizer.DoZeroUpper32Opt(var mov_p: tai; var and_p: tai): Boolean;
  14137. var
  14138. hp1, old_hp1: tai;
  14139. FullSourceReg, FullTargetReg: TRegister;
  14140. begin
  14141. if (mov_p.typ<>ait_instruction) or
  14142. (taicpu(mov_p).opsize<>S_L) or
  14143. not MatchOpType(taicpu(mov_p),top_reg,top_reg) then
  14144. InternalError(2025062801);
  14145. Result:=False;
  14146. FullSourceReg:=taicpu(mov_p).oper[0]^.reg; setsubreg(FullSourceReg, R_SUBQ);
  14147. FullTargetReg:=taicpu(mov_p).oper[1]^.reg; setsubreg(FullTargetReg, R_SUBQ);
  14148. { Mark the registers in the MOV command as "used" }
  14149. IncludeRegInUsedRegs(FullSourceReg,UsedRegs);
  14150. IncludeRegInUsedRegs(FullTargetReg,UsedRegs);
  14151. { This is a little hack to get DeepMOVOpt to replace the full 64-bit
  14152. registers. The MOV instruction will be put back as it was afterwards
  14153. (unless it got removed). }
  14154. taicpu(mov_p).oper[0]^.reg:=FullSourceReg;
  14155. taicpu(mov_p).oper[1]^.reg:=FullTargetReg;
  14156. { Start after the and_p otherwise that instruction will be considered
  14157. to have modified the source register }
  14158. old_hp1:=and_p;
  14159. while GetNextInstructionUsingReg(old_hp1,hp1,FullTargetReg) and
  14160. (hp1.typ=ait_instruction) do
  14161. begin
  14162. if RegReadByInstruction(FullTargetReg,hp1) and
  14163. not RegModifiedBetween(FullSourceReg,old_hp1,hp1) and
  14164. DeepMOVOpt(taicpu(mov_p),taicpu(hp1)) then
  14165. begin
  14166. { A change has occurred, just not in mov_p }
  14167. Include(OptsToCheck, aoc_ForceNewIteration);
  14168. TransferUsedRegs(TmpUsedRegs);
  14169. UpdateUsedRegsBetween(TmpUsedRegs,tai(mov_p.Next), hp1);
  14170. if not RegUsedAfterInstruction(FullTargetReg,hp1,TmpUsedRegs) and
  14171. { Just in case something didn't get modified (e.g. an
  14172. implicit register) }
  14173. not RegReadByInstruction(FullTargetReg,hp1) then
  14174. begin
  14175. { We can remove the original MOV }
  14176. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3d done',mov_p);
  14177. RemoveCurrentP(mov_p);
  14178. Result := True;
  14179. Exit;
  14180. end;
  14181. end
  14182. else
  14183. Break;
  14184. old_hp1:=hp1;
  14185. end;
  14186. { Put the MOV instruction back as it was }
  14187. setsubreg(taicpu(mov_p).oper[0]^.reg,R_SUBD);
  14188. setsubreg(taicpu(mov_p).oper[1]^.reg,R_SUBD);
  14189. end;
  14190. {$endif x86_64}
  14191. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  14192. var
  14193. hp1, hp2 : tai;
  14194. MaskLength : Cardinal;
  14195. MaskedBits : TCgInt;
  14196. ActiveReg : TRegister;
  14197. begin
  14198. Result:=false;
  14199. { There are no optimisations for reference targets }
  14200. if (taicpu(p).oper[1]^.typ <> top_reg) then
  14201. Exit;
  14202. { Saves on a bunch of dereferences }
  14203. ActiveReg := taicpu(p).oper[1]^.reg;
  14204. while GetNextInstruction(p, hp1) and
  14205. (hp1.typ = ait_instruction) do
  14206. begin
  14207. if (taicpu(p).oper[0]^.typ = top_const) then
  14208. begin
  14209. case taicpu(hp1).opcode of
  14210. A_AND:
  14211. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14212. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14213. { the second register must contain the first one, so compare their subreg types }
  14214. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  14215. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  14216. { change
  14217. and const1, reg
  14218. and const2, reg
  14219. to
  14220. and (const1 and const2), reg
  14221. }
  14222. begin
  14223. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  14224. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  14225. RemoveCurrentP(p, hp1);
  14226. Result:=true;
  14227. exit;
  14228. end;
  14229. A_CMP:
  14230. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  14231. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  14232. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  14233. { Just check that the condition on the next instruction is compatible }
  14234. GetNextInstruction(hp1, hp2) and
  14235. (hp2.typ = ait_instruction) and
  14236. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  14237. then
  14238. { change
  14239. and 2^n, reg
  14240. cmp 2^n, reg
  14241. j(c) / set(c) / cmov(c) (c is equal or not equal)
  14242. to
  14243. and 2^n, reg
  14244. test reg, reg
  14245. j(~c) / set(~c) / cmov(~c)
  14246. }
  14247. begin
  14248. { Keep TEST instruction in, rather than remove it, because
  14249. it may trigger other optimisations such as MovAndTest2Test }
  14250. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  14251. taicpu(hp1).opcode := A_TEST;
  14252. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  14253. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  14254. Result := True;
  14255. Exit;
  14256. end
  14257. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  14258. MatchOpType(taicpu(hp1),top_const,top_reg) and
  14259. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  14260. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  14261. { change
  14262. and $ff/$ff/$ffff, reg
  14263. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  14264. dealloc reg
  14265. to
  14266. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  14267. }
  14268. begin
  14269. TransferUsedRegs(TmpUsedRegs);
  14270. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14271. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  14272. begin
  14273. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  14274. case taicpu(p).oper[0]^.val of
  14275. $ff:
  14276. begin
  14277. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  14278. taicpu(hp1).opsize:=S_B;
  14279. end;
  14280. $ffff:
  14281. begin
  14282. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  14283. taicpu(hp1).opsize:=S_W;
  14284. end;
  14285. $ffffffff:
  14286. begin
  14287. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  14288. taicpu(hp1).opsize:=S_L;
  14289. end;
  14290. else
  14291. Internalerror(2023030401);
  14292. end;
  14293. RemoveCurrentP(p);
  14294. Result := True;
  14295. Exit;
  14296. end;
  14297. end;
  14298. A_MOVZX:
  14299. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  14300. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  14301. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  14302. (
  14303. (
  14304. (taicpu(p).opsize=S_W) and
  14305. (taicpu(hp1).opsize=S_BW)
  14306. ) or
  14307. (
  14308. (taicpu(p).opsize=S_L) and
  14309. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  14310. )
  14311. {$ifdef x86_64}
  14312. or
  14313. (
  14314. (taicpu(p).opsize=S_Q) and
  14315. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  14316. )
  14317. {$endif x86_64}
  14318. ) then
  14319. begin
  14320. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14321. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  14322. ) or
  14323. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14324. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  14325. then
  14326. begin
  14327. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  14328. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  14329. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  14330. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  14331. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  14332. }
  14333. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  14334. RemoveInstruction(hp1);
  14335. { See if there are other optimisations possible }
  14336. Continue;
  14337. end;
  14338. end;
  14339. A_SHL:
  14340. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14341. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  14342. begin
  14343. {$ifopt R+}
  14344. {$define RANGE_WAS_ON}
  14345. {$R-}
  14346. {$endif}
  14347. { get length of potential and mask }
  14348. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  14349. { really a mask? }
  14350. {$ifdef RANGE_WAS_ON}
  14351. {$R+}
  14352. {$endif}
  14353. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  14354. { unmasked part shifted out? }
  14355. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  14356. begin
  14357. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  14358. RemoveCurrentP(p, hp1);
  14359. Result:=true;
  14360. exit;
  14361. end;
  14362. end;
  14363. A_SHR:
  14364. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  14365. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  14366. (taicpu(hp1).oper[0]^.val <= 63) then
  14367. begin
  14368. { Does SHR combined with the AND cover all the bits?
  14369. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  14370. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  14371. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  14372. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  14373. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  14374. begin
  14375. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  14376. RemoveCurrentP(p, hp1);
  14377. Result := True;
  14378. Exit;
  14379. end;
  14380. end;
  14381. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14382. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14383. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14384. begin
  14385. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14386. (
  14387. (
  14388. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14389. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14390. ) or (
  14391. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14392. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14393. {$ifdef x86_64}
  14394. ) or (
  14395. (taicpu(hp1).opsize = S_LQ) and
  14396. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14397. {$endif x86_64}
  14398. )
  14399. ) then
  14400. begin
  14401. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14402. begin
  14403. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14404. RemoveInstruction(hp1);
  14405. { See if there are other optimisations possible }
  14406. Continue;
  14407. end;
  14408. { The super-registers are the same though.
  14409. Note that this change by itself doesn't improve
  14410. code speed, but it opens up other optimisations. }
  14411. {$ifdef x86_64}
  14412. { Convert 64-bit register to 32-bit }
  14413. case taicpu(hp1).opsize of
  14414. S_BQ:
  14415. begin
  14416. taicpu(hp1).opsize := S_BL;
  14417. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14418. end;
  14419. S_WQ:
  14420. begin
  14421. taicpu(hp1).opsize := S_WL;
  14422. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14423. end
  14424. else
  14425. ;
  14426. end;
  14427. {$endif x86_64}
  14428. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14429. taicpu(hp1).opcode := A_MOVZX;
  14430. { See if there are other optimisations possible }
  14431. Continue;
  14432. end;
  14433. end;
  14434. else
  14435. ;
  14436. end;
  14437. end
  14438. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14439. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14440. begin
  14441. {$ifdef x86_64}
  14442. if (taicpu(p).opsize = S_Q) then
  14443. begin
  14444. { Never necessary }
  14445. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14446. RemoveCurrentP(p, hp1);
  14447. Result := True;
  14448. Exit;
  14449. end;
  14450. {$endif x86_64}
  14451. { Forward check to determine necessity of and %reg,%reg }
  14452. TransferUsedRegs(TmpUsedRegs);
  14453. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14454. case taicpu(hp1).opcode of
  14455. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14456. if (
  14457. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14458. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14459. ) and
  14460. (
  14461. (taicpu(hp1).opcode <> A_MOV) or
  14462. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14463. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14464. ) and
  14465. not (
  14466. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14467. (taicpu(hp1).opcode = A_MOV) and
  14468. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14469. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14470. ) and
  14471. (
  14472. (
  14473. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14474. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14475. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14476. ) or
  14477. (
  14478. {$ifdef x86_64}
  14479. (
  14480. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14481. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14482. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14483. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14484. ) and
  14485. {$endif x86_64}
  14486. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14487. )
  14488. ) then
  14489. begin
  14490. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14491. RemoveCurrentP(p, hp1);
  14492. Result := True;
  14493. Exit;
  14494. end;
  14495. A_ADD,
  14496. A_AND,
  14497. A_BSF,
  14498. A_BSR,
  14499. A_BTC,
  14500. A_BTR,
  14501. A_BTS,
  14502. A_OR,
  14503. A_SUB,
  14504. A_XOR:
  14505. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14506. if (
  14507. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14508. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14509. ) and
  14510. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14511. begin
  14512. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14513. RemoveCurrentP(p, hp1);
  14514. Result := True;
  14515. Exit;
  14516. end;
  14517. A_CMP,
  14518. A_TEST:
  14519. if (
  14520. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14521. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14522. ) and
  14523. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14524. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14525. begin
  14526. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14527. RemoveCurrentP(p, hp1);
  14528. Result := True;
  14529. Exit;
  14530. end;
  14531. A_BSWAP,
  14532. A_NEG,
  14533. A_NOT:
  14534. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14535. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14536. begin
  14537. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14538. RemoveCurrentP(p, hp1);
  14539. Result := True;
  14540. Exit;
  14541. end;
  14542. else
  14543. ;
  14544. end;
  14545. end;
  14546. if (taicpu(hp1).is_jmp) and
  14547. (taicpu(hp1).opcode<>A_JMP) and
  14548. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14549. begin
  14550. { change
  14551. and x, reg
  14552. jxx
  14553. to
  14554. test x, reg
  14555. jxx
  14556. if reg is deallocated before the
  14557. jump, but only if it's a conditional jump (PFV)
  14558. }
  14559. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14560. taicpu(p).opcode := A_TEST;
  14561. Exit;
  14562. end;
  14563. Break;
  14564. end;
  14565. { Lone AND tests }
  14566. if (taicpu(p).oper[0]^.typ = top_const) then
  14567. begin
  14568. {
  14569. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14570. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14571. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14572. }
  14573. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14574. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14575. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14576. begin
  14577. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14578. if taicpu(p).opsize = S_L then
  14579. begin
  14580. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14581. Result := True;
  14582. end;
  14583. end;
  14584. end;
  14585. { Backward check to determine necessity of and %reg,%reg }
  14586. if (taicpu(p).oper[0]^.typ = top_reg) and
  14587. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14588. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14589. begin
  14590. hp2:=p;
  14591. while GetLastInstruction(hp2, hp2) and
  14592. (cs_opt_level3 in current_settings.optimizerswitches) and
  14593. (hp2.typ=ait_instruction) and
  14594. not RegModifiedByInstruction(ActiveReg,hp2) do { loop };
  14595. if Assigned(hp2) and
  14596. RegModifiedByInstruction(ActiveReg,hp2) and { Also checks if hp2 is an instruction }
  14597. { Check size of instruction to determine if the AND is effectively
  14598. a null operation }
  14599. (
  14600. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14601. { Note: Don't include S_Q }
  14602. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14603. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14604. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14605. ) then
  14606. begin
  14607. { AND %reg,%reg is unnecessary to zero the upper 32 bits. }
  14608. DebugMsg(SPeepholeOptimization + 'AND %reg,%reg proven unnecessary after backward search (And2Nop)', p);
  14609. RemoveCurrentP(p, hp1);
  14610. Result:=True;
  14611. Exit;
  14612. end;
  14613. end;
  14614. end;
  14615. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14616. var
  14617. hp1, hp2: tai;
  14618. NewRef: TReference;
  14619. Distance: Cardinal;
  14620. TempTracking: TAllUsedRegs;
  14621. DoAddMov2Lea: Boolean;
  14622. { This entire nested function is used in an if-statement below, but we
  14623. want to avoid all the used reg transfers and GetNextInstruction calls
  14624. until we really have to check }
  14625. function MemRegisterNotUsedLater: Boolean; inline;
  14626. var
  14627. hp2: tai;
  14628. begin
  14629. TransferUsedRegs(TmpUsedRegs);
  14630. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14631. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14632. else
  14633. { p and hp1 will be adjacent }
  14634. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14635. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14636. end;
  14637. begin
  14638. Result := False;
  14639. DoAddMov2Lea:=false;
  14640. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14641. (taicpu(p).oper[1]^.typ = top_reg) then
  14642. begin
  14643. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14644. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14645. (hp1.typ <> ait_instruction) or
  14646. not
  14647. (
  14648. (cs_opt_level3 in current_settings.optimizerswitches) or
  14649. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14650. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14651. ) then
  14652. Exit;
  14653. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14654. addq $x, %rax
  14655. movq %rax, %rdx
  14656. sarq $63, %rdx
  14657. (%rax still in use)
  14658. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14659. leaq $x(%rax),%rdx
  14660. addq $x, %rax
  14661. sarq $63, %rdx
  14662. ...which is okay since it breaks the dependency chain between
  14663. addq and movq, but if OptPass2MOV is called first:
  14664. addq $x, %rax
  14665. cqto
  14666. ...which is better in all ways, taking only 2 cycles to execute
  14667. and much smaller in code size.
  14668. }
  14669. { The extra register tracking is quite strenuous }
  14670. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14671. MatchInstruction(hp1, A_MOV, []) then
  14672. begin
  14673. { Update the register tracking to the MOV instruction }
  14674. CopyUsedRegs(TempTracking);
  14675. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14676. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14677. else
  14678. { p and hp1 will be adjacent }
  14679. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14680. hp2 := hp1;
  14681. if OptPass2MOV(hp1) then
  14682. Include(OptsToCheck, aoc_ForceNewIteration);
  14683. { Reset the tracking to the current instruction }
  14684. RestoreUsedRegs(TempTracking);
  14685. ReleaseUsedRegs(TempTracking);
  14686. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14687. OptPass2ADD get called again }
  14688. if (hp1 <> hp2) then
  14689. begin
  14690. Result := True;
  14691. Exit;
  14692. end;
  14693. end;
  14694. { Change:
  14695. add %reg2,%reg1
  14696. (%reg2 not modified in between)
  14697. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14698. To:
  14699. mov/s/z #(%reg1,%reg2),%reg1
  14700. }
  14701. if (taicpu(p).oper[0]^.typ = top_reg) and
  14702. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14703. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14704. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14705. (
  14706. (
  14707. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14708. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14709. { r/esp cannot be an index }
  14710. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14711. ) or (
  14712. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14713. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14714. )
  14715. ) and (
  14716. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14717. (
  14718. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14719. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14720. MemRegisterNotUsedLater
  14721. )
  14722. ) then
  14723. begin
  14724. if (
  14725. { Instructions are guaranteed to be adjacent on -O2 and under }
  14726. (cs_opt_level3 in current_settings.optimizerswitches) and
  14727. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14728. ) then
  14729. begin
  14730. { If the other register is used in between, move the MOV
  14731. instruction to right after the ADD instruction so a
  14732. saving can still be made }
  14733. Asml.Remove(hp1);
  14734. Asml.InsertAfter(hp1, p);
  14735. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14736. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14737. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14738. RemoveCurrentp(p, hp1);
  14739. end
  14740. else
  14741. begin
  14742. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14743. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14744. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14745. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14746. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14747. { hp1 may not be the immediate next instruction under -O3 }
  14748. RemoveCurrentp(p)
  14749. else
  14750. RemoveCurrentp(p, hp1);
  14751. end;
  14752. Result := True;
  14753. Exit;
  14754. end;
  14755. { Change:
  14756. addl/q $x,%reg1
  14757. movl/q %reg1,%reg2
  14758. To:
  14759. leal/q $x(%reg1),%reg2
  14760. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14761. Breaks the dependency chain.
  14762. }
  14763. if (taicpu(p).oper[0]^.typ = top_const) and
  14764. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14765. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14766. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14767. (
  14768. { Instructions are guaranteed to be adjacent on -O2 and under }
  14769. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14770. (
  14771. { If the flags are used, don't make the optimisation,
  14772. otherwise they will be scrambled. Fixes #41148 }
  14773. (
  14774. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14775. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14776. ) and
  14777. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14778. )
  14779. ) then
  14780. begin
  14781. TransferUsedRegs(TmpUsedRegs);
  14782. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14783. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14784. else
  14785. { p and hp1 will be adjacent }
  14786. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14787. if (
  14788. SetAndTest(
  14789. (
  14790. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14791. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14792. ),
  14793. DoAddMov2Lea
  14794. ) or
  14795. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14796. not (cs_opt_size in current_settings.optimizerswitches)
  14797. ) then
  14798. begin
  14799. { Change the MOV instruction to a LEA instruction, and update the
  14800. first operand }
  14801. reference_reset(NewRef, 1, []);
  14802. NewRef.base := taicpu(p).oper[1]^.reg;
  14803. NewRef.scalefactor := 1;
  14804. { if the destination reg is the same as the ADD register,
  14805. and we keep the ADD instruction, do not add the offset
  14806. to LEA instruction, otherwise the reg gets increased by 2 times the offset value }
  14807. if DoAddMov2Lea or not MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^.reg) then
  14808. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14809. taicpu(hp1).opcode := A_LEA;
  14810. taicpu(hp1).loadref(0, NewRef);
  14811. if DoAddMov2Lea then
  14812. begin
  14813. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14814. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14815. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14816. { hp1 may not be the immediate next instruction under -O3 }
  14817. RemoveCurrentp(p)
  14818. else
  14819. RemoveCurrentp(p, hp1);
  14820. end
  14821. else
  14822. begin
  14823. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14824. { Move what is now the LEA instruction to before the ADD instruction }
  14825. Asml.Remove(hp1);
  14826. Asml.InsertBefore(hp1, p);
  14827. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14828. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14829. p := hp1;
  14830. end;
  14831. Result := True;
  14832. end;
  14833. end;
  14834. end;
  14835. end;
  14836. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14837. var
  14838. SubReg: TSubRegister;
  14839. hp1, hp2: tai;
  14840. CallJmp: Boolean;
  14841. begin
  14842. Result := False;
  14843. CallJmp := False;
  14844. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14845. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14846. with taicpu(p).oper[0]^.ref^ do
  14847. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14848. if (offset = 0) then
  14849. begin
  14850. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14851. begin
  14852. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14853. taicpu(p).opcode := A_ADD;
  14854. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14855. Result := True;
  14856. end
  14857. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14858. begin
  14859. if (base <> NR_NO) then
  14860. begin
  14861. if (scalefactor <= 1) then
  14862. begin
  14863. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14864. taicpu(p).opcode := A_ADD;
  14865. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14866. Result := True;
  14867. end;
  14868. end
  14869. else
  14870. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14871. if (scalefactor in [2, 4, 8]) then
  14872. begin
  14873. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14874. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14875. taicpu(p).opcode := A_SHL;
  14876. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14877. Result := True;
  14878. end;
  14879. end;
  14880. end
  14881. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14882. lot of latency, so break off the offset if %reg3 is used soon
  14883. afterwards }
  14884. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14885. { If 3-component addresses don't have additional latency, don't
  14886. perform this optimisation }
  14887. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14888. GetNextInstruction(p, hp1) and
  14889. (hp1.typ = ait_instruction) and
  14890. (
  14891. (
  14892. { Permit jumps and calls since they have a larger degree of overhead }
  14893. (
  14894. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14895. (
  14896. { ... unless the register specifies the location }
  14897. (taicpu(hp1).ops > 0) and
  14898. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14899. )
  14900. ) and
  14901. (
  14902. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14903. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14904. )
  14905. )
  14906. or
  14907. (
  14908. { Check up to two instructions ahead }
  14909. GetNextInstruction(hp1, hp2) and
  14910. (hp2.typ = ait_instruction) and
  14911. (
  14912. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14913. (
  14914. { Same as above }
  14915. (taicpu(hp2).ops > 0) and
  14916. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14917. )
  14918. ) and
  14919. (
  14920. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14921. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14922. )
  14923. )
  14924. ) then
  14925. begin
  14926. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14927. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14928. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14929. offset := 0;
  14930. if Assigned(symbol) or Assigned(relsymbol) then
  14931. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14932. else
  14933. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14934. { Inserting before the next instruction rather than after the
  14935. current instruction gives more accurate register tracking }
  14936. asml.InsertBefore(hp2, hp1);
  14937. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14938. Result := True;
  14939. end;
  14940. end;
  14941. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14942. var
  14943. hp1, hp2: tai;
  14944. NewRef: TReference;
  14945. Distance: Cardinal;
  14946. TempTracking: TAllUsedRegs;
  14947. DoSubMov2Lea: Boolean;
  14948. begin
  14949. Result := False;
  14950. DoSubMov2Lea:=false;
  14951. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14952. MatchOpType(taicpu(p),top_const,top_reg) then
  14953. begin
  14954. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14955. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14956. (hp1.typ <> ait_instruction) or
  14957. not
  14958. (
  14959. (cs_opt_level3 in current_settings.optimizerswitches) or
  14960. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14961. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14962. ) then
  14963. Exit;
  14964. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14965. subq $x, %rax
  14966. movq %rax, %rdx
  14967. sarq $63, %rdx
  14968. (%rax still in use)
  14969. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14970. leaq $-x(%rax),%rdx
  14971. movq $x, %rax
  14972. sarq $63, %rdx
  14973. ...which is okay since it breaks the dependency chain between
  14974. subq and movq, but if OptPass2MOV is called first:
  14975. subq $x, %rax
  14976. cqto
  14977. ...which is better in all ways, taking only 2 cycles to execute
  14978. and much smaller in code size.
  14979. }
  14980. { The extra register tracking is quite strenuous }
  14981. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14982. MatchInstruction(hp1, A_MOV, []) then
  14983. begin
  14984. { Update the register tracking to the MOV instruction }
  14985. CopyUsedRegs(TempTracking);
  14986. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14987. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14988. else
  14989. { p and hp1 will be adjacent }
  14990. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14991. hp2 := hp1;
  14992. if OptPass2MOV(hp1) then
  14993. Include(OptsToCheck, aoc_ForceNewIteration);
  14994. { Reset the tracking to the current instruction }
  14995. RestoreUsedRegs(TempTracking);
  14996. ReleaseUsedRegs(TempTracking);
  14997. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14998. OptPass2SUB get called again }
  14999. if (hp1 <> hp2) then
  15000. begin
  15001. Result := True;
  15002. Exit;
  15003. end;
  15004. end;
  15005. { Change:
  15006. subl/q $x,%reg1
  15007. movl/q %reg1,%reg2
  15008. To:
  15009. leal/q $-x(%reg1),%reg2
  15010. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  15011. Breaks the dependency chain and potentially permits the removal of
  15012. a CMP instruction if one follows.
  15013. }
  15014. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  15015. (taicpu(hp1).oper[1]^.typ = top_reg) and
  15016. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  15017. (
  15018. { Instructions are guaranteed to be adjacent on -O2 and under }
  15019. not (cs_opt_level3 in current_settings.optimizerswitches) or
  15020. (
  15021. { If the flags are used, don't make the optimisation,
  15022. otherwise they will be scrambled. Fixes #41148 }
  15023. (
  15024. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  15025. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  15026. ) and
  15027. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  15028. )
  15029. ) then
  15030. begin
  15031. TransferUsedRegs(TmpUsedRegs);
  15032. if (cs_opt_level3 in current_settings.optimizerswitches) then
  15033. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  15034. else
  15035. { p and hp1 will be adjacent }
  15036. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15037. if (
  15038. SetAndTest(
  15039. (
  15040. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  15041. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  15042. ),
  15043. DoSubMov2Lea
  15044. ) or
  15045. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  15046. not (cs_opt_size in current_settings.optimizerswitches)
  15047. ) then
  15048. begin
  15049. { Change the MOV instruction to a LEA instruction, and update the
  15050. first operand }
  15051. reference_reset(NewRef, 1, []);
  15052. NewRef.base := taicpu(p).oper[1]^.reg;
  15053. NewRef.scalefactor := 1;
  15054. { if the destination reg is the same as the SUB register,
  15055. and we keep the ADD instruction, do not substract the offset
  15056. to LEA instruction, otherwise the reg gets decreased by 2 times the offset value }
  15057. if DoSubMov2Lea or not MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^.reg) then
  15058. NewRef.offset := -taicpu(p).oper[0]^.val;
  15059. taicpu(hp1).opcode := A_LEA;
  15060. taicpu(hp1).loadref(0, NewRef);
  15061. if DoSubMov2Lea then
  15062. begin
  15063. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  15064. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  15065. if (cs_opt_level3 in current_settings.optimizerswitches) then
  15066. { hp1 may not be the immediate next instruction under -O3 }
  15067. RemoveCurrentp(p)
  15068. else
  15069. RemoveCurrentp(p, hp1);
  15070. end
  15071. else
  15072. begin
  15073. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  15074. { Move what is now the LEA instruction to before the SUB instruction }
  15075. Asml.Remove(hp1);
  15076. Asml.InsertBefore(hp1, p);
  15077. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15078. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  15079. p := hp1;
  15080. end;
  15081. Result := True;
  15082. end;
  15083. end;
  15084. end;
  15085. end;
  15086. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  15087. begin
  15088. { we can skip all instructions not messing with the stack pointer }
  15089. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  15090. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  15091. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  15092. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  15093. ({(taicpu(hp1).ops=0) or }
  15094. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  15095. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  15096. ) and }
  15097. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  15098. )
  15099. ) do
  15100. GetNextInstruction(hp1,hp1);
  15101. Result:=assigned(hp1);
  15102. end;
  15103. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  15104. var
  15105. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  15106. begin
  15107. Result:=false;
  15108. {$ifdef x86_64}
  15109. { Change:
  15110. lea x(%reg1d,%reg2d),%reg3d
  15111. To:
  15112. lea x(%reg1q,%reg2q),%reg3d
  15113. Reduces the number of bytes of machine code
  15114. }
  15115. if (getsubreg(taicpu(p).oper[1]^.reg)=R_SUBD) and
  15116. (
  15117. (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) or
  15118. (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD)
  15119. ) then
  15120. begin
  15121. DebugMsg(SPeepholeOptimization + 'Changed 32-bit registers in reference to 64-bit (reduces instruction size)', p);
  15122. if (getsubreg(taicpu(p).oper[0]^.ref^.base)=R_SUBD) then
  15123. setsubreg(taicpu(p).oper[0]^.ref^.base,R_SUBQ);
  15124. if (getsubreg(taicpu(p).oper[0]^.ref^.index)=R_SUBD) then
  15125. setsubreg(taicpu(p).oper[0]^.ref^.index,R_SUBQ);
  15126. { No reason to set Result to true }
  15127. end;
  15128. {$endif x86_64}
  15129. hp5:=nil;
  15130. hp6:=nil;
  15131. hp7:=nil;
  15132. hp8:=nil;
  15133. { replace
  15134. leal(q) x(<stackpointer>),<stackpointer>
  15135. <optional .seh_stackalloc ...>
  15136. <optional .seh_endprologue ...>
  15137. call procname
  15138. <optional NOP>
  15139. leal(q) -x(<stackpointer>),<stackpointer>
  15140. <optional VZEROUPPER>
  15141. ret
  15142. by
  15143. jmp procname
  15144. but do it only on level 4 because it destroys stack back traces
  15145. }
  15146. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15147. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  15148. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  15149. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  15150. { the -8, -24, -40 are not required, but bail out early if possible,
  15151. higher values are unlikely }
  15152. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  15153. (taicpu(p).oper[0]^.ref^.offset=-24) or
  15154. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  15155. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  15156. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  15157. GetNextInstruction(p, hp1) and
  15158. { Take a copy of hp1 }
  15159. SetAndTest(hp1, hp4) and
  15160. { trick to skip label }
  15161. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  15162. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  15163. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  15164. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  15165. SkipSimpleInstructions(hp1) and
  15166. MatchInstruction(hp1,A_CALL,[S_NO]) and
  15167. GetNextInstruction(hp1, hp2) and
  15168. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  15169. { skip nop instruction on win64 }
  15170. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  15171. SetAndTest(hp2,hp6) and
  15172. GetNextInstruction(hp2,hp2) and
  15173. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  15174. ) and
  15175. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  15176. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  15177. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  15178. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  15179. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  15180. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  15181. { Segment register will be NR_NO }
  15182. GetNextInstruction(hp2, hp3) and
  15183. { trick to skip label }
  15184. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  15185. (MatchInstruction(hp3,A_RET,[S_NO]) or
  15186. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  15187. SetAndTest(hp3,hp5) and
  15188. GetNextInstruction(hp3,hp3) and
  15189. MatchInstruction(hp3,A_RET,[S_NO])
  15190. )
  15191. ) and
  15192. (taicpu(hp3).ops=0) then
  15193. begin
  15194. taicpu(hp1).opcode := A_JMP;
  15195. taicpu(hp1).is_jmp := true;
  15196. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  15197. { search for the stackalloc directive and remove it }
  15198. hp7:=tai(p.next);
  15199. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  15200. begin
  15201. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  15202. begin
  15203. { sanity check }
  15204. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  15205. Internalerror(2024012201);
  15206. hp8:=tai(hp7.next);
  15207. RemoveInstruction(tai(hp7));
  15208. hp7:=hp8;
  15209. break;
  15210. end
  15211. else
  15212. hp7:=tai(hp7.next);
  15213. end;
  15214. RemoveCurrentP(p, hp4);
  15215. RemoveInstruction(hp2);
  15216. RemoveInstruction(hp3);
  15217. { if there is a vzeroupper instruction then move it before the jmp }
  15218. if Assigned(hp5) then
  15219. begin
  15220. AsmL.Remove(hp5);
  15221. ASmL.InsertBefore(hp5,hp1)
  15222. end;
  15223. { remove nop on win64 }
  15224. if Assigned(hp6) then
  15225. RemoveInstruction(hp6);
  15226. Result:=true;
  15227. end;
  15228. end;
  15229. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  15230. {$ifdef x86_64}
  15231. var
  15232. hp1, hp2, hp3, hp4, hp5: tai;
  15233. {$endif x86_64}
  15234. begin
  15235. Result:=false;
  15236. {$ifdef x86_64}
  15237. hp5:=nil;
  15238. { replace
  15239. push %rax
  15240. call procname
  15241. pop %rcx
  15242. ret
  15243. by
  15244. jmp procname
  15245. but do it only on level 4 because it destroys stack back traces
  15246. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  15247. for all supported calling conventions
  15248. }
  15249. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15250. MatchOpType(taicpu(p),top_reg) and
  15251. (taicpu(p).oper[0]^.reg=NR_RAX) and
  15252. GetNextInstruction(p, hp1) and
  15253. { Take a copy of hp1 }
  15254. SetAndTest(hp1, hp4) and
  15255. { trick to skip label }
  15256. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  15257. SkipSimpleInstructions(hp1) and
  15258. MatchInstruction(hp1,A_CALL,[S_NO]) and
  15259. GetNextInstruction(hp1, hp2) and
  15260. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  15261. MatchOpType(taicpu(hp2),top_reg) and
  15262. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  15263. GetNextInstruction(hp2, hp3) and
  15264. { trick to skip label }
  15265. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  15266. (MatchInstruction(hp3,A_RET,[S_NO]) or
  15267. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  15268. SetAndTest(hp3,hp5) and
  15269. GetNextInstruction(hp3,hp3) and
  15270. MatchInstruction(hp3,A_RET,[S_NO])
  15271. )
  15272. ) and
  15273. (taicpu(hp3).ops=0) then
  15274. begin
  15275. taicpu(hp1).opcode := A_JMP;
  15276. taicpu(hp1).is_jmp := true;
  15277. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  15278. RemoveCurrentP(p, hp4);
  15279. RemoveInstruction(hp2);
  15280. RemoveInstruction(hp3);
  15281. if Assigned(hp5) then
  15282. begin
  15283. AsmL.Remove(hp5);
  15284. ASmL.InsertBefore(hp5,hp1)
  15285. end;
  15286. Result:=true;
  15287. end;
  15288. {$endif x86_64}
  15289. end;
  15290. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  15291. var
  15292. Value, RegName: string;
  15293. hp1: tai;
  15294. begin
  15295. Result:=false;
  15296. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  15297. begin
  15298. case taicpu(p).oper[0]^.val of
  15299. 0:
  15300. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  15301. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15302. (
  15303. { See if we can still convert the instruction }
  15304. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15305. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15306. ) then
  15307. begin
  15308. { change "mov $0,%reg" into "xor %reg,%reg" }
  15309. taicpu(p).opcode := A_XOR;
  15310. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  15311. Result := True;
  15312. {$ifdef x86_64}
  15313. end
  15314. else if (taicpu(p).opsize = S_Q) then
  15315. begin
  15316. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15317. { The actual optimization }
  15318. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15319. taicpu(p).changeopsize(S_L);
  15320. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15321. Result := True;
  15322. end;
  15323. $1..$FFFFFFFF:
  15324. begin
  15325. { Code size reduction by J. Gareth "Kit" Moreton }
  15326. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  15327. case taicpu(p).opsize of
  15328. S_Q:
  15329. begin
  15330. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  15331. Value := debug_tostr(taicpu(p).oper[0]^.val);
  15332. { The actual optimization }
  15333. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15334. taicpu(p).changeopsize(S_L);
  15335. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  15336. Result := True;
  15337. end;
  15338. else
  15339. { Do nothing };
  15340. end;
  15341. {$endif x86_64}
  15342. end;
  15343. -1:
  15344. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  15345. if (cs_opt_size in current_settings.optimizerswitches) and
  15346. (taicpu(p).opsize <> S_B) and
  15347. (
  15348. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  15349. (
  15350. { See if we can still convert the instruction }
  15351. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  15352. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  15353. )
  15354. ) then
  15355. begin
  15356. { change "mov $-1,%reg" into "or $-1,%reg" }
  15357. { NOTES:
  15358. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  15359. - This operation creates a false dependency on the register, so only do it when optimising for size
  15360. - 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
  15361. }
  15362. taicpu(p).opcode := A_OR;
  15363. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  15364. Result := True;
  15365. end;
  15366. else
  15367. { Do nothing };
  15368. end;
  15369. end;
  15370. end;
  15371. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  15372. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  15373. begin
  15374. Result := False;
  15375. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  15376. Exit;
  15377. { For sizes less than S_L, the byte size is equal or larger with BTx,
  15378. so don't bother optimising }
  15379. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  15380. Exit;
  15381. if (taicpu(p).oper[0]^.typ <> top_const) or
  15382. { If the value can fit into an 8-bit signed integer, a smaller
  15383. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  15384. falls within this range }
  15385. (
  15386. (taicpu(p).oper[0]^.val > -128) and
  15387. (taicpu(p).oper[0]^.val <= 127)
  15388. ) then
  15389. Exit;
  15390. { If we're optimising for size, this is acceptable }
  15391. if (cs_opt_size in current_settings.optimizerswitches) then
  15392. Exit(True);
  15393. if (taicpu(p).oper[1]^.typ = top_reg) and
  15394. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15395. Exit(True);
  15396. if (taicpu(p).oper[1]^.typ <> top_reg) and
  15397. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  15398. Exit(True);
  15399. end;
  15400. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  15401. var
  15402. hp1: tai;
  15403. Value: TCGInt;
  15404. begin
  15405. Result := False;
  15406. if MatchOpType(taicpu(p), top_const, top_reg) then
  15407. begin
  15408. { Detect:
  15409. andw x, %ax (0 <= x < $8000)
  15410. ...
  15411. movzwl %ax,%eax
  15412. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  15413. }
  15414. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15415. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15416. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15417. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15418. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15419. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15420. begin
  15421. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15422. taicpu(hp1).opcode := A_CWDE;
  15423. taicpu(hp1).clearop(0);
  15424. taicpu(hp1).clearop(1);
  15425. taicpu(hp1).ops := 0;
  15426. { A change was made, but not with p, so don't set Result, but
  15427. notify the compiler that a change was made }
  15428. Include(OptsToCheck, aoc_ForceNewIteration);
  15429. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15430. end;
  15431. end;
  15432. { If "not x" is a power of 2 (popcnt = 1), change:
  15433. and $x, %reg/ref
  15434. To:
  15435. btr lb(x), %reg/ref
  15436. }
  15437. if IsBTXAcceptable(p) and
  15438. (
  15439. { Make sure a TEST doesn't follow that plays with the register }
  15440. not GetNextInstruction(p, hp1) or
  15441. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15442. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15443. ) then
  15444. begin
  15445. {$push}{$R-}{$Q-}
  15446. { Value is a sign-extended 32-bit integer - just correct it
  15447. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15448. checks to see if this operand is an immediate. }
  15449. Value := not taicpu(p).oper[0]^.val;
  15450. {$pop}
  15451. {$ifdef x86_64}
  15452. if taicpu(p).opsize = S_L then
  15453. {$endif x86_64}
  15454. Value := Value and $FFFFFFFF;
  15455. if (PopCnt(QWord(Value)) = 1) then
  15456. begin
  15457. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15458. taicpu(p).opcode := A_BTR;
  15459. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15460. Result := True;
  15461. Exit;
  15462. end;
  15463. end;
  15464. end;
  15465. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15466. begin
  15467. Result := False;
  15468. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15469. Exit;
  15470. { Convert:
  15471. movswl %ax,%eax -> cwtl
  15472. movslq %eax,%rax -> cdqe
  15473. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15474. refer to the same opcode and depends only on the assembler's
  15475. current operand-size attribute. [Kit]
  15476. }
  15477. with taicpu(p) do
  15478. case opsize of
  15479. S_WL:
  15480. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15481. begin
  15482. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15483. opcode := A_CWDE;
  15484. clearop(0);
  15485. clearop(1);
  15486. ops := 0;
  15487. Result := True;
  15488. end;
  15489. {$ifdef x86_64}
  15490. S_LQ:
  15491. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15492. begin
  15493. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15494. opcode := A_CDQE;
  15495. clearop(0);
  15496. clearop(1);
  15497. ops := 0;
  15498. Result := True;
  15499. end;
  15500. {$endif x86_64}
  15501. else
  15502. ;
  15503. end;
  15504. end;
  15505. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15506. var
  15507. hp1: tai;
  15508. begin
  15509. Result := False;
  15510. { All these optimisations work on "shr const,%reg" }
  15511. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15512. Exit;
  15513. if HandleSHRMerge(p, True) then
  15514. begin
  15515. Result := True;
  15516. Exit;
  15517. end;
  15518. { Detect the following (looking backwards):
  15519. shr %cl,%reg
  15520. shr x, %reg
  15521. Swap the two SHR instructions to minimise a pipeline stall.
  15522. }
  15523. if GetLastInstruction(p, hp1) and
  15524. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15525. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15526. { First operand will be %cl }
  15527. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15528. { Just to be sure }
  15529. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15530. begin
  15531. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15532. { Moving the entries this way ensures the register tracking remains correct }
  15533. Asml.Remove(p);
  15534. Asml.InsertBefore(p, hp1);
  15535. p := hp1;
  15536. { Don't set Result to True because the current instruction is now
  15537. "shr %cl,%reg" and there's nothing more we can do with it }
  15538. end;
  15539. end;
  15540. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15541. var
  15542. hp1, hp2: tai;
  15543. Opposite, SecondOpposite: TAsmOp;
  15544. NewCond: TAsmCond;
  15545. begin
  15546. Result := False;
  15547. { Change:
  15548. add/sub 128,(dest)
  15549. To:
  15550. sub/add -128,(dest)
  15551. This generaally takes fewer bytes to encode because -128 can be stored
  15552. in a signed byte, whereas +128 cannot.
  15553. }
  15554. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15555. begin
  15556. if taicpu(p).opcode = A_ADD then
  15557. Opposite := A_SUB
  15558. else
  15559. Opposite := A_ADD;
  15560. { Be careful if the flags are in use, because the CF flag inverts
  15561. when changing from ADD to SUB and vice versa }
  15562. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15563. GetNextInstruction(p, hp1) then
  15564. begin
  15565. TransferUsedRegs(TmpUsedRegs);
  15566. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15567. hp2 := hp1;
  15568. { Scan ahead to check if everything's safe }
  15569. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15570. begin
  15571. if (hp1.typ <> ait_instruction) then
  15572. { Probably unsafe since the flags are still in use }
  15573. Exit;
  15574. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15575. { Stop searching at an unconditional jump }
  15576. Break;
  15577. if not
  15578. (
  15579. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15580. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15581. ) and
  15582. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15583. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15584. Exit;
  15585. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15586. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15587. { Move to the next instruction }
  15588. GetNextInstruction(hp1, hp1);
  15589. end;
  15590. while Assigned(hp2) and (hp2 <> hp1) do
  15591. begin
  15592. NewCond := C_None;
  15593. case taicpu(hp2).condition of
  15594. C_A, C_NBE:
  15595. NewCond := C_BE;
  15596. C_B, C_C, C_NAE:
  15597. NewCond := C_AE;
  15598. C_AE, C_NB, C_NC:
  15599. NewCond := C_B;
  15600. C_BE, C_NA:
  15601. NewCond := C_A;
  15602. else
  15603. { No change needed };
  15604. end;
  15605. if NewCond <> C_None then
  15606. begin
  15607. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15608. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15609. taicpu(hp2).condition := NewCond;
  15610. end
  15611. else
  15612. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15613. begin
  15614. { Because of the flipping of the carry bit, to ensure
  15615. the operation remains equivalent, ADC becomes SBB
  15616. and vice versa, and the constant is not-inverted.
  15617. If multiple ADCs or SBBs appear in a row, each one
  15618. changed causes the carry bit to invert, so they all
  15619. need to be flipped }
  15620. if taicpu(hp2).opcode = A_ADC then
  15621. SecondOpposite := A_SBB
  15622. else
  15623. SecondOpposite := A_ADC;
  15624. if taicpu(hp2).oper[0]^.typ <> top_const then
  15625. { Should have broken out of this optimisation already }
  15626. InternalError(2021112901);
  15627. 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]^) + ' -> ' +
  15628. 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);
  15629. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15630. taicpu(hp2).opcode := SecondOpposite;
  15631. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15632. end;
  15633. { Move to the next instruction }
  15634. GetNextInstruction(hp2, hp2);
  15635. end;
  15636. if (hp2 <> hp1) then
  15637. InternalError(2021111501);
  15638. end;
  15639. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15640. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15641. taicpu(p).opcode := Opposite;
  15642. taicpu(p).oper[0]^.val := -128;
  15643. { No further optimisations can be made on this instruction, so move
  15644. onto the next one to save time }
  15645. p := tai(p.Next);
  15646. UpdateUsedRegs(p);
  15647. Result := True;
  15648. Exit;
  15649. end;
  15650. { Detect:
  15651. add/sub %reg2,(dest)
  15652. add/sub x, (dest)
  15653. (dest can be a register or a reference)
  15654. Swap the instructions to minimise a pipeline stall. This reverses the
  15655. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15656. optimisations could be made.
  15657. }
  15658. if (taicpu(p).oper[0]^.typ = top_reg) and
  15659. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15660. (
  15661. (
  15662. (taicpu(p).oper[1]^.typ = top_reg) and
  15663. { We can try searching further ahead if we're writing to a register }
  15664. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15665. ) or
  15666. (
  15667. (taicpu(p).oper[1]^.typ = top_ref) and
  15668. GetNextInstruction(p, hp1)
  15669. )
  15670. ) and
  15671. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15672. (taicpu(hp1).oper[0]^.typ = top_const) and
  15673. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15674. begin
  15675. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15676. TransferUsedRegs(TmpUsedRegs);
  15677. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15678. hp2 := p;
  15679. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15680. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15681. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15682. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15683. begin
  15684. asml.remove(hp1);
  15685. asml.InsertBefore(hp1, p);
  15686. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15687. Result := True;
  15688. end;
  15689. end;
  15690. end;
  15691. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15692. var
  15693. hp1: tai;
  15694. begin
  15695. Result:=false;
  15696. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15697. while GetNextInstruction(p, hp1) and
  15698. TrySwapMovCmp(p, hp1) do
  15699. begin
  15700. if MatchInstruction(hp1, A_MOV, []) then
  15701. begin
  15702. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15703. begin
  15704. { A little hacky, but since CMP doesn't read the flags, only
  15705. modify them, it's safe if they get scrambled by MOV -> XOR }
  15706. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15707. Result := PostPeepholeOptMov(hp1);
  15708. {$ifdef x86_64}
  15709. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15710. { Used to shrink instruction size }
  15711. PostPeepholeOptXor(hp1);
  15712. {$endif x86_64}
  15713. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15714. end
  15715. else
  15716. begin
  15717. Result := PostPeepholeOptMov(hp1);
  15718. {$ifdef x86_64}
  15719. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15720. { Used to shrink instruction size }
  15721. PostPeepholeOptXor(hp1);
  15722. {$endif x86_64}
  15723. end;
  15724. end;
  15725. { Enabling this flag is actually a null operation, but it marks
  15726. the code as 'modified' during this pass }
  15727. Include(OptsToCheck, aoc_ForceNewIteration);
  15728. end;
  15729. { change "cmp $0, %reg" to "test %reg, %reg" }
  15730. if MatchOpType(taicpu(p),top_const,top_reg) and
  15731. (taicpu(p).oper[0]^.val = 0) then
  15732. begin
  15733. taicpu(p).opcode := A_TEST;
  15734. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15735. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15736. Result:=true;
  15737. end;
  15738. end;
  15739. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15740. var
  15741. IsTestConstX, IsValid : Boolean;
  15742. hp1,hp2 : tai;
  15743. begin
  15744. Result:=false;
  15745. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15746. if (taicpu(p).opcode = A_TEST) then
  15747. while GetNextInstruction(p, hp1) and
  15748. TrySwapMovCmp(p, hp1) do
  15749. begin
  15750. if MatchInstruction(hp1, A_MOV, []) then
  15751. begin
  15752. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15753. begin
  15754. { A little hacky, but since TEST doesn't read the flags, only
  15755. modify them, it's safe if they get scrambled by MOV -> XOR }
  15756. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15757. Result := PostPeepholeOptMov(hp1);
  15758. {$ifdef x86_64}
  15759. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15760. { Used to shrink instruction size }
  15761. PostPeepholeOptXor(hp1);
  15762. {$endif x86_64}
  15763. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15764. end
  15765. else
  15766. begin
  15767. Result := PostPeepholeOptMov(hp1);
  15768. {$ifdef x86_64}
  15769. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15770. { Used to shrink instruction size }
  15771. PostPeepholeOptXor(hp1);
  15772. {$endif x86_64}
  15773. end;
  15774. end;
  15775. { Enabling this flag is actually a null operation, but it marks
  15776. the code as 'modified' during this pass }
  15777. Include(OptsToCheck, aoc_ForceNewIteration);
  15778. end;
  15779. { If x is a power of 2 (popcnt = 1), change:
  15780. or $x, %reg/ref
  15781. To:
  15782. bts lb(x), %reg/ref
  15783. }
  15784. if (taicpu(p).opcode = A_OR) and
  15785. IsBTXAcceptable(p) and
  15786. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15787. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15788. (
  15789. { Don't optimise if a test instruction follows }
  15790. not GetNextInstruction(p, hp1) or
  15791. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15792. ) then
  15793. begin
  15794. 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);
  15795. taicpu(p).opcode := A_BTS;
  15796. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15797. Result := True;
  15798. Exit;
  15799. end;
  15800. { If x is a power of 2 (popcnt = 1), change:
  15801. test $x, %reg/ref
  15802. je / sete / cmove (or jne / setne)
  15803. To:
  15804. bt lb(x), %reg/ref
  15805. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15806. }
  15807. if (taicpu(p).opcode = A_TEST) and
  15808. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15809. (taicpu(p).oper[0]^.typ = top_const) and
  15810. (
  15811. (cs_opt_size in current_settings.optimizerswitches) or
  15812. (
  15813. (taicpu(p).oper[1]^.typ = top_reg) and
  15814. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15815. ) or
  15816. (
  15817. (taicpu(p).oper[1]^.typ <> top_reg) and
  15818. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15819. )
  15820. ) and
  15821. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15822. { For sizes less than S_L, the byte size is equal or larger with BT,
  15823. so don't bother optimising }
  15824. (taicpu(p).opsize >= S_L) then
  15825. begin
  15826. IsValid := True;
  15827. { Check the next set of instructions, watching the FLAGS register
  15828. and the conditions used }
  15829. TransferUsedRegs(TmpUsedRegs);
  15830. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15831. hp1 := p;
  15832. hp2 := nil;
  15833. while GetNextInstruction(hp1, hp1) do
  15834. begin
  15835. if not Assigned(hp2) then
  15836. { The first instruction after TEST }
  15837. hp2 := hp1;
  15838. if (hp1.typ <> ait_instruction) then
  15839. begin
  15840. { If the flags are no longer in use, everything is fine }
  15841. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15842. IsValid := False;
  15843. Break;
  15844. end;
  15845. case taicpu(hp1).condition of
  15846. C_None:
  15847. begin
  15848. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15849. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15850. { Something is not quite normal, so play safe and don't change }
  15851. IsValid := False;
  15852. Break;
  15853. end;
  15854. C_E, C_Z, C_NE, C_NZ:
  15855. { This is fine };
  15856. else
  15857. begin
  15858. { Unsupported condition }
  15859. IsValid := False;
  15860. Break;
  15861. end;
  15862. end;
  15863. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15864. end;
  15865. if IsValid then
  15866. begin
  15867. while hp2 <> hp1 do
  15868. begin
  15869. case taicpu(hp2).condition of
  15870. C_Z, C_E:
  15871. taicpu(hp2).condition := C_NC;
  15872. C_NZ, C_NE:
  15873. taicpu(hp2).condition := C_C;
  15874. else
  15875. { Should not get this by this point }
  15876. InternalError(2022110701);
  15877. end;
  15878. GetNextInstruction(hp2, hp2);
  15879. end;
  15880. 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);
  15881. taicpu(p).opcode := A_BT;
  15882. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15883. Result := True;
  15884. Exit;
  15885. end;
  15886. end;
  15887. { removes the line marked with (x) from the sequence
  15888. and/or/xor/add/sub/... $x, %y
  15889. test/or %y, %y | test $-1, %y (x)
  15890. j(n)z _Label
  15891. as the first instruction already adjusts the ZF
  15892. %y operand may also be a reference }
  15893. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15894. MatchOperand(taicpu(p).oper[0]^,-1);
  15895. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15896. GetLastInstruction(p, hp1) and
  15897. (tai(hp1).typ = ait_instruction) and
  15898. GetNextInstruction(p,hp2) and
  15899. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15900. case taicpu(hp1).opcode Of
  15901. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15902. { These two instructions set the zero flag if the result is zero }
  15903. A_POPCNT, A_LZCNT:
  15904. begin
  15905. if (
  15906. { With POPCNT, an input of zero will set the zero flag
  15907. because the population count of zero is zero }
  15908. (taicpu(hp1).opcode = A_POPCNT) and
  15909. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15910. (
  15911. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15912. { Faster than going through the second half of the 'or'
  15913. condition below }
  15914. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15915. )
  15916. ) or (
  15917. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15918. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15919. { and in case of carry for A(E)/B(E)/C/NC }
  15920. (
  15921. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15922. (
  15923. (taicpu(hp1).opcode <> A_ADD) and
  15924. (taicpu(hp1).opcode <> A_SUB) and
  15925. (taicpu(hp1).opcode <> A_LZCNT)
  15926. )
  15927. )
  15928. ) then
  15929. begin
  15930. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15931. RemoveCurrentP(p, hp2);
  15932. Result:=true;
  15933. Exit;
  15934. end;
  15935. end;
  15936. A_SHL, A_SAL, A_SHR, A_SAR:
  15937. begin
  15938. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15939. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15940. { therefore, it's only safe to do this optimization for }
  15941. { shifts by a (nonzero) constant }
  15942. (taicpu(hp1).oper[0]^.typ = top_const) and
  15943. (taicpu(hp1).oper[0]^.val <> 0) and
  15944. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15945. { and in case of carry for A(E)/B(E)/C/NC }
  15946. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15947. begin
  15948. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15949. RemoveCurrentP(p, hp2);
  15950. Result:=true;
  15951. Exit;
  15952. end;
  15953. end;
  15954. A_DEC, A_INC, A_NEG:
  15955. begin
  15956. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15957. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15958. { and in case of carry for A(E)/B(E)/C/NC }
  15959. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15960. begin
  15961. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15962. RemoveCurrentP(p, hp2);
  15963. Result:=true;
  15964. Exit;
  15965. end;
  15966. end;
  15967. A_ANDN, A_BZHI:
  15968. begin
  15969. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15970. { Only the zero and sign flags are consistent with what the result is }
  15971. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15972. begin
  15973. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15974. RemoveCurrentP(p, hp2);
  15975. Result:=true;
  15976. Exit;
  15977. end;
  15978. end;
  15979. A_BEXTR:
  15980. begin
  15981. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15982. { Only the zero flag is set }
  15983. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15984. begin
  15985. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15986. RemoveCurrentP(p, hp2);
  15987. Result:=true;
  15988. Exit;
  15989. end;
  15990. end;
  15991. else
  15992. ;
  15993. end; { case }
  15994. { change "test $-1,%reg" into "test %reg,%reg" }
  15995. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15996. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15997. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15998. if MatchInstruction(p, A_OR, []) and
  15999. { Can only match if they're both registers }
  16000. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  16001. begin
  16002. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  16003. taicpu(p).opcode := A_TEST;
  16004. { No need to set Result to True, as we've done all the optimisations we can }
  16005. end;
  16006. end;
  16007. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  16008. var
  16009. hp1,hp3 : tai;
  16010. {$ifndef x86_64}
  16011. hp2 : taicpu;
  16012. {$endif x86_64}
  16013. begin
  16014. Result:=false;
  16015. hp3:=nil;
  16016. {$ifndef x86_64}
  16017. { don't do this on modern CPUs, this really hurts them due to
  16018. broken call/ret pairing }
  16019. if (current_settings.optimizecputype < cpu_Pentium2) and
  16020. not(cs_create_pic in current_settings.moduleswitches) and
  16021. GetNextInstruction(p, hp1) and
  16022. MatchInstruction(hp1,A_JMP,[S_NO]) and
  16023. MatchOpType(taicpu(hp1),top_ref) and
  16024. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  16025. begin
  16026. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  16027. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  16028. InsertLLItem(p.previous, p, hp2);
  16029. taicpu(p).opcode := A_JMP;
  16030. taicpu(p).is_jmp := true;
  16031. RemoveInstruction(hp1);
  16032. Result:=true;
  16033. end
  16034. else
  16035. {$endif x86_64}
  16036. { replace
  16037. call procname
  16038. ret
  16039. by
  16040. jmp procname
  16041. but do it only on level 4 because it destroys stack back traces
  16042. else if the subroutine is marked as no return, remove the ret
  16043. }
  16044. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  16045. (po_noreturn in current_procinfo.procdef.procoptions)) and
  16046. GetNextInstruction(p, hp1) and
  16047. (MatchInstruction(hp1,A_RET,[S_NO]) or
  16048. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  16049. SetAndTest(hp1,hp3) and
  16050. GetNextInstruction(hp1,hp1) and
  16051. MatchInstruction(hp1,A_RET,[S_NO])
  16052. )
  16053. ) and
  16054. (taicpu(hp1).ops=0) then
  16055. begin
  16056. if (cs_opt_level4 in current_settings.optimizerswitches) and
  16057. { we might destroy stack alignment here if we do not do a call }
  16058. (target_info.stackalign<=sizeof(SizeUInt)) then
  16059. begin
  16060. taicpu(p).opcode := A_JMP;
  16061. taicpu(p).is_jmp := true;
  16062. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  16063. end
  16064. else
  16065. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  16066. RemoveInstruction(hp1);
  16067. if Assigned(hp3) then
  16068. begin
  16069. AsmL.Remove(hp3);
  16070. AsmL.InsertBefore(hp3,p)
  16071. end;
  16072. Result:=true;
  16073. end;
  16074. end;
  16075. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  16076. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  16077. begin
  16078. case OpSize of
  16079. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  16080. Result := (Val <= $FF) and (Val >= -128);
  16081. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  16082. Result := (Val <= $FFFF) and (Val >= -32768);
  16083. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  16084. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  16085. else
  16086. Result := True;
  16087. end;
  16088. end;
  16089. var
  16090. hp1, hp2 : tai;
  16091. SizeChange: Boolean;
  16092. PreMessage: string;
  16093. begin
  16094. Result := False;
  16095. if (taicpu(p).oper[0]^.typ = top_reg) and
  16096. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  16097. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  16098. begin
  16099. { Change (using movzbl %al,%eax as an example):
  16100. movzbl %al, %eax movzbl %al, %eax
  16101. cmpl x, %eax testl %eax,%eax
  16102. To:
  16103. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  16104. movzbl %al, %eax movzbl %al, %eax
  16105. Smaller instruction and minimises pipeline stall as the CPU
  16106. doesn't have to wait for the register to get zero-extended. [Kit]
  16107. Also allow if the smaller of the two registers is being checked,
  16108. as this still removes the false dependency.
  16109. }
  16110. if
  16111. (
  16112. (
  16113. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  16114. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  16115. ) or (
  16116. { If MatchOperand returns True, they must both be registers }
  16117. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  16118. )
  16119. ) and
  16120. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  16121. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  16122. begin
  16123. 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);
  16124. asml.Remove(hp1);
  16125. asml.InsertBefore(hp1, p);
  16126. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  16127. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  16128. begin
  16129. taicpu(hp1).opcode := A_TEST;
  16130. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  16131. end;
  16132. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  16133. case taicpu(p).opsize of
  16134. S_BW, S_BL:
  16135. begin
  16136. SizeChange := taicpu(hp1).opsize <> S_B;
  16137. taicpu(hp1).changeopsize(S_B);
  16138. end;
  16139. S_WL:
  16140. begin
  16141. SizeChange := taicpu(hp1).opsize <> S_W;
  16142. taicpu(hp1).changeopsize(S_W);
  16143. end
  16144. else
  16145. InternalError(2020112701);
  16146. end;
  16147. UpdateUsedRegs(tai(p.Next));
  16148. { Check if the register is used aferwards - if not, we can
  16149. remove the movzx instruction completely }
  16150. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  16151. begin
  16152. { Hp1 is a better position than p for debugging purposes }
  16153. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  16154. RemoveCurrentp(p, hp1);
  16155. Result := True;
  16156. end;
  16157. if SizeChange then
  16158. DebugMsg(SPeepholeOptimization + PreMessage +
  16159. 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)
  16160. else
  16161. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  16162. Exit;
  16163. end;
  16164. { Change (using movzwl %ax,%eax as an example):
  16165. movzwl %ax, %eax
  16166. movb %al, (dest) (Register is smaller than read register in movz)
  16167. To:
  16168. movb %al, (dest) (Move one back to avoid a false dependency)
  16169. movzwl %ax, %eax
  16170. }
  16171. if (taicpu(hp1).opcode = A_MOV) and
  16172. (taicpu(hp1).oper[0]^.typ = top_reg) and
  16173. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  16174. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  16175. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  16176. begin
  16177. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  16178. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  16179. asml.Remove(hp1);
  16180. asml.InsertBefore(hp1, p);
  16181. if taicpu(hp1).oper[1]^.typ = top_reg then
  16182. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  16183. { Check if the register is used aferwards - if not, we can
  16184. remove the movzx instruction completely }
  16185. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  16186. begin
  16187. { Hp1 is a better position than p for debugging purposes }
  16188. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  16189. RemoveCurrentp(p, hp1);
  16190. Result := True;
  16191. end;
  16192. Exit;
  16193. end;
  16194. end;
  16195. end;
  16196. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  16197. var
  16198. hp1: tai;
  16199. {$ifdef x86_64}
  16200. PreMessage, RegName: string;
  16201. {$endif x86_64}
  16202. begin
  16203. Result := False;
  16204. { If x is a power of 2 (popcnt = 1), change:
  16205. xor $x, %reg/ref
  16206. To:
  16207. btc lb(x), %reg/ref
  16208. }
  16209. if IsBTXAcceptable(p) and
  16210. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  16211. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  16212. (
  16213. { Don't optimise if a test instruction follows }
  16214. not GetNextInstruction(p, hp1) or
  16215. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  16216. ) then
  16217. begin
  16218. 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);
  16219. taicpu(p).opcode := A_BTC;
  16220. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  16221. Result := True;
  16222. Exit;
  16223. end;
  16224. {$ifdef x86_64}
  16225. { Code size reduction by J. Gareth "Kit" Moreton }
  16226. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  16227. as this removes the REX prefix }
  16228. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  16229. Exit;
  16230. if taicpu(p).oper[0]^.typ <> top_reg then
  16231. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  16232. InternalError(2018011500);
  16233. case taicpu(p).opsize of
  16234. S_Q:
  16235. begin
  16236. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  16237. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  16238. { The actual optimization }
  16239. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  16240. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  16241. taicpu(p).changeopsize(S_L);
  16242. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  16243. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  16244. end;
  16245. else
  16246. ;
  16247. end;
  16248. {$endif x86_64}
  16249. end;
  16250. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  16251. var
  16252. XReg: TRegister;
  16253. begin
  16254. Result := False;
  16255. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  16256. Smaller encoding and slightly faster on some platforms (also works for
  16257. ZMM-sized registers) }
  16258. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  16259. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  16260. begin
  16261. XReg := taicpu(p).oper[0]^.reg;
  16262. if (taicpu(p).oper[1]^.reg = XReg) then
  16263. begin
  16264. taicpu(p).changeopsize(S_XMM);
  16265. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  16266. if (cs_opt_size in current_settings.optimizerswitches) then
  16267. begin
  16268. { Change input registers to %xmm0 to reduce size. Note that
  16269. there's a risk of a false dependency doing this, so only
  16270. optimise for size here }
  16271. XReg := NR_XMM0;
  16272. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  16273. end
  16274. else
  16275. begin
  16276. setsubreg(XReg, R_SUBMMX);
  16277. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  16278. end;
  16279. taicpu(p).oper[0]^.reg := XReg;
  16280. taicpu(p).oper[1]^.reg := XReg;
  16281. Result := True;
  16282. end;
  16283. end;
  16284. end;
  16285. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  16286. var
  16287. hp1, p_new: tai;
  16288. begin
  16289. Result := False;
  16290. { Check for:
  16291. ret
  16292. .Lbl:
  16293. ret
  16294. Remove first 'ret'
  16295. }
  16296. if GetNextInstruction(p, hp1) and
  16297. { Remember where the label is }
  16298. SetAndTest(hp1, p_new) and
  16299. (hp1.typ in [ait_align, ait_label]) and
  16300. SkipLabels(hp1, hp1) and
  16301. MatchInstruction(hp1, A_RET, []) and
  16302. { To be safe, make sure the RET instructions are identical }
  16303. (taicpu(p).ops = taicpu(hp1).ops) and
  16304. (
  16305. (taicpu(p).ops = 0) or
  16306. (
  16307. (taicpu(p).ops = 1) and
  16308. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  16309. )
  16310. ) then
  16311. begin
  16312. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  16313. UpdateUsedRegs(tai(p.Next));
  16314. RemoveCurrentP(p, p_new);
  16315. Result := True;
  16316. Exit;
  16317. end;
  16318. end;
  16319. function TX86AsmOptimizer.PostPeepholeOptRORX(var p: tai): Boolean;
  16320. begin
  16321. Result := False;
  16322. { Change: To:
  16323. rorx #x,%reg,%reg ror #x,%reg
  16324. (Smaller instruction size)
  16325. }
  16326. if MatchOperand(taicpu(p).oper[1]^,taicpu(p).oper[2]^.reg) and
  16327. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  16328. begin
  16329. taicpu(p).opcode:=A_ROR;
  16330. taicpu(p).ops:=2;
  16331. taicpu(p).clearop(2);
  16332. end;
  16333. end;
  16334. function TX86AsmOptimizer.PostPeepholeOptSARXSHLXSHRX(var p: tai): Boolean;
  16335. begin
  16336. Result := False;
  16337. { Change: bTo:
  16338. shlx %ecx,%reg,%reg shl %cl,%reg
  16339. (Smaller instruction size)
  16340. Same with SARX and SHRX (and when using %rcx for 64-bit)
  16341. }
  16342. if (getsupreg(taicpu(p).oper[0]^.reg)=RS_ECX) and
  16343. MatchOperand(taicpu(p).oper[1]^,taicpu(p).oper[2]^.reg) and
  16344. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  16345. begin
  16346. case taicpu(p).opcode of
  16347. A_SARX: taicpu(p).opcode:=A_SAR;
  16348. A_SHLX: taicpu(p).opcode:=A_SHL;
  16349. A_SHRX: taicpu(p).opcode:=A_SHR;
  16350. else
  16351. InternalError(2025090501);
  16352. end;
  16353. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  16354. taicpu(p).ops:=2;
  16355. taicpu(p).clearop(2);
  16356. end;
  16357. end;
  16358. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  16359. var
  16360. OperIdx: Integer;
  16361. begin
  16362. for OperIdx := 0 to p.ops - 1 do
  16363. if p.oper[OperIdx]^.typ = top_ref then
  16364. optimize_ref(p.oper[OperIdx]^.ref^, False);
  16365. end;
  16366. end.