aoptx86.pas 698 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135
  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. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2037. (hp1.typ = ait_instruction) and
  2038. (
  2039. { Under -O2 and below, the instructions are always adjacent }
  2040. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2041. (taicpu(hp1).ops <= 1) or
  2042. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2043. { If reg1 = reg3, reg1 must not be modified in between }
  2044. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2045. ) then
  2046. begin
  2047. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2048. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2049. begin
  2050. { vmova* reg1,reg2
  2051. ...
  2052. vmova* reg2,reg3
  2053. dealloc reg2
  2054. =>
  2055. vmova* reg1,reg3 }
  2056. TransferUsedRegs(TmpUsedRegs);
  2057. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2058. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2059. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2060. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2061. begin
  2062. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2063. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2064. RemoveInstruction(hp1);
  2065. result:=true;
  2066. exit;
  2067. end;
  2068. { special case:
  2069. vmova* reg1,<op>
  2070. ...
  2071. vmova* <op>,reg1
  2072. =>
  2073. vmova* reg1,<op> }
  2074. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2075. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2076. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2077. ) then
  2078. begin
  2079. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2080. RemoveInstruction(hp1);
  2081. result:=true;
  2082. exit;
  2083. end
  2084. end
  2085. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2086. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2087. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2088. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2089. ) and
  2090. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2091. begin
  2092. { vmova* reg1,reg2
  2093. ...
  2094. vmovs* reg2,<op>
  2095. dealloc reg2
  2096. =>
  2097. vmovs* reg1,reg3 }
  2098. TransferUsedRegs(TmpUsedRegs);
  2099. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2100. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2101. begin
  2102. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2103. taicpu(p).opcode:=taicpu(hp1).opcode;
  2104. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2105. RemoveInstruction(hp1);
  2106. result:=true;
  2107. exit;
  2108. end
  2109. end;
  2110. if MatchInstruction(hp1,[A_VFMADDPD,
  2111. A_VFMADD132PD,
  2112. A_VFMADD132PS,
  2113. A_VFMADD132SD,
  2114. A_VFMADD132SS,
  2115. A_VFMADD213PD,
  2116. A_VFMADD213PS,
  2117. A_VFMADD213SD,
  2118. A_VFMADD213SS,
  2119. A_VFMADD231PD,
  2120. A_VFMADD231PS,
  2121. A_VFMADD231SD,
  2122. A_VFMADD231SS,
  2123. A_VFMADDSUB132PD,
  2124. A_VFMADDSUB132PS,
  2125. A_VFMADDSUB213PD,
  2126. A_VFMADDSUB213PS,
  2127. A_VFMADDSUB231PD,
  2128. A_VFMADDSUB231PS,
  2129. A_VFMSUB132PD,
  2130. A_VFMSUB132PS,
  2131. A_VFMSUB132SD,
  2132. A_VFMSUB132SS,
  2133. A_VFMSUB213PD,
  2134. A_VFMSUB213PS,
  2135. A_VFMSUB213SD,
  2136. A_VFMSUB213SS,
  2137. A_VFMSUB231PD,
  2138. A_VFMSUB231PS,
  2139. A_VFMSUB231SD,
  2140. A_VFMSUB231SS,
  2141. A_VFMSUBADD132PD,
  2142. A_VFMSUBADD132PS,
  2143. A_VFMSUBADD213PD,
  2144. A_VFMSUBADD213PS,
  2145. A_VFMSUBADD231PD,
  2146. A_VFMSUBADD231PS,
  2147. A_VFNMADD132PD,
  2148. A_VFNMADD132PS,
  2149. A_VFNMADD132SD,
  2150. A_VFNMADD132SS,
  2151. A_VFNMADD213PD,
  2152. A_VFNMADD213PS,
  2153. A_VFNMADD213SD,
  2154. A_VFNMADD213SS,
  2155. A_VFNMADD231PD,
  2156. A_VFNMADD231PS,
  2157. A_VFNMADD231SD,
  2158. A_VFNMADD231SS,
  2159. A_VFNMSUB132PD,
  2160. A_VFNMSUB132PS,
  2161. A_VFNMSUB132SD,
  2162. A_VFNMSUB132SS,
  2163. A_VFNMSUB213PD,
  2164. A_VFNMSUB213PS,
  2165. A_VFNMSUB213SD,
  2166. A_VFNMSUB213SS,
  2167. A_VFNMSUB231PD,
  2168. A_VFNMSUB231PS,
  2169. A_VFNMSUB231SD,
  2170. A_VFNMSUB231SS],[S_NO]) and
  2171. { we mix single and double opperations here because we assume that the compiler
  2172. generates vmovapd only after double operations and vmovaps only after single operations }
  2173. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2174. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2175. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2176. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2177. begin
  2178. TransferUsedRegs(TmpUsedRegs);
  2179. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2180. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2181. begin
  2182. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2183. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2184. RemoveCurrentP(p)
  2185. else
  2186. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2187. RemoveInstruction(hp2);
  2188. end;
  2189. end
  2190. else if (hp1.typ = ait_instruction) and
  2191. (((taicpu(p).opcode=A_MOVAPS) and
  2192. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2193. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2194. ((taicpu(p).opcode=A_MOVAPD) and
  2195. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2196. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2197. ) and
  2198. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2199. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2200. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2201. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2202. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2203. { change
  2204. movapX reg,reg2
  2205. addsX/subsX/... reg3, reg2
  2206. movapX reg2,reg
  2207. to
  2208. addsX/subsX/... reg3,reg
  2209. }
  2210. begin
  2211. TransferUsedRegs(TmpUsedRegs);
  2212. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2213. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2214. begin
  2215. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2216. debug_op2str(taicpu(p).opcode)+' '+
  2217. debug_op2str(taicpu(hp1).opcode)+' '+
  2218. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2219. { we cannot eliminate the first move if
  2220. the operations uses the same register for source and dest }
  2221. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2222. { Remember that hp1 is not necessarily the immediate
  2223. next instruction }
  2224. RemoveCurrentP(p);
  2225. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2226. RemoveInstruction(hp2);
  2227. result:=true;
  2228. end;
  2229. end
  2230. else if (hp1.typ = ait_instruction) and
  2231. (((taicpu(p).opcode=A_VMOVAPD) and
  2232. (taicpu(hp1).opcode=A_VCOMISD)) or
  2233. ((taicpu(p).opcode=A_VMOVAPS) and
  2234. ((taicpu(hp1).opcode=A_VCOMISS))
  2235. )
  2236. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2237. { change
  2238. movapX reg,reg1
  2239. vcomisX reg1,reg1
  2240. to
  2241. vcomisX reg,reg
  2242. }
  2243. begin
  2244. TransferUsedRegs(TmpUsedRegs);
  2245. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2246. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2247. begin
  2248. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2249. debug_op2str(taicpu(p).opcode)+' '+
  2250. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2251. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2252. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2253. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2254. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2255. RemoveCurrentP(p);
  2256. result:=true;
  2257. exit;
  2258. end;
  2259. end
  2260. end;
  2261. end;
  2262. end;
  2263. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2264. var
  2265. hp1 : tai;
  2266. begin
  2267. result:=false;
  2268. { replace
  2269. V<Op>X %mreg1,%mreg2,%mreg3
  2270. VMovX %mreg3,%mreg4
  2271. dealloc %mreg3
  2272. by
  2273. V<Op>X %mreg1,%mreg2,%mreg4
  2274. ?
  2275. }
  2276. if GetNextInstruction(p,hp1) and
  2277. { we mix single and double operations here because we assume that the compiler
  2278. generates vmovapd only after double operations and vmovaps only after single operations }
  2279. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2280. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2281. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2282. begin
  2283. TransferUsedRegs(TmpUsedRegs);
  2284. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2285. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2286. begin
  2287. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2288. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2289. RemoveInstruction(hp1);
  2290. result:=true;
  2291. end;
  2292. end;
  2293. end;
  2294. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2295. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2296. begin
  2297. Result := False;
  2298. { For safety reasons, only check for exact register matches }
  2299. { Check base register }
  2300. if (ref.base = AOldReg) then
  2301. begin
  2302. ref.base := ANewReg;
  2303. Result := True;
  2304. end;
  2305. { Check index register }
  2306. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2307. begin
  2308. ref.index := ANewReg;
  2309. Result := True;
  2310. end;
  2311. end;
  2312. { Replaces all references to AOldReg in an operand to ANewReg }
  2313. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2314. var
  2315. OldSupReg, NewSupReg: TSuperRegister;
  2316. OldSubReg, NewSubReg: TSubRegister;
  2317. OldRegType: TRegisterType;
  2318. ThisOper: POper;
  2319. begin
  2320. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2321. Result := False;
  2322. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2323. InternalError(2020011801);
  2324. OldSupReg := getsupreg(AOldReg);
  2325. OldSubReg := getsubreg(AOldReg);
  2326. OldRegType := getregtype(AOldReg);
  2327. NewSupReg := getsupreg(ANewReg);
  2328. NewSubReg := getsubreg(ANewReg);
  2329. if OldRegType <> getregtype(ANewReg) then
  2330. InternalError(2020011802);
  2331. if OldSubReg <> NewSubReg then
  2332. InternalError(2020011803);
  2333. case ThisOper^.typ of
  2334. top_reg:
  2335. if (
  2336. (ThisOper^.reg = AOldReg) or
  2337. (
  2338. (OldRegType = R_INTREGISTER) and
  2339. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2340. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2341. (
  2342. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2343. {$ifndef x86_64}
  2344. and (
  2345. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2346. don't have an 8-bit representation }
  2347. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2348. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2349. )
  2350. {$endif x86_64}
  2351. )
  2352. )
  2353. ) then
  2354. begin
  2355. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2356. Result := True;
  2357. end;
  2358. top_ref:
  2359. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2360. Result := True;
  2361. else
  2362. ;
  2363. end;
  2364. end;
  2365. { Replaces all references to AOldReg in an instruction to ANewReg }
  2366. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2367. const
  2368. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2369. var
  2370. OperIdx: Integer;
  2371. begin
  2372. Result := False;
  2373. for OperIdx := 0 to p.ops - 1 do
  2374. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2375. begin
  2376. { The shift and rotate instructions can only use CL }
  2377. if not (
  2378. (OperIdx = 0) and
  2379. { This second condition just helps to avoid unnecessarily
  2380. calling MatchInstruction for 10 different opcodes }
  2381. (p.oper[0]^.reg = NR_CL) and
  2382. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2383. ) then
  2384. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2385. end
  2386. else if p.oper[OperIdx]^.typ = top_ref then
  2387. { It's okay to replace registers in references that get written to }
  2388. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2389. end;
  2390. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2391. begin
  2392. Result :=
  2393. (ref^.index = NR_NO) and
  2394. (
  2395. {$ifdef x86_64}
  2396. (
  2397. (ref^.base = NR_RIP) and
  2398. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2399. ) or
  2400. {$endif x86_64}
  2401. (ref^.refaddr = addr_full) or
  2402. (ref^.base = NR_STACK_POINTER_REG) or
  2403. (ref^.base = current_procinfo.framepointer)
  2404. );
  2405. end;
  2406. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2407. var
  2408. l: asizeint;
  2409. begin
  2410. Result := False;
  2411. { Should have been checked previously }
  2412. if p.opcode <> A_LEA then
  2413. InternalError(2020072501);
  2414. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2415. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2416. not(cs_opt_size in current_settings.optimizerswitches) then
  2417. exit;
  2418. with p.oper[0]^.ref^ do
  2419. begin
  2420. if (base <> p.oper[1]^.reg) or
  2421. (index <> NR_NO) or
  2422. assigned(symbol) then
  2423. exit;
  2424. l:=offset;
  2425. if (l=1) and UseIncDec then
  2426. begin
  2427. p.opcode:=A_INC;
  2428. p.loadreg(0,p.oper[1]^.reg);
  2429. p.ops:=1;
  2430. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2431. end
  2432. else if (l=-1) and UseIncDec then
  2433. begin
  2434. p.opcode:=A_DEC;
  2435. p.loadreg(0,p.oper[1]^.reg);
  2436. p.ops:=1;
  2437. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2438. end
  2439. else
  2440. begin
  2441. if (l<0) and (l<>-2147483648) then
  2442. begin
  2443. p.opcode:=A_SUB;
  2444. p.loadConst(0,-l);
  2445. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2446. end
  2447. else
  2448. begin
  2449. p.opcode:=A_ADD;
  2450. p.loadConst(0,l);
  2451. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2452. end;
  2453. end;
  2454. end;
  2455. Result := True;
  2456. end;
  2457. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2458. var
  2459. CurrentReg, ReplaceReg: TRegister;
  2460. begin
  2461. Result := False;
  2462. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2463. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2464. case hp.opcode of
  2465. A_FSTSW, A_FNSTSW,
  2466. A_IN, A_INS, A_OUT, A_OUTS,
  2467. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2468. { These routines have explicit operands, but they are restricted in
  2469. what they can be (e.g. IN and OUT can only read from AL, AX or
  2470. EAX. }
  2471. Exit;
  2472. A_IMUL:
  2473. begin
  2474. { The 1-operand version writes to implicit registers
  2475. The 2-operand version reads from the first operator, and reads
  2476. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2477. the 3-operand version reads from a register that it doesn't write to
  2478. }
  2479. case hp.ops of
  2480. 1:
  2481. if (
  2482. (
  2483. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2484. ) or
  2485. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2486. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2487. begin
  2488. Result := True;
  2489. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2490. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2491. end;
  2492. 2:
  2493. { Only modify the first parameter }
  2494. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2495. begin
  2496. Result := True;
  2497. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2498. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2499. end;
  2500. 3:
  2501. { Only modify the second parameter }
  2502. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2503. begin
  2504. Result := True;
  2505. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2506. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2507. end;
  2508. else
  2509. InternalError(2020012901);
  2510. end;
  2511. end;
  2512. else
  2513. if (hp.ops > 0) and
  2514. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2515. begin
  2516. Result := True;
  2517. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2518. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2519. end;
  2520. end;
  2521. end;
  2522. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2523. var
  2524. hp2: tai;
  2525. p_SourceReg, p_TargetReg: TRegister;
  2526. begin
  2527. Result := False;
  2528. { Backward optimisation. If we have:
  2529. func. %reg1,%reg2
  2530. mov %reg2,%reg3
  2531. (dealloc %reg2)
  2532. Change to:
  2533. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2534. Perform similar optimisations with 1, 3 and 4-operand instructions
  2535. that only have one output.
  2536. }
  2537. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2538. begin
  2539. p_SourceReg := taicpu(p).oper[0]^.reg;
  2540. p_TargetReg := taicpu(p).oper[1]^.reg;
  2541. TransferUsedRegs(TmpUsedRegs);
  2542. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2543. GetLastInstruction(p, hp2) and
  2544. (hp2.typ = ait_instruction) and
  2545. { Have to make sure it's an instruction that only reads from
  2546. the first operands and only writes (not reads or modifies) to
  2547. the last one; in essence, a pure function such as BSR, POPCNT
  2548. or ANDN }
  2549. (
  2550. (
  2551. (taicpu(hp2).ops = 1) and
  2552. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2553. ) or
  2554. (
  2555. (taicpu(hp2).ops = 2) and
  2556. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2557. ) or
  2558. (
  2559. (taicpu(hp2).ops = 3) and
  2560. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2561. ) or
  2562. (
  2563. (taicpu(hp2).ops = 4) and
  2564. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2565. )
  2566. ) and
  2567. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2568. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2569. begin
  2570. case taicpu(hp2).opcode of
  2571. A_FSTSW, A_FNSTSW,
  2572. A_IN, A_INS, A_OUT, A_OUTS,
  2573. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2574. { These routines have explicit operands, but they are restricted in
  2575. what they can be (e.g. IN and OUT can only read from AL, AX or
  2576. EAX. }
  2577. ;
  2578. else
  2579. begin
  2580. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2581. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2582. if not RegInInstruction(p_TargetReg, hp2) then
  2583. begin
  2584. { Since we're allocating from an earlier point, we
  2585. need to remove the register from the tracking }
  2586. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2587. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2588. end;
  2589. RemoveCurrentp(p, hp1);
  2590. { If the Func was another MOV instruction, we might get
  2591. "mov %reg,%reg" that doesn't get removed in Pass 2
  2592. otherwise, so deal with it here (also do something
  2593. similar with lea (%reg),%reg}
  2594. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2595. begin
  2596. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2597. if p = hp2 then
  2598. RemoveCurrentp(p)
  2599. else
  2600. RemoveInstruction(hp2);
  2601. end;
  2602. Result := True;
  2603. Exit;
  2604. end;
  2605. end;
  2606. end;
  2607. end;
  2608. end;
  2609. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2610. var
  2611. hp1, hp2, hp3: tai;
  2612. DoOptimisation, TempBool: Boolean;
  2613. {$ifdef x86_64}
  2614. NewConst: TCGInt;
  2615. {$endif x86_64}
  2616. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2617. begin
  2618. if taicpu(hp1).opcode = signed_movop then
  2619. begin
  2620. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2621. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2622. end
  2623. else
  2624. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2625. end;
  2626. function TryConstMerge(var p1, p2: tai): Boolean;
  2627. var
  2628. ThisRef: TReference;
  2629. begin
  2630. Result := False;
  2631. ThisRef := taicpu(p2).oper[1]^.ref^;
  2632. { Only permit writes to the stack, since we can guarantee alignment with that }
  2633. if (ThisRef.index = NR_NO) and
  2634. (
  2635. (ThisRef.base = NR_STACK_POINTER_REG) or
  2636. (ThisRef.base = current_procinfo.framepointer)
  2637. ) then
  2638. begin
  2639. case taicpu(p).opsize of
  2640. S_B:
  2641. begin
  2642. { Word writes must be on a 2-byte boundary }
  2643. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2644. begin
  2645. { Reduce offset of second reference to see if it is sequential with the first }
  2646. Dec(ThisRef.offset, 1);
  2647. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2648. begin
  2649. { Make sure the constants aren't represented as a
  2650. negative number, as these won't merge properly }
  2651. taicpu(p1).opsize := S_W;
  2652. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2653. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2654. RemoveInstruction(p2);
  2655. Result := True;
  2656. end;
  2657. end;
  2658. end;
  2659. S_W:
  2660. begin
  2661. { Longword writes must be on a 4-byte boundary }
  2662. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2663. begin
  2664. { Reduce offset of second reference to see if it is sequential with the first }
  2665. Dec(ThisRef.offset, 2);
  2666. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2667. begin
  2668. { Make sure the constants aren't represented as a
  2669. negative number, as these won't merge properly }
  2670. taicpu(p1).opsize := S_L;
  2671. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2672. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2673. RemoveInstruction(p2);
  2674. Result := True;
  2675. end;
  2676. end;
  2677. end;
  2678. {$ifdef x86_64}
  2679. S_L:
  2680. begin
  2681. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2682. see if the constants can be encoded this way. }
  2683. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2684. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2685. { Quadword writes must be on an 8-byte boundary }
  2686. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2687. begin
  2688. { Reduce offset of second reference to see if it is sequential with the first }
  2689. Dec(ThisRef.offset, 4);
  2690. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2691. begin
  2692. { Make sure the constants aren't represented as a
  2693. negative number, as these won't merge properly }
  2694. taicpu(p1).opsize := S_Q;
  2695. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2696. taicpu(p1).oper[0]^.val := NewConst;
  2697. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2698. RemoveInstruction(p2);
  2699. Result := True;
  2700. end;
  2701. end;
  2702. end;
  2703. {$endif x86_64}
  2704. else
  2705. ;
  2706. end;
  2707. end;
  2708. end;
  2709. var
  2710. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2711. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2712. NewSize: topsize; NewOffset: asizeint;
  2713. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2714. SourceRef, TargetRef: TReference;
  2715. MovAligned, MovUnaligned: TAsmOp;
  2716. ThisRef: TReference;
  2717. JumpTracking: TLinkedList;
  2718. begin
  2719. Result:=false;
  2720. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2721. { remove mov reg1,reg1? }
  2722. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2723. then
  2724. begin
  2725. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2726. { take care of the register (de)allocs following p }
  2727. RemoveCurrentP(p, hp1);
  2728. Result:=true;
  2729. exit;
  2730. end;
  2731. { All the next optimisations require a next instruction }
  2732. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2733. Exit;
  2734. { Prevent compiler warnings }
  2735. p_TargetReg := NR_NO;
  2736. if taicpu(p).oper[1]^.typ = top_reg then
  2737. begin
  2738. { Saves on a large number of dereferences }
  2739. p_TargetReg := taicpu(p).oper[1]^.reg;
  2740. { Look for:
  2741. mov %reg1,%reg2
  2742. ??? %reg2,r/m
  2743. Change to:
  2744. mov %reg1,%reg2
  2745. ??? %reg1,r/m
  2746. }
  2747. if taicpu(p).oper[0]^.typ = top_reg then
  2748. begin
  2749. if RegReadByInstruction(p_TargetReg, hp1) and
  2750. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2751. begin
  2752. { A change has occurred, just not in p }
  2753. Result := True;
  2754. TransferUsedRegs(TmpUsedRegs);
  2755. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2756. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2757. { Just in case something didn't get modified (e.g. an
  2758. implicit register) }
  2759. not RegReadByInstruction(p_TargetReg, hp1) then
  2760. begin
  2761. { We can remove the original MOV }
  2762. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2763. RemoveCurrentp(p, hp1);
  2764. { UsedRegs got updated by RemoveCurrentp }
  2765. Result := True;
  2766. Exit;
  2767. end;
  2768. { If we know a MOV instruction has become a null operation, we might as well
  2769. get rid of it now to save time. }
  2770. if (taicpu(hp1).opcode = A_MOV) and
  2771. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2772. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2773. { Just being a register is enough to confirm it's a null operation }
  2774. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2775. begin
  2776. Result := True;
  2777. { Speed-up to reduce a pipeline stall... if we had something like...
  2778. movl %eax,%edx
  2779. movw %dx,%ax
  2780. ... the second instruction would change to movw %ax,%ax, but
  2781. given that it is now %ax that's active rather than %eax,
  2782. penalties might occur due to a partial register write, so instead,
  2783. change it to a MOVZX instruction when optimising for speed.
  2784. }
  2785. if not (cs_opt_size in current_settings.optimizerswitches) and
  2786. IsMOVZXAcceptable and
  2787. (taicpu(hp1).opsize < taicpu(p).opsize)
  2788. {$ifdef x86_64}
  2789. { operations already implicitly set the upper 64 bits to zero }
  2790. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2791. {$endif x86_64}
  2792. then
  2793. begin
  2794. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2795. case taicpu(p).opsize of
  2796. S_W:
  2797. if taicpu(hp1).opsize = S_B then
  2798. taicpu(hp1).opsize := S_BL
  2799. else
  2800. InternalError(2020012911);
  2801. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2802. case taicpu(hp1).opsize of
  2803. S_B:
  2804. taicpu(hp1).opsize := S_BL;
  2805. S_W:
  2806. taicpu(hp1).opsize := S_WL;
  2807. else
  2808. InternalError(2020012912);
  2809. end;
  2810. else
  2811. InternalError(2020012910);
  2812. end;
  2813. taicpu(hp1).opcode := A_MOVZX;
  2814. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2815. end
  2816. else
  2817. begin
  2818. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2819. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2820. RemoveInstruction(hp1);
  2821. { The instruction after what was hp1 is now the immediate next instruction,
  2822. so we can continue to make optimisations if it's present }
  2823. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2824. Exit;
  2825. hp1 := hp2;
  2826. end;
  2827. end;
  2828. end;
  2829. end;
  2830. end;
  2831. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2832. overwrites the original destination register. e.g.
  2833. movl ###,%reg2d
  2834. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2835. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2836. }
  2837. if (taicpu(p).oper[1]^.typ = top_reg) and
  2838. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2839. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2840. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2841. begin
  2842. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2843. begin
  2844. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2845. case taicpu(p).oper[0]^.typ of
  2846. top_const:
  2847. { We have something like:
  2848. movb $x, %regb
  2849. movzbl %regb,%regd
  2850. Change to:
  2851. movl $x, %regd
  2852. }
  2853. begin
  2854. case taicpu(hp1).opsize of
  2855. S_BW:
  2856. begin
  2857. convert_mov_value(A_MOVSX, $FF);
  2858. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2859. taicpu(p).opsize := S_W;
  2860. end;
  2861. S_BL:
  2862. begin
  2863. convert_mov_value(A_MOVSX, $FF);
  2864. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2865. taicpu(p).opsize := S_L;
  2866. end;
  2867. S_WL:
  2868. begin
  2869. convert_mov_value(A_MOVSX, $FFFF);
  2870. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2871. taicpu(p).opsize := S_L;
  2872. end;
  2873. {$ifdef x86_64}
  2874. S_BQ:
  2875. begin
  2876. convert_mov_value(A_MOVSX, $FF);
  2877. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2878. taicpu(p).opsize := S_Q;
  2879. end;
  2880. S_WQ:
  2881. begin
  2882. convert_mov_value(A_MOVSX, $FFFF);
  2883. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2884. taicpu(p).opsize := S_Q;
  2885. end;
  2886. S_LQ:
  2887. begin
  2888. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2889. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2890. taicpu(p).opsize := S_Q;
  2891. end;
  2892. {$endif x86_64}
  2893. else
  2894. { If hp1 was a MOV instruction, it should have been
  2895. optimised already }
  2896. InternalError(2020021001);
  2897. end;
  2898. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2899. RemoveInstruction(hp1);
  2900. Result := True;
  2901. Exit;
  2902. end;
  2903. top_ref:
  2904. begin
  2905. { We have something like:
  2906. movb mem, %regb
  2907. movzbl %regb,%regd
  2908. Change to:
  2909. movzbl mem, %regd
  2910. }
  2911. ThisRef := taicpu(p).oper[0]^.ref^;
  2912. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2913. begin
  2914. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2915. taicpu(hp1).loadref(0, ThisRef);
  2916. { Make sure any registers in the references are properly tracked }
  2917. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2918. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2919. if (ThisRef.index <> NR_NO) then
  2920. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2921. RemoveCurrentP(p, hp1);
  2922. Result := True;
  2923. Exit;
  2924. end;
  2925. end;
  2926. else
  2927. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2928. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2929. Exit;
  2930. end;
  2931. end
  2932. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2933. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2934. optimised }
  2935. else
  2936. begin
  2937. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2938. RemoveCurrentP(p, hp1);
  2939. Result := True;
  2940. Exit;
  2941. end;
  2942. end;
  2943. if (taicpu(hp1).opcode = A_AND) and
  2944. (taicpu(p).oper[1]^.typ = top_reg) and
  2945. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2946. begin
  2947. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2948. begin
  2949. case taicpu(p).opsize of
  2950. S_L:
  2951. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2952. begin
  2953. { Optimize out:
  2954. mov x, %reg
  2955. and ffffffffh, %reg
  2956. }
  2957. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2958. RemoveInstruction(hp1);
  2959. Result:=true;
  2960. exit;
  2961. end;
  2962. S_Q: { TODO: Confirm if this is even possible }
  2963. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2964. begin
  2965. { Optimize out:
  2966. mov x, %reg
  2967. and ffffffffffffffffh, %reg
  2968. }
  2969. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2970. RemoveInstruction(hp1);
  2971. Result:=true;
  2972. exit;
  2973. end;
  2974. else
  2975. ;
  2976. end;
  2977. if (
  2978. (taicpu(p).oper[0]^.typ=top_reg) or
  2979. (
  2980. (taicpu(p).oper[0]^.typ=top_ref) and
  2981. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2982. )
  2983. ) and
  2984. GetNextInstruction(hp1,hp2) and
  2985. MatchInstruction(hp2,A_TEST,[]) and
  2986. (
  2987. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2988. (
  2989. { If the register being tested is smaller than the one
  2990. that received a bitwise AND, permit it if the constant
  2991. fits into the smaller size }
  2992. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2993. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2994. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2995. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2996. (
  2997. (
  2998. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2999. (taicpu(hp1).oper[0]^.val <= $FF)
  3000. ) or
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3003. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3004. {$ifdef x86_64}
  3005. ) or
  3006. (
  3007. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3008. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3009. {$endif x86_64}
  3010. )
  3011. )
  3012. )
  3013. ) and
  3014. (
  3015. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3016. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3017. ) and
  3018. GetNextInstruction(hp2,hp3) and
  3019. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3020. (taicpu(hp3).condition in [C_E,C_NE]) then
  3021. begin
  3022. TransferUsedRegs(TmpUsedRegs);
  3023. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3024. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3025. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3026. begin
  3027. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3028. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3029. taicpu(hp1).opcode:=A_TEST;
  3030. { Shrink the TEST instruction down to the smallest possible size }
  3031. case taicpu(hp1).oper[0]^.val of
  3032. 0..255:
  3033. if (taicpu(hp1).opsize <> S_B)
  3034. {$ifndef x86_64}
  3035. and (
  3036. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3037. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3038. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3039. )
  3040. {$endif x86_64}
  3041. then
  3042. begin
  3043. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3044. { Only print debug message if the TEST instruction
  3045. is a different size before and after }
  3046. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3047. taicpu(hp1).opsize := S_B;
  3048. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3049. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3050. end;
  3051. 256..65535:
  3052. if (taicpu(hp1).opsize <> S_W) then
  3053. begin
  3054. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3055. { Only print debug message if the TEST instruction
  3056. is a different size before and after }
  3057. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3058. taicpu(hp1).opsize := S_W;
  3059. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3060. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3061. end;
  3062. {$ifdef x86_64}
  3063. 65536..$7FFFFFFF:
  3064. if (taicpu(hp1).opsize <> S_L) then
  3065. begin
  3066. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3067. { Only print debug message if the TEST instruction
  3068. is a different size before and after }
  3069. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3070. taicpu(hp1).opsize := S_L;
  3071. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3072. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3073. end;
  3074. {$endif x86_64}
  3075. else
  3076. ;
  3077. end;
  3078. RemoveInstruction(hp2);
  3079. RemoveCurrentP(p, hp1);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. end;
  3084. end
  3085. else if IsMOVZXAcceptable and
  3086. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3087. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3088. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3089. then
  3090. begin
  3091. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3092. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3093. case taicpu(p).opsize of
  3094. S_B:
  3095. if (taicpu(hp1).oper[0]^.val = $ff) then
  3096. begin
  3097. { Convert:
  3098. movb x, %regl movb x, %regl
  3099. andw ffh, %regw andl ffh, %regd
  3100. To:
  3101. movzbw x, %regd movzbl x, %regd
  3102. (Identical registers, just different sizes)
  3103. }
  3104. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3105. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3106. case taicpu(hp1).opsize of
  3107. S_W: NewSize := S_BW;
  3108. S_L: NewSize := S_BL;
  3109. {$ifdef x86_64}
  3110. S_Q: NewSize := S_BQ;
  3111. {$endif x86_64}
  3112. else
  3113. InternalError(2018011510);
  3114. end;
  3115. end
  3116. else
  3117. NewSize := S_NO;
  3118. S_W:
  3119. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3120. begin
  3121. { Convert:
  3122. movw x, %regw
  3123. andl ffffh, %regd
  3124. To:
  3125. movzwl x, %regd
  3126. (Identical registers, just different sizes)
  3127. }
  3128. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3129. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3130. case taicpu(hp1).opsize of
  3131. S_L: NewSize := S_WL;
  3132. {$ifdef x86_64}
  3133. S_Q: NewSize := S_WQ;
  3134. {$endif x86_64}
  3135. else
  3136. InternalError(2018011511);
  3137. end;
  3138. end
  3139. else
  3140. NewSize := S_NO;
  3141. else
  3142. NewSize := S_NO;
  3143. end;
  3144. if NewSize <> S_NO then
  3145. begin
  3146. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3147. { The actual optimization }
  3148. taicpu(p).opcode := A_MOVZX;
  3149. taicpu(p).changeopsize(NewSize);
  3150. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3151. { Safeguard if "and" is followed by a conditional command }
  3152. TransferUsedRegs(TmpUsedRegs);
  3153. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3154. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3155. begin
  3156. { At this point, the "and" command is effectively equivalent to
  3157. "test %reg,%reg". This will be handled separately by the
  3158. Peephole Optimizer. [Kit] }
  3159. DebugMsg(SPeepholeOptimization + PreMessage +
  3160. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3161. end
  3162. else
  3163. begin
  3164. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3165. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3166. RemoveInstruction(hp1);
  3167. end;
  3168. Result := True;
  3169. Exit;
  3170. end;
  3171. end;
  3172. end;
  3173. if (taicpu(hp1).opcode = A_OR) and
  3174. (taicpu(p).oper[1]^.typ = top_reg) and
  3175. MatchOperand(taicpu(p).oper[0]^, 0) and
  3176. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3177. begin
  3178. { mov 0, %reg
  3179. or ###,%reg
  3180. Change to (only if the flags are not used):
  3181. mov ###,%reg
  3182. }
  3183. TransferUsedRegs(TmpUsedRegs);
  3184. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3185. DoOptimisation := True;
  3186. { Even if the flags are used, we might be able to do the optimisation
  3187. if the conditions are predictable }
  3188. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3189. begin
  3190. { Only perform if ### = %reg (the same register) or equal to 0,
  3191. so %reg is guaranteed to still have a value of zero }
  3192. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3193. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3194. begin
  3195. hp2 := hp1;
  3196. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3197. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3198. GetNextInstruction(hp2, hp3) do
  3199. begin
  3200. { Don't continue modifying if the flags state is getting changed }
  3201. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3202. Break;
  3203. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3204. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3205. begin
  3206. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3207. begin
  3208. { Condition is always true }
  3209. case taicpu(hp3).opcode of
  3210. A_Jcc:
  3211. begin
  3212. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3213. { Check for jump shortcuts before we destroy the condition }
  3214. DoJumpOptimizations(hp3, TempBool);
  3215. MakeUnconditional(taicpu(hp3));
  3216. Result := True;
  3217. end;
  3218. A_CMOVcc:
  3219. begin
  3220. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3221. taicpu(hp3).opcode := A_MOV;
  3222. taicpu(hp3).condition := C_None;
  3223. Result := True;
  3224. end;
  3225. A_SETcc:
  3226. begin
  3227. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3228. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3229. taicpu(hp3).opcode := A_MOV;
  3230. taicpu(hp3).ops := 2;
  3231. taicpu(hp3).condition := C_None;
  3232. taicpu(hp3).opsize := S_B;
  3233. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3234. taicpu(hp3).loadconst(0, 1);
  3235. Result := True;
  3236. end;
  3237. else
  3238. InternalError(2021090701);
  3239. end;
  3240. end
  3241. 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
  3242. begin
  3243. { Condition is always false }
  3244. case taicpu(hp3).opcode of
  3245. A_Jcc:
  3246. begin
  3247. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3248. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3249. RemoveInstruction(hp3);
  3250. Result := True;
  3251. { Since hp3 was deleted, hp2 must not be updated }
  3252. Continue;
  3253. end;
  3254. A_CMOVcc:
  3255. begin
  3256. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3257. RemoveInstruction(hp3);
  3258. Result := True;
  3259. { Since hp3 was deleted, hp2 must not be updated }
  3260. Continue;
  3261. end;
  3262. A_SETcc:
  3263. begin
  3264. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3265. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3266. taicpu(hp3).opcode := A_MOV;
  3267. taicpu(hp3).ops := 2;
  3268. taicpu(hp3).condition := C_None;
  3269. taicpu(hp3).opsize := S_B;
  3270. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3271. taicpu(hp3).loadconst(0, 0);
  3272. Result := True;
  3273. end;
  3274. else
  3275. InternalError(2021090702);
  3276. end;
  3277. end
  3278. else
  3279. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3280. DoOptimisation := False;
  3281. end;
  3282. hp2 := hp3;
  3283. end;
  3284. { Flags are still in use - don't optimise }
  3285. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3286. DoOptimisation := False;
  3287. end
  3288. else
  3289. DoOptimisation := False;
  3290. end;
  3291. if DoOptimisation then
  3292. begin
  3293. {$ifdef x86_64}
  3294. { OR only supports 32-bit sign-extended constants for 64-bit
  3295. instructions, so compensate for this if the constant is
  3296. encoded as a value greater than or equal to 2^31 }
  3297. if (taicpu(hp1).opsize = S_Q) and
  3298. (taicpu(hp1).oper[0]^.typ = top_const) and
  3299. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3300. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3301. {$endif x86_64}
  3302. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3303. taicpu(hp1).opcode := A_MOV;
  3304. RemoveCurrentP(p, hp1);
  3305. Result := True;
  3306. Exit;
  3307. end;
  3308. end;
  3309. { Next instruction is also a MOV ? }
  3310. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3311. begin
  3312. if MatchOpType(taicpu(p), top_const, top_ref) and
  3313. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3314. TryConstMerge(p, hp1) then
  3315. begin
  3316. Result := True;
  3317. { In case we have four byte writes in a row, check for 2 more
  3318. right now so we don't have to wait for another iteration of
  3319. pass 1
  3320. }
  3321. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3322. case taicpu(p).opsize of
  3323. S_W:
  3324. begin
  3325. if GetNextInstruction(p, hp1) and
  3326. MatchInstruction(hp1, A_MOV, [S_B]) and
  3327. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3328. GetNextInstruction(hp1, hp2) and
  3329. MatchInstruction(hp2, A_MOV, [S_B]) and
  3330. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3331. { Try to merge the two bytes }
  3332. TryConstMerge(hp1, hp2) then
  3333. { Now try to merge the two words (hp2 will get deleted) }
  3334. TryConstMerge(p, hp1);
  3335. end;
  3336. S_L:
  3337. begin
  3338. { Though this only really benefits x86_64 and not i386, it
  3339. gets a potential optimisation done faster and hence
  3340. reduces the number of times OptPass1MOV is entered }
  3341. if GetNextInstruction(p, hp1) and
  3342. MatchInstruction(hp1, A_MOV, [S_W]) and
  3343. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3344. GetNextInstruction(hp1, hp2) and
  3345. MatchInstruction(hp2, A_MOV, [S_W]) and
  3346. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3347. { Try to merge the two words }
  3348. TryConstMerge(hp1, hp2) then
  3349. { This will always fail on i386, so don't bother
  3350. calling it unless we're doing x86_64 }
  3351. {$ifdef x86_64}
  3352. { Now try to merge the two longwords (hp2 will get deleted) }
  3353. TryConstMerge(p, hp1)
  3354. {$endif x86_64}
  3355. ;
  3356. end;
  3357. else
  3358. ;
  3359. end;
  3360. Exit;
  3361. end;
  3362. if (taicpu(p).oper[1]^.typ = top_reg) and
  3363. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3364. begin
  3365. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3366. TransferUsedRegs(TmpUsedRegs);
  3367. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3368. { we have
  3369. mov x, %treg
  3370. mov %treg, y
  3371. }
  3372. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3373. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3374. { we've got
  3375. mov x, %treg
  3376. mov %treg, y
  3377. with %treg is not used after }
  3378. case taicpu(p).oper[0]^.typ Of
  3379. { top_reg is covered by DeepMOVOpt }
  3380. top_const:
  3381. begin
  3382. { change
  3383. mov const, %treg
  3384. mov %treg, y
  3385. to
  3386. mov const, y
  3387. }
  3388. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3389. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3390. begin
  3391. if taicpu(hp1).oper[1]^.typ=top_reg then
  3392. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3393. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3394. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3395. RemoveInstruction(hp1);
  3396. Result:=true;
  3397. Exit;
  3398. end;
  3399. end;
  3400. top_ref:
  3401. case taicpu(hp1).oper[1]^.typ of
  3402. top_reg:
  3403. begin
  3404. { change
  3405. mov mem, %treg
  3406. mov %treg, %reg
  3407. to
  3408. mov mem, %reg"
  3409. }
  3410. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3411. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3412. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3413. RemoveInstruction(hp1);
  3414. Result:=true;
  3415. Exit;
  3416. end;
  3417. top_ref:
  3418. begin
  3419. {$ifdef x86_64}
  3420. { Look for the following to simplify:
  3421. mov x(mem1), %reg
  3422. mov %reg, y(mem2)
  3423. mov x+8(mem1), %reg
  3424. mov %reg, y+8(mem2)
  3425. Change to:
  3426. movdqu x(mem1), %xmmreg
  3427. movdqu %xmmreg, y(mem2)
  3428. ...but only as long as the memory blocks don't overlap
  3429. }
  3430. SourceRef := taicpu(p).oper[0]^.ref^;
  3431. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3432. if (taicpu(p).opsize = S_Q) and
  3433. GetNextInstruction(hp1, hp2) and
  3434. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3435. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3436. begin
  3437. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3438. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3439. Inc(SourceRef.offset, 8);
  3440. if UseAVX then
  3441. begin
  3442. MovAligned := A_VMOVDQA;
  3443. MovUnaligned := A_VMOVDQU;
  3444. end
  3445. else
  3446. begin
  3447. MovAligned := A_MOVDQA;
  3448. MovUnaligned := A_MOVDQU;
  3449. end;
  3450. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3451. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3452. begin
  3453. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3454. Inc(TargetRef.offset, 8);
  3455. if GetNextInstruction(hp2, hp3) and
  3456. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3457. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3458. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3459. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3460. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3461. begin
  3462. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3463. if NewMMReg <> NR_NO then
  3464. begin
  3465. { Remember that the offsets are 8 ahead }
  3466. if ((SourceRef.offset mod 16) = 8) and
  3467. (
  3468. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3469. (SourceRef.base = current_procinfo.framepointer) or
  3470. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3471. ) then
  3472. taicpu(p).opcode := MovAligned
  3473. else
  3474. taicpu(p).opcode := MovUnaligned;
  3475. taicpu(p).opsize := S_XMM;
  3476. taicpu(p).oper[1]^.reg := NewMMReg;
  3477. if ((TargetRef.offset mod 16) = 8) and
  3478. (
  3479. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3480. (TargetRef.base = current_procinfo.framepointer) or
  3481. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3482. ) then
  3483. taicpu(hp1).opcode := MovAligned
  3484. else
  3485. taicpu(hp1).opcode := MovUnaligned;
  3486. taicpu(hp1).opsize := S_XMM;
  3487. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3488. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3489. RemoveInstruction(hp2);
  3490. RemoveInstruction(hp3);
  3491. Result := True;
  3492. Exit;
  3493. end;
  3494. end;
  3495. end
  3496. else
  3497. begin
  3498. { See if the next references are 8 less rather than 8 greater }
  3499. Dec(SourceRef.offset, 16); { -8 the other way }
  3500. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3501. begin
  3502. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3503. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3504. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3505. GetNextInstruction(hp2, hp3) and
  3506. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3507. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3508. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3509. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3510. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3511. begin
  3512. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3513. if NewMMReg <> NR_NO then
  3514. begin
  3515. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3516. if ((SourceRef.offset mod 16) = 0) and
  3517. (
  3518. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3519. (SourceRef.base = current_procinfo.framepointer) or
  3520. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3521. ) then
  3522. taicpu(hp2).opcode := MovAligned
  3523. else
  3524. taicpu(hp2).opcode := MovUnaligned;
  3525. taicpu(hp2).opsize := S_XMM;
  3526. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3527. if ((TargetRef.offset mod 16) = 0) and
  3528. (
  3529. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3530. (TargetRef.base = current_procinfo.framepointer) or
  3531. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3532. ) then
  3533. taicpu(hp3).opcode := MovAligned
  3534. else
  3535. taicpu(hp3).opcode := MovUnaligned;
  3536. taicpu(hp3).opsize := S_XMM;
  3537. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3538. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3539. RemoveInstruction(hp1);
  3540. RemoveCurrentP(p, hp2);
  3541. Result := True;
  3542. Exit;
  3543. end;
  3544. end;
  3545. end;
  3546. end;
  3547. end;
  3548. {$endif x86_64}
  3549. end;
  3550. else
  3551. { The write target should be a reg or a ref }
  3552. InternalError(2021091601);
  3553. end;
  3554. else
  3555. ;
  3556. end
  3557. else
  3558. { %treg is used afterwards, but all eventualities
  3559. other than the first MOV instruction being a constant
  3560. are covered by DeepMOVOpt, so only check for that }
  3561. if (taicpu(p).oper[0]^.typ = top_const) and
  3562. (
  3563. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3564. not (cs_opt_size in current_settings.optimizerswitches) or
  3565. (taicpu(hp1).opsize = S_B)
  3566. ) and
  3567. (
  3568. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3569. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3570. ) then
  3571. begin
  3572. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3573. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3574. end;
  3575. end;
  3576. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3577. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3578. { mov reg1, mem1 or mov mem1, reg1
  3579. mov mem2, reg2 mov reg2, mem2}
  3580. begin
  3581. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3582. { mov reg1, mem1 or mov mem1, reg1
  3583. mov mem2, reg1 mov reg2, mem1}
  3584. begin
  3585. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3586. { Removes the second statement from
  3587. mov reg1, mem1/reg2
  3588. mov mem1/reg2, reg1 }
  3589. begin
  3590. if taicpu(p).oper[0]^.typ=top_reg then
  3591. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3592. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3593. RemoveInstruction(hp1);
  3594. Result:=true;
  3595. exit;
  3596. end
  3597. else
  3598. begin
  3599. TransferUsedRegs(TmpUsedRegs);
  3600. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3601. if (taicpu(p).oper[1]^.typ = top_ref) and
  3602. { mov reg1, mem1
  3603. mov mem2, reg1 }
  3604. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3605. GetNextInstruction(hp1, hp2) and
  3606. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3607. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3608. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3609. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3610. { change to
  3611. mov reg1, mem1 mov reg1, mem1
  3612. mov mem2, reg1 cmp reg1, mem2
  3613. cmp mem1, reg1
  3614. }
  3615. begin
  3616. RemoveInstruction(hp2);
  3617. taicpu(hp1).opcode := A_CMP;
  3618. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3619. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3620. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3621. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3622. end;
  3623. end;
  3624. end
  3625. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3626. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3627. begin
  3628. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3629. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3630. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3631. end
  3632. else
  3633. begin
  3634. TransferUsedRegs(TmpUsedRegs);
  3635. if GetNextInstruction(hp1, hp2) and
  3636. MatchOpType(taicpu(p),top_ref,top_reg) and
  3637. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3638. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3639. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3640. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3641. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3642. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3643. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3644. { mov mem1, %reg1
  3645. mov %reg1, mem2
  3646. mov mem2, reg2
  3647. to:
  3648. mov mem1, reg2
  3649. mov reg2, mem2}
  3650. begin
  3651. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3652. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3653. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3654. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3655. RemoveInstruction(hp2);
  3656. Result := True;
  3657. end
  3658. {$ifdef i386}
  3659. { this is enabled for i386 only, as the rules to create the reg sets below
  3660. are too complicated for x86-64, so this makes this code too error prone
  3661. on x86-64
  3662. }
  3663. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3664. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3665. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3666. { mov mem1, reg1 mov mem1, reg1
  3667. mov reg1, mem2 mov reg1, mem2
  3668. mov mem2, reg2 mov mem2, reg1
  3669. to: to:
  3670. mov mem1, reg1 mov mem1, reg1
  3671. mov mem1, reg2 mov reg1, mem2
  3672. mov reg1, mem2
  3673. or (if mem1 depends on reg1
  3674. and/or if mem2 depends on reg2)
  3675. to:
  3676. mov mem1, reg1
  3677. mov reg1, mem2
  3678. mov reg1, reg2
  3679. }
  3680. begin
  3681. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3682. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3683. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3684. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3685. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3686. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3687. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3688. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3689. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3690. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3691. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3692. end
  3693. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3694. begin
  3695. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3696. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3697. end
  3698. else
  3699. begin
  3700. RemoveInstruction(hp2);
  3701. end
  3702. {$endif i386}
  3703. ;
  3704. end;
  3705. end
  3706. { movl [mem1],reg1
  3707. movl [mem1],reg2
  3708. to
  3709. movl [mem1],reg1
  3710. movl reg1,reg2
  3711. }
  3712. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3713. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3714. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3715. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3716. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3717. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3718. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3719. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3720. begin
  3721. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3722. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3723. end;
  3724. { movl const1,[mem1]
  3725. movl [mem1],reg1
  3726. to
  3727. movl const1,reg1
  3728. movl reg1,[mem1]
  3729. }
  3730. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3731. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3732. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3733. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3734. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3735. begin
  3736. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3737. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3738. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3739. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3740. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3741. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3742. Result:=true;
  3743. exit;
  3744. end;
  3745. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3746. { Change:
  3747. movl %reg1,%reg2
  3748. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3749. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3750. To:
  3751. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3752. movl x(%reg1),%reg1
  3753. movl %reg1,%regX
  3754. }
  3755. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3756. begin
  3757. p_SourceReg := taicpu(p).oper[0]^.reg;
  3758. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3759. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3760. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3761. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3762. GetNextInstruction(hp1, hp2) and
  3763. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3764. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3765. begin
  3766. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3767. if RegInRef(p_TargetReg, SourceRef) and
  3768. { If %reg1 also appears in the second reference, then it will
  3769. not refer to the same memory block as the first reference }
  3770. not RegInRef(p_SourceReg, SourceRef) then
  3771. begin
  3772. { Check to see if the references match if %reg2 is changed to %reg1 }
  3773. if SourceRef.base = p_TargetReg then
  3774. SourceRef.base := p_SourceReg;
  3775. if SourceRef.index = p_TargetReg then
  3776. SourceRef.index := p_SourceReg;
  3777. { RefsEqual also checks to ensure both references are non-volatile }
  3778. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3779. begin
  3780. taicpu(hp2).loadreg(0, p_SourceReg);
  3781. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3782. Result := True;
  3783. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3784. begin
  3785. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3786. RemoveCurrentP(p, hp1);
  3787. Exit;
  3788. end
  3789. else
  3790. begin
  3791. { Check to see if %reg2 is no longer in use }
  3792. TransferUsedRegs(TmpUsedRegs);
  3793. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3794. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3795. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3796. begin
  3797. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3798. RemoveCurrentP(p, hp1);
  3799. Exit;
  3800. end;
  3801. end;
  3802. { If we reach this point, p and hp1 weren't actually modified,
  3803. so we can do a bit more work on this pass }
  3804. end;
  3805. end;
  3806. end;
  3807. end;
  3808. end;
  3809. {$ifdef x86_64}
  3810. { Change:
  3811. movl %reg1l,%reg2l
  3812. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3813. To:
  3814. movl %reg1l,%reg2l
  3815. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3816. If %reg1 = %reg3, convert to:
  3817. movl %reg1l,%reg2l
  3818. andl %reg1l,%reg1l
  3819. }
  3820. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3821. MatchOpType(taicpu(p), top_reg, top_reg) and
  3822. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3823. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3824. begin
  3825. TransferUsedRegs(TmpUsedRegs);
  3826. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3827. taicpu(hp1).opsize := S_L;
  3828. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3829. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3830. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3831. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3832. begin
  3833. { %reg1 = %reg3 }
  3834. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3835. taicpu(hp1).opcode := A_AND;
  3836. end
  3837. else
  3838. begin
  3839. { %reg1 <> %reg3 }
  3840. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3841. end;
  3842. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3843. begin
  3844. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3845. RemoveCurrentP(p, hp1);
  3846. Result := True;
  3847. Exit;
  3848. end
  3849. else
  3850. begin
  3851. { Initial instruction wasn't actually changed }
  3852. Include(OptsToCheck, aoc_ForceNewIteration);
  3853. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3854. appears below since %reg1 has technically changed }
  3855. if taicpu(hp1).opcode = A_AND then
  3856. Exit;
  3857. end;
  3858. end;
  3859. {$endif x86_64}
  3860. { search further than the next instruction for a mov (as long as it's not a jump) }
  3861. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3862. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3863. (taicpu(p).oper[1]^.typ = top_reg) and
  3864. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3865. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3866. begin
  3867. { we work with hp2 here, so hp1 can be still used later on when
  3868. checking for GetNextInstruction_p }
  3869. hp3 := hp1;
  3870. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3871. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3872. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3873. TransferUsedRegs(TmpUsedRegs);
  3874. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3875. if NotFirstIteration then
  3876. JumpTracking := TLinkedList.Create
  3877. else
  3878. JumpTracking := nil;
  3879. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3880. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3881. (hp2.typ=ait_instruction) do
  3882. begin
  3883. case taicpu(hp2).opcode of
  3884. A_POP:
  3885. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3886. begin
  3887. if not CrossJump and
  3888. not RegUsedBetween(p_TargetReg, p, hp2) then
  3889. begin
  3890. { We can remove the original MOV since the register
  3891. wasn't used between it and its popping from the stack }
  3892. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3893. RemoveCurrentp(p, hp1);
  3894. Result := True;
  3895. JumpTracking.Free;
  3896. Exit;
  3897. end;
  3898. { Can't go any further }
  3899. Break;
  3900. end;
  3901. A_MOV:
  3902. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3903. ((taicpu(p).oper[0]^.typ=top_const) or
  3904. ((taicpu(p).oper[0]^.typ=top_reg) and
  3905. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3906. )
  3907. ) then
  3908. begin
  3909. { we have
  3910. mov x, %treg
  3911. mov %treg, y
  3912. }
  3913. { We don't need to call UpdateUsedRegs for every instruction between
  3914. p and hp2 because the register we're concerned about will not
  3915. become deallocated (otherwise GetNextInstructionUsingReg would
  3916. have stopped at an earlier instruction). [Kit] }
  3917. TempRegUsed :=
  3918. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3919. RegReadByInstruction(p_TargetReg, hp3) or
  3920. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3921. case taicpu(p).oper[0]^.typ Of
  3922. top_reg:
  3923. begin
  3924. { change
  3925. mov %reg, %treg
  3926. mov %treg, y
  3927. to
  3928. mov %reg, y
  3929. }
  3930. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3931. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3932. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3933. begin
  3934. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3935. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3936. if TempRegUsed then
  3937. begin
  3938. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3939. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3940. { Set the start of the next GetNextInstructionUsingRegCond search
  3941. to start at the entry right before hp2 (which is about to be removed) }
  3942. hp3 := tai(hp2.Previous);
  3943. RemoveInstruction(hp2);
  3944. Include(OptsToCheck, aoc_ForceNewIteration);
  3945. { See if there's more we can optimise }
  3946. Continue;
  3947. end
  3948. else
  3949. begin
  3950. RemoveInstruction(hp2);
  3951. { We can remove the original MOV too }
  3952. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3953. RemoveCurrentP(p, hp1);
  3954. Result:=true;
  3955. JumpTracking.Free;
  3956. Exit;
  3957. end;
  3958. end
  3959. else
  3960. begin
  3961. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3962. taicpu(hp2).loadReg(0, p_SourceReg);
  3963. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3964. { Check to see if the register also appears in the reference }
  3965. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3966. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3967. { Don't remove the first instruction if the temporary register is in use }
  3968. if not TempRegUsed and
  3969. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3970. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3971. begin
  3972. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3973. RemoveCurrentP(p, hp1);
  3974. Result:=true;
  3975. JumpTracking.Free;
  3976. Exit;
  3977. end;
  3978. { No need to set Result to True here. If there's another instruction later
  3979. on that can be optimised, it will be detected when the main Pass 1 loop
  3980. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3981. end;
  3982. end;
  3983. top_const:
  3984. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3985. begin
  3986. { change
  3987. mov const, %treg
  3988. mov %treg, y
  3989. to
  3990. mov const, y
  3991. }
  3992. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3993. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3994. begin
  3995. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3996. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3997. if TempRegUsed then
  3998. begin
  3999. { Don't remove the first instruction if the temporary register is in use }
  4000. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4001. { No need to set Result to True. If there's another instruction later on
  4002. that can be optimised, it will be detected when the main Pass 1 loop
  4003. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4004. end
  4005. else
  4006. begin
  4007. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4008. RemoveCurrentP(p, hp1);
  4009. Result:=true;
  4010. Exit;
  4011. end;
  4012. end;
  4013. end;
  4014. else
  4015. Internalerror(2019103001);
  4016. end;
  4017. end
  4018. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4019. begin
  4020. if not CrossJump and
  4021. not RegUsedBetween(p_TargetReg, p, hp2) and
  4022. not RegReadByInstruction(p_TargetReg, hp2) then
  4023. begin
  4024. { Register is not used before it is overwritten }
  4025. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4026. RemoveCurrentp(p, hp1);
  4027. Result := True;
  4028. Exit;
  4029. end;
  4030. if (taicpu(p).oper[0]^.typ = top_const) and
  4031. (taicpu(hp2).oper[0]^.typ = top_const) then
  4032. begin
  4033. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4034. begin
  4035. { Same value - register hasn't changed }
  4036. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4037. RemoveInstruction(hp2);
  4038. Include(OptsToCheck, aoc_ForceNewIteration);
  4039. { See if there's more we can optimise }
  4040. Continue;
  4041. end;
  4042. end;
  4043. {$ifdef x86_64}
  4044. end
  4045. { Change:
  4046. movl %reg1l,%reg2l
  4047. ...
  4048. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4049. To:
  4050. movl %reg1l,%reg2l
  4051. ...
  4052. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4053. If %reg1 = %reg3, convert to:
  4054. movl %reg1l,%reg2l
  4055. ...
  4056. andl %reg1l,%reg1l
  4057. }
  4058. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4059. (taicpu(p).oper[0]^.typ = top_reg) and
  4060. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4061. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4062. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4063. begin
  4064. TempRegUsed :=
  4065. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4066. RegReadByInstruction(p_TargetReg, hp3) or
  4067. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4068. taicpu(hp2).opsize := S_L;
  4069. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4070. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4071. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4072. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4073. begin
  4074. { %reg1 = %reg3 }
  4075. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4076. taicpu(hp2).opcode := A_AND;
  4077. end
  4078. else
  4079. begin
  4080. { %reg1 <> %reg3 }
  4081. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4082. end;
  4083. if not TempRegUsed then
  4084. begin
  4085. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4086. RemoveCurrentP(p, hp1);
  4087. Result := True;
  4088. Exit;
  4089. end
  4090. else
  4091. begin
  4092. { Initial instruction wasn't actually changed }
  4093. Include(OptsToCheck, aoc_ForceNewIteration);
  4094. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4095. appears below since %reg1 has technically changed }
  4096. if taicpu(hp2).opcode = A_AND then
  4097. Break;
  4098. end;
  4099. {$endif x86_64}
  4100. end;
  4101. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4102. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4103. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4104. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4105. begin
  4106. {
  4107. Change from:
  4108. mov ###, %reg
  4109. ...
  4110. movs/z %reg,%reg (Same register, just different sizes)
  4111. To:
  4112. movs/z ###, %reg (Longer version)
  4113. ...
  4114. (remove)
  4115. }
  4116. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4117. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4118. { Keep the first instruction as mov if ### is a constant }
  4119. if taicpu(p).oper[0]^.typ = top_const then
  4120. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4121. else
  4122. begin
  4123. taicpu(p).opcode := taicpu(hp2).opcode;
  4124. taicpu(p).opsize := taicpu(hp2).opsize;
  4125. end;
  4126. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4127. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4128. RemoveInstruction(hp2);
  4129. Result := True;
  4130. JumpTracking.Free;
  4131. Exit;
  4132. end;
  4133. else
  4134. { Move down to the if-block below };
  4135. end;
  4136. { Also catches MOV/S/Z instructions that aren't modified }
  4137. if taicpu(p).oper[0]^.typ = top_reg then
  4138. begin
  4139. p_SourceReg := taicpu(p).oper[0]^.reg;
  4140. if
  4141. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4142. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4143. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4144. begin
  4145. Result := True;
  4146. { Just in case something didn't get modified (e.g. an
  4147. implicit register). Also, if it does read from this
  4148. register, then there's no longer an advantage to
  4149. changing the register on subsequent instructions.}
  4150. if not RegReadByInstruction(p_TargetReg, hp2) then
  4151. begin
  4152. { If a conditional jump was crossed, do not delete
  4153. the original MOV no matter what }
  4154. if not CrossJump and
  4155. { RegEndOfLife returns True if the register is
  4156. deallocated before the next instruction or has
  4157. been loaded with a new value }
  4158. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4159. begin
  4160. { We can remove the original MOV }
  4161. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4162. RemoveCurrentp(p, hp1);
  4163. JumpTracking.Free;
  4164. Result := True;
  4165. Exit;
  4166. end;
  4167. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4168. begin
  4169. { See if there's more we can optimise }
  4170. hp3 := hp2;
  4171. Continue;
  4172. end;
  4173. end;
  4174. end;
  4175. end;
  4176. { Break out of the while loop under normal circumstances }
  4177. Break;
  4178. end;
  4179. JumpTracking.Free;
  4180. end;
  4181. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4182. (taicpu(p).oper[1]^.typ = top_reg) and
  4183. (taicpu(p).opsize = S_L) and
  4184. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4185. (hp2.typ = ait_instruction) and
  4186. (taicpu(hp2).opcode = A_AND) and
  4187. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4188. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4189. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4190. ) then
  4191. begin
  4192. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4193. begin
  4194. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4195. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4196. begin
  4197. { Optimize out:
  4198. mov x, %reg
  4199. and ffffffffh, %reg
  4200. }
  4201. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4202. RemoveInstruction(hp2);
  4203. Result:=true;
  4204. exit;
  4205. end;
  4206. end;
  4207. end;
  4208. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4209. x >= RetOffset) as it doesn't do anything (it writes either to a
  4210. parameter or to the temporary storage room for the function
  4211. result)
  4212. }
  4213. if IsExitCode(hp1) and
  4214. (taicpu(p).oper[1]^.typ = top_ref) and
  4215. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4216. (
  4217. (
  4218. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4219. not (
  4220. assigned(current_procinfo.procdef.funcretsym) and
  4221. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4222. )
  4223. ) or
  4224. { Also discard writes to the stack that are below the base pointer,
  4225. as this is temporary storage rather than a function result on the
  4226. stack, say. }
  4227. (
  4228. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4229. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4230. )
  4231. ) then
  4232. begin
  4233. RemoveCurrentp(p, hp1);
  4234. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4235. RemoveLastDeallocForFuncRes(p);
  4236. Result:=true;
  4237. exit;
  4238. end;
  4239. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4240. begin
  4241. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4242. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4243. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4244. begin
  4245. { change
  4246. mov reg1, mem1
  4247. test/cmp x, mem1
  4248. to
  4249. mov reg1, mem1
  4250. test/cmp x, reg1
  4251. }
  4252. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4253. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4254. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4255. Result := True;
  4256. Exit;
  4257. end;
  4258. if DoMovCmpMemOpt(p, hp1) then
  4259. begin
  4260. Result := True;
  4261. Exit;
  4262. end;
  4263. end;
  4264. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4265. { If the flags register is in use, don't change the instruction to an
  4266. ADD otherwise this will scramble the flags. [Kit] }
  4267. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4268. begin
  4269. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4270. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4271. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4272. ) or
  4273. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4274. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4275. )
  4276. ) then
  4277. { mov reg1,ref
  4278. lea reg2,[reg1,reg2]
  4279. to
  4280. add reg2,ref}
  4281. begin
  4282. TransferUsedRegs(TmpUsedRegs);
  4283. { reg1 may not be used afterwards }
  4284. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4285. begin
  4286. Taicpu(hp1).opcode:=A_ADD;
  4287. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4288. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4289. RemoveCurrentp(p, hp1);
  4290. result:=true;
  4291. exit;
  4292. end;
  4293. end;
  4294. { If the LEA instruction can be converted into an arithmetic instruction,
  4295. it may be possible to then fold it in the next optimisation, otherwise
  4296. there's nothing more that can be optimised here. }
  4297. if not ConvertLEA(taicpu(hp1)) then
  4298. Exit;
  4299. end;
  4300. if (taicpu(p).oper[1]^.typ = top_reg) and
  4301. (hp1.typ = ait_instruction) and
  4302. GetNextInstruction(hp1, hp2) and
  4303. MatchInstruction(hp2,A_MOV,[]) and
  4304. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4305. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4306. (
  4307. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4308. {$ifdef x86_64}
  4309. or
  4310. (
  4311. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4312. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4313. )
  4314. {$endif x86_64}
  4315. ) then
  4316. begin
  4317. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4318. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4319. { change movsX/movzX reg/ref, reg2
  4320. add/sub/or/... reg3/$const, reg2
  4321. mov reg2 reg/ref
  4322. dealloc reg2
  4323. to
  4324. add/sub/or/... reg3/$const, reg/ref }
  4325. begin
  4326. TransferUsedRegs(TmpUsedRegs);
  4327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4328. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4329. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4330. begin
  4331. { by example:
  4332. movswl %si,%eax movswl %si,%eax p
  4333. decl %eax addl %edx,%eax hp1
  4334. movw %ax,%si movw %ax,%si hp2
  4335. ->
  4336. movswl %si,%eax movswl %si,%eax p
  4337. decw %eax addw %edx,%eax hp1
  4338. movw %ax,%si movw %ax,%si hp2
  4339. }
  4340. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4341. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4342. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4343. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4344. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4345. {
  4346. ->
  4347. movswl %si,%eax movswl %si,%eax p
  4348. decw %si addw %dx,%si hp1
  4349. movw %ax,%si movw %ax,%si hp2
  4350. }
  4351. case taicpu(hp1).ops of
  4352. 1:
  4353. begin
  4354. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4355. if taicpu(hp1).oper[0]^.typ=top_reg then
  4356. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4357. end;
  4358. 2:
  4359. begin
  4360. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4361. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4362. (taicpu(hp1).opcode<>A_SHL) and
  4363. (taicpu(hp1).opcode<>A_SHR) and
  4364. (taicpu(hp1).opcode<>A_SAR) then
  4365. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4366. end;
  4367. else
  4368. internalerror(2008042701);
  4369. end;
  4370. {
  4371. ->
  4372. decw %si addw %dx,%si p
  4373. }
  4374. RemoveInstruction(hp2);
  4375. RemoveCurrentP(p, hp1);
  4376. Result:=True;
  4377. Exit;
  4378. end;
  4379. end;
  4380. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4381. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4382. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4383. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4384. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4385. )
  4386. {$ifdef i386}
  4387. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4388. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4389. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4390. {$endif i386}
  4391. then
  4392. { change movsX/movzX reg/ref, reg2
  4393. add/sub/or/... regX/$const, reg2
  4394. mov reg2, reg3
  4395. dealloc reg2
  4396. to
  4397. movsX/movzX reg/ref, reg3
  4398. add/sub/or/... reg3/$const, reg3
  4399. }
  4400. begin
  4401. TransferUsedRegs(TmpUsedRegs);
  4402. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4403. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4404. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4405. begin
  4406. { by example:
  4407. movswl %si,%eax movswl %si,%eax p
  4408. decl %eax addl %edx,%eax hp1
  4409. movw %ax,%si movw %ax,%si hp2
  4410. ->
  4411. movswl %si,%eax movswl %si,%eax p
  4412. decw %eax addw %edx,%eax hp1
  4413. movw %ax,%si movw %ax,%si hp2
  4414. }
  4415. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4416. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4417. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4418. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4419. { limit size of constants as well to avoid assembler errors, but
  4420. check opsize to avoid overflow when left shifting the 1 }
  4421. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4422. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4423. {$ifdef x86_64}
  4424. { Be careful of, for example:
  4425. movl %reg1,%reg2
  4426. addl %reg3,%reg2
  4427. movq %reg2,%reg4
  4428. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4429. }
  4430. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4431. begin
  4432. taicpu(hp2).changeopsize(S_L);
  4433. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4434. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4435. end;
  4436. {$endif x86_64}
  4437. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4438. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4439. if taicpu(p).oper[0]^.typ=top_reg then
  4440. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4441. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4442. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4443. {
  4444. ->
  4445. movswl %si,%eax movswl %si,%eax p
  4446. decw %si addw %dx,%si hp1
  4447. movw %ax,%si movw %ax,%si hp2
  4448. }
  4449. case taicpu(hp1).ops of
  4450. 1:
  4451. begin
  4452. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4453. if taicpu(hp1).oper[0]^.typ=top_reg then
  4454. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4455. end;
  4456. 2:
  4457. begin
  4458. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4459. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4460. (taicpu(hp1).opcode<>A_SHL) and
  4461. (taicpu(hp1).opcode<>A_SHR) and
  4462. (taicpu(hp1).opcode<>A_SAR) then
  4463. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4464. end;
  4465. else
  4466. internalerror(2018111801);
  4467. end;
  4468. {
  4469. ->
  4470. decw %si addw %dx,%si p
  4471. }
  4472. RemoveInstruction(hp2);
  4473. end;
  4474. end;
  4475. end;
  4476. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4477. GetNextInstruction(hp1, hp2) and
  4478. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4479. MatchOperand(Taicpu(p).oper[0]^,0) and
  4480. (Taicpu(p).oper[1]^.typ = top_reg) and
  4481. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4482. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4483. { mov reg1,0
  4484. bts reg1,operand1 --> mov reg1,operand2
  4485. or reg1,operand2 bts reg1,operand1}
  4486. begin
  4487. Taicpu(hp2).opcode:=A_MOV;
  4488. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4489. asml.remove(hp1);
  4490. insertllitem(hp2,hp2.next,hp1);
  4491. RemoveCurrentp(p, hp1);
  4492. Result:=true;
  4493. exit;
  4494. end;
  4495. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4496. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4497. GetNextInstruction(hp1, hp2) and
  4498. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4499. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4500. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4501. { change
  4502. mov reg1,reg2
  4503. sub reg3,reg2
  4504. cmp reg3,reg1
  4505. into
  4506. mov reg1,reg2
  4507. sub reg3,reg2
  4508. }
  4509. begin
  4510. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4511. RemoveInstruction(hp2);
  4512. Result:=true;
  4513. exit;
  4514. end;
  4515. {
  4516. mov ref,reg0
  4517. <op> reg0,reg1
  4518. dealloc reg0
  4519. to
  4520. <op> ref,reg1
  4521. }
  4522. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4523. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4524. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4525. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4526. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4527. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4528. begin
  4529. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4530. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4531. RemoveCurrentp(p, hp1);
  4532. Result:=true;
  4533. exit;
  4534. end;
  4535. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4536. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4537. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4538. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4539. begin
  4540. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4541. {$ifdef x86_64}
  4542. { Convert:
  4543. movq x(ref),%reg64
  4544. shrq y,%reg64
  4545. To:
  4546. movl x+4(ref),%reg32
  4547. shrl y-32,%reg32 (Remove if y = 32)
  4548. }
  4549. if (taicpu(p).opsize = S_Q) and
  4550. (taicpu(hp1).opcode = A_SHR) and
  4551. (taicpu(hp1).oper[0]^.val >= 32) then
  4552. begin
  4553. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4554. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4555. { Convert to 32-bit }
  4556. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4557. taicpu(p).opsize := S_L;
  4558. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4559. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4560. if (taicpu(hp1).oper[0]^.val = 32) then
  4561. begin
  4562. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4563. RemoveInstruction(hp1);
  4564. end
  4565. else
  4566. begin
  4567. { This will potentially open up more arithmetic operations since
  4568. the peephole optimizer now has a big hint that only the lower
  4569. 32 bits are currently in use (and opcodes are smaller in size) }
  4570. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4571. taicpu(hp1).opsize := S_L;
  4572. Dec(taicpu(hp1).oper[0]^.val, 32);
  4573. DebugMsg(SPeepholeOptimization + PreMessage +
  4574. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4575. end;
  4576. Result := True;
  4577. Exit;
  4578. end;
  4579. {$endif x86_64}
  4580. { Convert:
  4581. movl x(ref),%reg
  4582. shrl $24,%reg
  4583. To:
  4584. movzbl x+3(ref),%reg
  4585. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4586. Also accept sar instead of shr, but convert to movsx instead of movzx
  4587. }
  4588. if taicpu(hp1).opcode = A_SHR then
  4589. MovUnaligned := A_MOVZX
  4590. else
  4591. MovUnaligned := A_MOVSX;
  4592. NewSize := S_NO;
  4593. NewOffset := 0;
  4594. case taicpu(p).opsize of
  4595. S_B:
  4596. { No valid combinations };
  4597. S_W:
  4598. if (taicpu(hp1).oper[0]^.val = 8) then
  4599. begin
  4600. NewSize := S_BW;
  4601. NewOffset := 1;
  4602. end;
  4603. S_L:
  4604. case taicpu(hp1).oper[0]^.val of
  4605. 16:
  4606. begin
  4607. NewSize := S_WL;
  4608. NewOffset := 2;
  4609. end;
  4610. 24:
  4611. begin
  4612. NewSize := S_BL;
  4613. NewOffset := 3;
  4614. end;
  4615. else
  4616. ;
  4617. end;
  4618. {$ifdef x86_64}
  4619. S_Q:
  4620. case taicpu(hp1).oper[0]^.val of
  4621. 32:
  4622. begin
  4623. if taicpu(hp1).opcode = A_SAR then
  4624. begin
  4625. { 32-bit to 64-bit is a distinct instruction }
  4626. MovUnaligned := A_MOVSXD;
  4627. NewSize := S_LQ;
  4628. NewOffset := 4;
  4629. end
  4630. else
  4631. { Should have been handled by MovShr2Mov above }
  4632. InternalError(2022081811);
  4633. end;
  4634. 48:
  4635. begin
  4636. NewSize := S_WQ;
  4637. NewOffset := 6;
  4638. end;
  4639. 56:
  4640. begin
  4641. NewSize := S_BQ;
  4642. NewOffset := 7;
  4643. end;
  4644. else
  4645. ;
  4646. end;
  4647. {$endif x86_64}
  4648. else
  4649. InternalError(2022081810);
  4650. end;
  4651. if (NewSize <> S_NO) and
  4652. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4653. begin
  4654. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4655. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4656. debug_op2str(MovUnaligned);
  4657. {$ifdef x86_64}
  4658. if MovUnaligned <> A_MOVSXD then
  4659. { Don't add size suffix for MOVSXD }
  4660. {$endif x86_64}
  4661. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4662. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4663. taicpu(p).opcode := MovUnaligned;
  4664. taicpu(p).opsize := NewSize;
  4665. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4666. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4667. RemoveInstruction(hp1);
  4668. Result := True;
  4669. Exit;
  4670. end;
  4671. end;
  4672. { Backward optimisation shared with OptPass2MOV }
  4673. if FuncMov2Func(p, hp1) then
  4674. begin
  4675. Result := True;
  4676. Exit;
  4677. end;
  4678. end;
  4679. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4680. var
  4681. hp1 : tai;
  4682. begin
  4683. Result:=false;
  4684. if taicpu(p).ops <> 2 then
  4685. exit;
  4686. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4687. GetNextInstruction(p,hp1) then
  4688. begin
  4689. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4690. (taicpu(hp1).ops = 2) then
  4691. begin
  4692. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4693. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4694. { movXX reg1, mem1 or movXX mem1, reg1
  4695. movXX mem2, reg2 movXX reg2, mem2}
  4696. begin
  4697. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4698. { movXX reg1, mem1 or movXX mem1, reg1
  4699. movXX mem2, reg1 movXX reg2, mem1}
  4700. begin
  4701. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4702. begin
  4703. { Removes the second statement from
  4704. movXX reg1, mem1/reg2
  4705. movXX mem1/reg2, reg1
  4706. }
  4707. if taicpu(p).oper[0]^.typ=top_reg then
  4708. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4709. { Removes the second statement from
  4710. movXX mem1/reg1, reg2
  4711. movXX reg2, mem1/reg1
  4712. }
  4713. if (taicpu(p).oper[1]^.typ=top_reg) and
  4714. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4715. begin
  4716. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4717. RemoveInstruction(hp1);
  4718. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4719. Result:=true;
  4720. exit;
  4721. end
  4722. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4723. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4724. begin
  4725. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4726. RemoveInstruction(hp1);
  4727. Result:=true;
  4728. exit;
  4729. end;
  4730. end
  4731. end;
  4732. end;
  4733. end;
  4734. end;
  4735. end;
  4736. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4737. var
  4738. hp1 : tai;
  4739. begin
  4740. result:=false;
  4741. { replace
  4742. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4743. MovX %mreg2,%mreg1
  4744. dealloc %mreg2
  4745. by
  4746. <Op>X %mreg2,%mreg1
  4747. ?
  4748. }
  4749. if GetNextInstruction(p,hp1) and
  4750. { we mix single and double opperations here because we assume that the compiler
  4751. generates vmovapd only after double operations and vmovaps only after single operations }
  4752. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4753. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4754. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4755. (taicpu(p).oper[0]^.typ=top_reg) then
  4756. begin
  4757. TransferUsedRegs(TmpUsedRegs);
  4758. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4759. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4760. begin
  4761. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4762. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4763. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4764. RemoveInstruction(hp1);
  4765. result:=true;
  4766. end;
  4767. end;
  4768. end;
  4769. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4770. var
  4771. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4772. JumpLabel, JumpLabel_dist: TAsmLabel;
  4773. FirstValue, SecondValue: TCGInt;
  4774. TempBool: Boolean;
  4775. begin
  4776. Result := False;
  4777. if (taicpu(p).oper[0]^.typ = top_const) and
  4778. (taicpu(p).oper[0]^.val <> -1) then
  4779. begin
  4780. { Convert unsigned maximum constants to -1 to aid optimisation }
  4781. case taicpu(p).opsize of
  4782. S_B:
  4783. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4784. begin
  4785. taicpu(p).oper[0]^.val := -1;
  4786. Result := True;
  4787. Exit;
  4788. end;
  4789. S_W:
  4790. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4791. begin
  4792. taicpu(p).oper[0]^.val := -1;
  4793. Result := True;
  4794. Exit;
  4795. end;
  4796. S_L:
  4797. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4798. begin
  4799. taicpu(p).oper[0]^.val := -1;
  4800. Result := True;
  4801. Exit;
  4802. end;
  4803. {$ifdef x86_64}
  4804. S_Q:
  4805. { Storing anything greater than $7FFFFFFF is not possible so do
  4806. nothing };
  4807. {$endif x86_64}
  4808. else
  4809. InternalError(2021121001);
  4810. end;
  4811. end;
  4812. if GetNextInstruction(p, hp1) and
  4813. TrySwapMovCmp(p, hp1) then
  4814. begin
  4815. Result := True;
  4816. Exit;
  4817. end;
  4818. if MatchInstruction(hp1, A_Jcc, []) then
  4819. begin
  4820. TempBool := True;
  4821. if DoJumpOptimizations(hp1, TempBool) or
  4822. not TempBool then
  4823. begin
  4824. Result := True;
  4825. if Assigned(hp1) then
  4826. begin
  4827. if (hp1.typ in [ait_align]) then
  4828. SkipAligns(hp1, hp1);
  4829. { CollapseZeroDistJump will be set to the label after the
  4830. jump if it optimises, whether or not it's live or dead }
  4831. if (hp1.typ in [ait_label]) and
  4832. not (tai_label(hp1).labsym.is_used) then
  4833. GetNextInstruction(hp1, hp1);
  4834. end;
  4835. TransferUsedRegs(TmpUsedRegs);
  4836. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4837. if not Assigned(hp1) or
  4838. (
  4839. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4840. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4841. ) then
  4842. begin
  4843. { No more conditional jumps; conditional statement is no longer required }
  4844. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4845. RemoveCurrentP(p);
  4846. end;
  4847. Exit;
  4848. end;
  4849. end;
  4850. { Search for:
  4851. test $x,(reg/ref)
  4852. jne @lbl1
  4853. test $y,(reg/ref) (same register or reference)
  4854. jne @lbl1
  4855. Change to:
  4856. test $(x or y),(reg/ref)
  4857. jne @lbl1
  4858. (Note, this doesn't work with je instead of jne)
  4859. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4860. Also search for:
  4861. test $x,(reg/ref)
  4862. je @lbl1
  4863. ...
  4864. test $y,(reg/ref)
  4865. je/jne @lbl2
  4866. If (x or y) = x, then the second jump is deterministic
  4867. }
  4868. if (
  4869. (
  4870. (taicpu(p).oper[0]^.typ = top_const) or
  4871. (
  4872. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4873. (taicpu(p).oper[0]^.typ = top_reg) and
  4874. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4875. )
  4876. ) and
  4877. MatchInstruction(hp1, A_JCC, [])
  4878. ) then
  4879. begin
  4880. if (taicpu(p).oper[0]^.typ = top_reg) and
  4881. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4882. FirstValue := -1
  4883. else
  4884. FirstValue := taicpu(p).oper[0]^.val;
  4885. { If we have several test/jne's in a row, it might be the case that
  4886. the second label doesn't go to the same location, but the one
  4887. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4888. so accommodate for this with a while loop.
  4889. }
  4890. hp1_last := hp1;
  4891. while (
  4892. (
  4893. (taicpu(p).oper[1]^.typ = top_reg) and
  4894. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4895. ) or GetNextInstruction(hp1_last, p_dist)
  4896. ) and (p_dist.typ = ait_instruction) do
  4897. begin
  4898. if (
  4899. (
  4900. (taicpu(p_dist).opcode = A_TEST) and
  4901. (
  4902. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4903. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4904. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4905. )
  4906. ) or
  4907. (
  4908. { cmp 0,%reg = test %reg,%reg }
  4909. (taicpu(p_dist).opcode = A_CMP) and
  4910. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4911. )
  4912. ) and
  4913. { Make sure the destination operands are actually the same }
  4914. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4915. GetNextInstruction(p_dist, hp1_dist) and
  4916. MatchInstruction(hp1_dist, A_JCC, []) then
  4917. begin
  4918. if
  4919. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4920. (
  4921. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4922. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4923. ) then
  4924. SecondValue := -1
  4925. else
  4926. SecondValue := taicpu(p_dist).oper[0]^.val;
  4927. { If both of the TEST constants are identical, delete the
  4928. second TEST that is unnecessary (be careful though, just
  4929. in case the flags are modified in between) }
  4930. if (FirstValue = SecondValue) then
  4931. begin
  4932. { We have to check the entire range }
  4933. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4934. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4935. begin
  4936. { Since the second jump's condition is a subset of the first, we
  4937. know it will never branch because the first jump dominates it.
  4938. Get it out of the way now rather than wait for the jump
  4939. optimisations for a speed boost. }
  4940. if IsJumpToLabel(taicpu(hp1_dist)) then
  4941. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4942. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4943. RemoveInstruction(hp1_dist);
  4944. Result := True;
  4945. end
  4946. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4947. begin
  4948. { If the inverse of the first condition is a subset of the second,
  4949. the second one will definitely branch if the first one doesn't }
  4950. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4951. { We can remove the TEST instruction too }
  4952. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4953. RemoveInstruction(p_dist);
  4954. MakeUnconditional(taicpu(hp1_dist));
  4955. RemoveDeadCodeAfterJump(hp1_dist);
  4956. { Since the jump is now unconditional, we can't
  4957. continue any further with this particular
  4958. optimisation. The original TEST is still intact
  4959. though, so there might be something else we can
  4960. do }
  4961. Include(OptsToCheck, aoc_ForceNewIteration);
  4962. Break;
  4963. end;
  4964. if Result or
  4965. { If a jump wasn't removed or made unconditional, only
  4966. remove the identical TEST instruction if the flags
  4967. weren't modified }
  4968. TempBool then
  4969. begin
  4970. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4971. RemoveInstruction(p_dist);
  4972. { If the jump was removed or made unconditional, we
  4973. don't need to allocate NR_DEFAULTFLAGS over the
  4974. entire range }
  4975. if not Result then
  4976. begin
  4977. { Mark the flags as 'in use' over the entire range }
  4978. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4979. { Speed gain - continue search from the Jcc instruction }
  4980. hp1_last := hp1_dist;
  4981. { Only the TEST instruction was removed, and the
  4982. original was unchanged, so we can safely do
  4983. another iteration of the while loop }
  4984. Include(OptsToCheck, aoc_ForceNewIteration);
  4985. Continue;
  4986. end;
  4987. Exit;
  4988. end;
  4989. end;
  4990. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4991. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4992. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4993. then the second jump will never branch, so it can also be
  4994. removed regardless of where it goes }
  4995. (
  4996. (FirstValue = -1) or
  4997. (SecondValue = -1) or
  4998. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4999. ) and
  5000. (
  5001. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5002. { Always adjacent under -O2 and under }
  5003. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5004. (
  5005. GetNextInstruction(hp1, hp1_last) and
  5006. (hp1_last = p_dist)
  5007. )
  5008. ) then
  5009. begin
  5010. { Same jump location... can be a register since nothing's changed }
  5011. { If any of the entries are equivalent to test %reg,%reg, then the
  5012. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5013. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5014. if IsJumpToLabel(taicpu(hp1_dist)) then
  5015. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5016. { Only remove the second test if no jumps or other conditional instructions follow }
  5017. TransferUsedRegs(TmpUsedRegs);
  5018. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5019. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5020. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5021. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5022. begin
  5023. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5024. RemoveInstruction(p_dist);
  5025. { Remove the first jump, not the second, to keep
  5026. any register deallocations between the second
  5027. TEST/JNE pair in the same place. Aids future
  5028. optimisation. }
  5029. RemoveInstruction(hp1);
  5030. end
  5031. else
  5032. begin
  5033. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5034. { Remove second jump in this instance }
  5035. RemoveInstruction(hp1_dist);
  5036. end;
  5037. Result := True;
  5038. Exit;
  5039. end;
  5040. end;
  5041. if { If -O2 and under, it may stop on any old instruction }
  5042. (cs_opt_level3 in current_settings.optimizerswitches) and
  5043. (taicpu(p).oper[1]^.typ = top_reg) and
  5044. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5045. begin
  5046. hp1_last := p_dist;
  5047. Continue;
  5048. end;
  5049. Break;
  5050. end;
  5051. end;
  5052. { Search for:
  5053. test %reg,%reg
  5054. j(c1) @lbl1
  5055. ...
  5056. @lbl:
  5057. test %reg,%reg (same register)
  5058. j(c2) @lbl2
  5059. If c2 is a subset of c1, change to:
  5060. test %reg,%reg
  5061. j(c1) @lbl2
  5062. (@lbl1 may become a dead label as a result)
  5063. }
  5064. if (taicpu(p).oper[1]^.typ = top_reg) and
  5065. (taicpu(p).oper[0]^.typ = top_reg) and
  5066. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5067. MatchInstruction(hp1, A_JCC, []) and
  5068. IsJumpToLabel(taicpu(hp1)) then
  5069. begin
  5070. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5071. p_label := nil;
  5072. if Assigned(JumpLabel) then
  5073. p_label := getlabelwithsym(JumpLabel);
  5074. if Assigned(p_label) and
  5075. GetNextInstruction(p_label, p_dist) and
  5076. MatchInstruction(p_dist, A_TEST, []) and
  5077. { It's fine if the second test uses smaller sub-registers }
  5078. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5079. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5080. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5081. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5082. GetNextInstruction(p_dist, hp1_dist) and
  5083. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5084. begin
  5085. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5086. if JumpLabel = JumpLabel_dist then
  5087. { This is an infinite loop }
  5088. Exit;
  5089. { Best optimisation when the first condition is a subset (or equal) of the second }
  5090. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5091. begin
  5092. { Any registers used here will already be allocated }
  5093. if Assigned(JumpLabel) then
  5094. JumpLabel.DecRefs;
  5095. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5096. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5097. Result := True;
  5098. Exit;
  5099. end;
  5100. end;
  5101. end;
  5102. end;
  5103. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5104. var
  5105. hp1, hp2: tai;
  5106. ActiveReg: TRegister;
  5107. OldOffset: asizeint;
  5108. ThisConst: TCGInt;
  5109. function RegDeallocated: Boolean;
  5110. begin
  5111. TransferUsedRegs(TmpUsedRegs);
  5112. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5113. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5114. end;
  5115. begin
  5116. result:=false;
  5117. hp1 := nil;
  5118. { replace
  5119. addX const,%reg1
  5120. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5121. dealloc %reg1
  5122. by
  5123. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5124. }
  5125. if MatchOpType(taicpu(p),top_const,top_reg) then
  5126. begin
  5127. ActiveReg := taicpu(p).oper[1]^.reg;
  5128. { Ensures the entire register was updated }
  5129. if (taicpu(p).opsize >= S_L) and
  5130. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5131. MatchInstruction(hp1,A_LEA,[]) and
  5132. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5133. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5134. (
  5135. { Cover the case where the register in the reference is also the destination register }
  5136. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5137. (
  5138. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5139. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5140. RegDeallocated
  5141. )
  5142. ) then
  5143. begin
  5144. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5145. {$push}
  5146. {$R-}{$Q-}
  5147. { Explicitly disable overflow checking for these offset calculation
  5148. as those do not matter for the final result }
  5149. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5150. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5151. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5152. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5153. {$pop}
  5154. {$ifdef x86_64}
  5155. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5156. begin
  5157. { Overflow; abort }
  5158. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5159. end
  5160. else
  5161. {$endif x86_64}
  5162. begin
  5163. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5164. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5165. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5166. RemoveCurrentP(p, hp1)
  5167. else
  5168. RemoveCurrentP(p);
  5169. result:=true;
  5170. Exit;
  5171. end;
  5172. end;
  5173. if (
  5174. { Save calling GetNextInstructionUsingReg again }
  5175. Assigned(hp1) or
  5176. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5177. ) and
  5178. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5179. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5180. begin
  5181. if taicpu(hp1).oper[0]^.typ = top_const then
  5182. begin
  5183. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5184. if taicpu(hp1).opcode = A_ADD then
  5185. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5186. else
  5187. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5188. Result := True;
  5189. { Handle any overflows }
  5190. case taicpu(p).opsize of
  5191. S_B:
  5192. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5193. S_W:
  5194. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5195. S_L:
  5196. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5197. {$ifdef x86_64}
  5198. S_Q:
  5199. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5200. { Overflow; abort }
  5201. Result := False
  5202. else
  5203. taicpu(p).oper[0]^.val := ThisConst;
  5204. {$endif x86_64}
  5205. else
  5206. InternalError(2021102610);
  5207. end;
  5208. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5209. if Result then
  5210. begin
  5211. if (taicpu(p).oper[0]^.val < 0) and
  5212. (
  5213. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5214. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5215. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5216. ) then
  5217. begin
  5218. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5219. taicpu(p).opcode := A_SUB;
  5220. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5221. end
  5222. else
  5223. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5224. RemoveInstruction(hp1);
  5225. end;
  5226. end
  5227. else
  5228. begin
  5229. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5230. TransferUsedRegs(TmpUsedRegs);
  5231. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5232. hp2 := p;
  5233. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5234. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5235. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5236. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5237. begin
  5238. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5239. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5240. Asml.Remove(p);
  5241. Asml.InsertAfter(p, hp1);
  5242. p := hp1;
  5243. Result := True;
  5244. Exit;
  5245. end;
  5246. end;
  5247. end;
  5248. if DoArithCombineOpt(p) then
  5249. Result:=true;
  5250. end;
  5251. end;
  5252. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5253. var
  5254. hp1, hp2: tai;
  5255. ref: Integer;
  5256. saveref: treference;
  5257. offsetcalc: Int64;
  5258. TempReg: TRegister;
  5259. Multiple: TCGInt;
  5260. Adjacent, IntermediateRegDiscarded: Boolean;
  5261. begin
  5262. Result:=false;
  5263. { play save and throw an error if LEA uses a seg register prefix,
  5264. this is most likely an error somewhere else }
  5265. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5266. internalerror(2022022001);
  5267. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5268. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5269. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5270. (
  5271. { do not mess with leas accessing the stack pointer
  5272. unless it's a null operation }
  5273. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5274. (
  5275. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5276. (taicpu(p).oper[0]^.ref^.offset = 0)
  5277. )
  5278. ) and
  5279. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5280. begin
  5281. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5282. begin
  5283. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5284. begin
  5285. taicpu(p).opcode := A_MOV;
  5286. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5287. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5288. end
  5289. else
  5290. begin
  5291. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5292. RemoveCurrentP(p);
  5293. end;
  5294. Result:=true;
  5295. exit;
  5296. end
  5297. else if (
  5298. { continue to use lea to adjust the stack pointer,
  5299. it is the recommended way, but only if not optimizing for size }
  5300. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5301. (cs_opt_size in current_settings.optimizerswitches)
  5302. ) and
  5303. { If the flags register is in use, don't change the instruction
  5304. to an ADD otherwise this will scramble the flags. [Kit] }
  5305. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5306. ConvertLEA(taicpu(p)) then
  5307. begin
  5308. Result:=true;
  5309. exit;
  5310. end;
  5311. end;
  5312. { Don't optimise if the stack or frame pointer is the destination register }
  5313. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5314. Exit;
  5315. if GetNextInstruction(p,hp1) and
  5316. (hp1.typ=ait_instruction) then
  5317. begin
  5318. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5319. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5320. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5321. begin
  5322. TransferUsedRegs(TmpUsedRegs);
  5323. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5324. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5325. begin
  5326. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5327. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5328. RemoveInstruction(hp1);
  5329. result:=true;
  5330. exit;
  5331. end;
  5332. end;
  5333. { changes
  5334. lea <ref1>, reg1
  5335. <op> ...,<ref. with reg1>,...
  5336. to
  5337. <op> ...,<ref1>,... }
  5338. { find a reference which uses reg1 }
  5339. 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
  5340. ref:=0
  5341. 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
  5342. ref:=1
  5343. else
  5344. ref:=-1;
  5345. if (ref<>-1) and
  5346. { reg1 must be either the base or the index }
  5347. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5348. begin
  5349. { reg1 can be removed from the reference }
  5350. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5351. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5352. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5353. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5354. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5355. else
  5356. Internalerror(2019111201);
  5357. { check if the can insert all data of the lea into the second instruction }
  5358. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5359. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5360. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5361. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5362. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5363. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5364. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5365. {$ifdef x86_64}
  5366. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5367. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5368. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5369. )
  5370. {$endif x86_64}
  5371. then
  5372. begin
  5373. { reg1 might not used by the second instruction after it is remove from the reference }
  5374. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5375. begin
  5376. TransferUsedRegs(TmpUsedRegs);
  5377. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5378. { reg1 is not updated so it might not be used afterwards }
  5379. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5380. begin
  5381. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5382. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5383. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5384. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5385. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5386. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5387. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5388. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5389. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5390. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5391. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5392. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5393. RemoveCurrentP(p, hp1);
  5394. result:=true;
  5395. exit;
  5396. end
  5397. end;
  5398. end;
  5399. { recover }
  5400. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5401. end;
  5402. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5403. if Adjacent or
  5404. { Check further ahead (up to 2 instructions ahead for -O2) }
  5405. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5406. begin
  5407. { Check common LEA/LEA conditions }
  5408. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5409. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5410. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5411. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5412. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5413. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5414. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5415. (
  5416. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5417. calling it (since it calls GetNextInstruction) }
  5418. Adjacent or
  5419. (
  5420. (
  5421. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5422. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5423. ) and (
  5424. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5425. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5426. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5427. )
  5428. )
  5429. ) then
  5430. begin
  5431. TransferUsedRegs(TmpUsedRegs);
  5432. hp2 := p;
  5433. repeat
  5434. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5435. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5436. IntermediateRegDiscarded :=
  5437. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5438. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5439. { changes
  5440. lea offset1(regX,scale), reg1
  5441. lea offset2(reg1,reg1), reg2
  5442. to
  5443. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5444. and
  5445. lea offset1(regX,scale1), reg1
  5446. lea offset2(reg1,scale2), reg2
  5447. to
  5448. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5449. and
  5450. lea offset1(regX,scale1), reg1
  5451. lea offset2(reg3,reg1,scale2), reg2
  5452. to
  5453. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5454. ... so long as the final scale does not exceed 8
  5455. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5456. }
  5457. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5458. (
  5459. { Don't optimise if size is a concern and the intermediate register remains in use }
  5460. IntermediateRegDiscarded or
  5461. not (cs_opt_size in current_settings.optimizerswitches)
  5462. ) and
  5463. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5464. (
  5465. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5466. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5467. ) and (
  5468. (
  5469. { lea (reg1,scale2), reg2 variant }
  5470. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5471. (
  5472. Adjacent or
  5473. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5474. ) and
  5475. (
  5476. (
  5477. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5478. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5479. ) or (
  5480. { lea (regX,regX), reg1 variant }
  5481. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5482. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5483. )
  5484. )
  5485. ) or (
  5486. { lea (reg1,reg1), reg1 variant }
  5487. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5488. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5489. )
  5490. ) then
  5491. begin
  5492. { Make everything homogeneous to make calculations easier }
  5493. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5494. begin
  5495. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5496. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5497. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5498. else
  5499. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5500. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5501. end;
  5502. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5503. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5504. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5505. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5506. begin
  5507. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5508. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5509. begin
  5510. { Put the register to change in the index register }
  5511. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5512. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5513. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5514. end;
  5515. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5516. begin
  5517. { Just to prevent miscalculations }
  5518. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5519. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5520. else
  5521. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5522. end
  5523. else
  5524. begin
  5525. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5526. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5527. end;
  5528. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5529. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5530. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5531. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5532. if IntermediateRegDiscarded then
  5533. begin
  5534. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5535. RemoveCurrentP(p);
  5536. end
  5537. else
  5538. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5539. result:=true;
  5540. exit;
  5541. end;
  5542. end;
  5543. { changes
  5544. lea offset1(regX), reg1
  5545. lea offset2(reg1), reg2
  5546. to
  5547. lea offset1+offset2(regX), reg2 }
  5548. if (
  5549. { Don't optimise if size is a concern and the intermediate register remains in use }
  5550. IntermediateRegDiscarded or
  5551. not (cs_opt_size in current_settings.optimizerswitches)
  5552. ) and
  5553. (
  5554. (
  5555. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5556. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5557. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5558. ) or (
  5559. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5560. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5561. (
  5562. (
  5563. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5564. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5565. ) or (
  5566. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5567. (
  5568. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5569. (
  5570. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5571. (
  5572. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5573. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5574. )
  5575. )
  5576. )
  5577. )
  5578. )
  5579. )
  5580. ) then
  5581. begin
  5582. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5583. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5584. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5585. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5586. begin
  5587. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5588. begin
  5589. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5590. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5591. { if the register is used as index and base, we have to increase for base as well
  5592. and adapt base }
  5593. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5594. begin
  5595. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5596. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5597. end;
  5598. end
  5599. else
  5600. begin
  5601. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5602. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5603. end;
  5604. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5605. begin
  5606. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5607. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5608. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5609. end;
  5610. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5611. if IntermediateRegDiscarded then
  5612. begin
  5613. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5614. RemoveCurrentP(p);
  5615. end
  5616. else
  5617. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5618. result:=true;
  5619. exit;
  5620. end;
  5621. end;
  5622. end;
  5623. { Change:
  5624. leal/q $x(%reg1),%reg2
  5625. ...
  5626. shll/q $y,%reg2
  5627. To:
  5628. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5629. }
  5630. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5631. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5632. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5633. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5634. (taicpu(hp1).oper[0]^.val <= 3) then
  5635. begin
  5636. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5637. TransferUsedRegs(TmpUsedRegs);
  5638. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5639. if
  5640. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5641. (this works even if scalefactor is zero) }
  5642. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5643. { Ensure offset doesn't go out of bounds }
  5644. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5645. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5646. (
  5647. (
  5648. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5649. (
  5650. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5651. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5652. (
  5653. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5654. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5655. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5656. )
  5657. )
  5658. ) or (
  5659. (
  5660. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5661. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5662. ) and
  5663. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5664. )
  5665. ) then
  5666. begin
  5667. repeat
  5668. with taicpu(p).oper[0]^.ref^ do
  5669. begin
  5670. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5671. if index = base then
  5672. begin
  5673. if Multiple > 4 then
  5674. { Optimisation will no longer work because resultant
  5675. scale factor will exceed 8 }
  5676. Break;
  5677. base := NR_NO;
  5678. scalefactor := 2;
  5679. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5680. end
  5681. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5682. begin
  5683. { Scale factor only works on the index register }
  5684. index := base;
  5685. base := NR_NO;
  5686. end;
  5687. { For safety }
  5688. if scalefactor <= 1 then
  5689. begin
  5690. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5691. scalefactor := Multiple;
  5692. end
  5693. else
  5694. begin
  5695. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5696. scalefactor := scalefactor * Multiple;
  5697. end;
  5698. offset := offset * Multiple;
  5699. end;
  5700. RemoveInstruction(hp1);
  5701. Result := True;
  5702. Exit;
  5703. { This repeat..until loop exists for the benefit of Break }
  5704. until True;
  5705. end;
  5706. end;
  5707. end;
  5708. end;
  5709. end;
  5710. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5711. var
  5712. hp1 : tai;
  5713. SubInstr: Boolean;
  5714. ThisConst: TCGInt;
  5715. const
  5716. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5717. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5718. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5719. begin
  5720. Result := False;
  5721. if taicpu(p).oper[0]^.typ <> top_const then
  5722. { Should have been confirmed before calling }
  5723. InternalError(2021102601);
  5724. SubInstr := (taicpu(p).opcode = A_SUB);
  5725. if GetLastInstruction(p, hp1) and
  5726. (hp1.typ = ait_instruction) and
  5727. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5728. begin
  5729. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5730. { Bad size }
  5731. InternalError(2022042001);
  5732. case taicpu(hp1).opcode Of
  5733. A_INC:
  5734. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5735. begin
  5736. if SubInstr then
  5737. ThisConst := taicpu(p).oper[0]^.val - 1
  5738. else
  5739. ThisConst := taicpu(p).oper[0]^.val + 1;
  5740. end
  5741. else
  5742. Exit;
  5743. A_DEC:
  5744. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5745. begin
  5746. if SubInstr then
  5747. ThisConst := taicpu(p).oper[0]^.val + 1
  5748. else
  5749. ThisConst := taicpu(p).oper[0]^.val - 1;
  5750. end
  5751. else
  5752. Exit;
  5753. A_SUB:
  5754. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5755. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5756. begin
  5757. if SubInstr then
  5758. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5759. else
  5760. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5761. end
  5762. else
  5763. Exit;
  5764. A_ADD:
  5765. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5766. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5767. begin
  5768. if SubInstr then
  5769. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5770. else
  5771. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5772. end
  5773. else
  5774. Exit;
  5775. else
  5776. Exit;
  5777. end;
  5778. { Check that the values are in range }
  5779. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5780. { Overflow; abort }
  5781. Exit;
  5782. if (ThisConst = 0) then
  5783. begin
  5784. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5785. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5786. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5787. RemoveInstruction(hp1);
  5788. hp1 := tai(p.next);
  5789. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5790. if not GetLastInstruction(hp1, p) then
  5791. p := hp1;
  5792. end
  5793. else
  5794. begin
  5795. if taicpu(hp1).opercnt=1 then
  5796. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5797. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5798. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5799. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5800. else
  5801. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5802. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5803. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5804. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5805. RemoveInstruction(hp1);
  5806. taicpu(p).loadconst(0, ThisConst);
  5807. end;
  5808. Result := True;
  5809. end;
  5810. end;
  5811. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5812. begin
  5813. Result := False;
  5814. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5815. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5816. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5817. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5818. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5819. (
  5820. (
  5821. (taicpu(hp1).opcode = A_TEST)
  5822. ) or (
  5823. (taicpu(hp1).opcode = A_CMP) and
  5824. { A sanity check more than anything }
  5825. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5826. )
  5827. ) then
  5828. begin
  5829. { change
  5830. mov mem, %reg
  5831. ...
  5832. cmp/test x, %reg / test %reg,%reg
  5833. (reg deallocated)
  5834. to
  5835. cmp/test x, mem / cmp 0, mem
  5836. }
  5837. TransferUsedRegs(TmpUsedRegs);
  5838. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5839. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5840. begin
  5841. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5842. if (taicpu(hp1).opcode = A_TEST) and
  5843. (
  5844. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5845. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5846. ) then
  5847. begin
  5848. taicpu(hp1).opcode := A_CMP;
  5849. taicpu(hp1).loadconst(0, 0);
  5850. end;
  5851. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5852. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5853. RemoveCurrentP(p);
  5854. if (p <> hp1) then
  5855. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5856. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5857. { Make sure the flags are allocated across the CMP instruction }
  5858. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5859. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5860. Result := True;
  5861. Exit;
  5862. end;
  5863. end;
  5864. end;
  5865. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5866. var
  5867. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5868. ThisReg, SecondReg: TRegister;
  5869. JumpLoc: TAsmLabel;
  5870. NewSize: TOpSize;
  5871. begin
  5872. Result := False;
  5873. {
  5874. Convert:
  5875. j<c> .L1
  5876. .L2:
  5877. mov 1,reg
  5878. jmp .L3 (or ret, although it might not be a RET yet)
  5879. .L1:
  5880. mov 0,reg
  5881. jmp .L3 (or ret)
  5882. ( As long as .L3 <> .L1 or .L2)
  5883. To:
  5884. mov 0,reg
  5885. set<not(c)> reg
  5886. jmp .L3 (or ret)
  5887. .L2:
  5888. mov 1,reg
  5889. jmp .L3 (or ret)
  5890. .L1:
  5891. mov 0,reg
  5892. jmp .L3 (or ret)
  5893. }
  5894. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5895. Exit;
  5896. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5897. if GetNextInstruction(hp_label, hp2) and
  5898. MatchInstruction(hp2,A_MOV,[]) and
  5899. (taicpu(hp2).oper[0]^.typ = top_const) and
  5900. (
  5901. (
  5902. (taicpu(hp2).oper[1]^.typ = top_reg)
  5903. {$ifdef i386}
  5904. { Under i386, ESI, EDI, EBP and ESP
  5905. don't have an 8-bit representation }
  5906. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5907. {$endif i386}
  5908. ) or (
  5909. {$ifdef i386}
  5910. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5911. {$endif i386}
  5912. (taicpu(hp2).opsize = S_B)
  5913. )
  5914. ) and
  5915. GetNextInstruction(hp2, hp3) and
  5916. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5917. (
  5918. (taicpu(hp3).opcode=A_RET) or
  5919. (
  5920. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5921. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5922. )
  5923. ) and
  5924. GetNextInstruction(hp3, hp4) and
  5925. SkipAligns(hp4, hp4) and
  5926. (hp4.typ=ait_label) and
  5927. (tai_label(hp4).labsym=JumpLoc) and
  5928. (
  5929. not (cs_opt_size in current_settings.optimizerswitches) or
  5930. { If the initial jump is the label's only reference, then it will
  5931. become a dead label if the other conditions are met and hence
  5932. remove at least 2 instructions, including a jump }
  5933. (JumpLoc.getrefs = 1)
  5934. ) and
  5935. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5936. that will be optimised out }
  5937. GetNextInstruction(hp4, hp5) and
  5938. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5939. (taicpu(hp5).oper[0]^.typ = top_const) and
  5940. (
  5941. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5942. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5943. ) and
  5944. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5945. GetNextInstruction(hp5,hp6) and
  5946. (
  5947. (hp6.typ<>ait_label) or
  5948. SkipLabels(hp6, hp6)
  5949. ) and
  5950. (hp6.typ=ait_instruction) then
  5951. begin
  5952. { First, let's look at the two jumps that are hp3 and hp6 }
  5953. if not
  5954. (
  5955. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5956. (
  5957. (taicpu(hp6).opcode=A_RET) or
  5958. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5959. )
  5960. ) then
  5961. { If condition is False, then the JMP/RET instructions matched conventionally }
  5962. begin
  5963. { See if one of the jumps can be instantly converted into a RET }
  5964. if (taicpu(hp3).opcode=A_JMP) then
  5965. begin
  5966. { Reuse hp5 }
  5967. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5968. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5969. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5970. Exit;
  5971. if MatchInstruction(hp5, A_RET, []) then
  5972. begin
  5973. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5974. ConvertJumpToRET(hp3, hp5);
  5975. Result := True;
  5976. end
  5977. else
  5978. Exit;
  5979. end;
  5980. if (taicpu(hp6).opcode=A_JMP) then
  5981. begin
  5982. { Reuse hp5 }
  5983. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5984. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5985. Exit;
  5986. if MatchInstruction(hp5, A_RET, []) then
  5987. begin
  5988. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5989. ConvertJumpToRET(hp6, hp5);
  5990. Result := True;
  5991. end
  5992. else
  5993. Exit;
  5994. end;
  5995. if not
  5996. (
  5997. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5998. (
  5999. (taicpu(hp6).opcode=A_RET) or
  6000. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6001. )
  6002. ) then
  6003. { Still doesn't match }
  6004. Exit;
  6005. end;
  6006. if (taicpu(hp2).oper[0]^.val = 1) then
  6007. begin
  6008. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6009. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6010. end
  6011. else
  6012. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6013. if taicpu(hp2).opsize=S_B then
  6014. begin
  6015. if taicpu(hp2).oper[1]^.typ = top_reg then
  6016. begin
  6017. SecondReg := taicpu(hp2).oper[1]^.reg;
  6018. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6019. end
  6020. else
  6021. begin
  6022. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6023. SecondReg := NR_NO;
  6024. end;
  6025. hp_pos := p;
  6026. hp_allocstart := hp4;
  6027. end
  6028. else
  6029. begin
  6030. { Will be a register because the size can't be S_B otherwise }
  6031. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6032. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6033. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6034. if (cs_opt_size in current_settings.optimizerswitches) then
  6035. begin
  6036. { Favour using MOVZX when optimising for size }
  6037. case taicpu(hp2).opsize of
  6038. S_W:
  6039. NewSize := S_BW;
  6040. S_L:
  6041. NewSize := S_BL;
  6042. {$ifdef x86_64}
  6043. S_Q:
  6044. begin
  6045. NewSize := S_BL;
  6046. { Will implicitly zero-extend to 64-bit }
  6047. setsubreg(SecondReg, R_SUBD);
  6048. end;
  6049. {$endif x86_64}
  6050. else
  6051. InternalError(2022101301);
  6052. end;
  6053. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6054. { Inserting it right before p will guarantee that the flags are also tracked }
  6055. Asml.InsertBefore(hp5, p);
  6056. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6057. hp_pos := hp5;
  6058. hp_allocstart := hp4;
  6059. end
  6060. else
  6061. begin
  6062. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6063. { Inserting it right before p will guarantee that the flags are also tracked }
  6064. Asml.InsertBefore(hp5, p);
  6065. hp_pos := p;
  6066. hp_allocstart := hp5;
  6067. end;
  6068. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6069. end;
  6070. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6071. taicpu(hp4).condition := taicpu(p).condition;
  6072. asml.InsertBefore(hp4, hp_pos);
  6073. if taicpu(hp3).is_jmp then
  6074. begin
  6075. JumpLoc.decrefs;
  6076. MakeUnconditional(taicpu(p));
  6077. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6078. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6079. end
  6080. else
  6081. ConvertJumpToRET(p, hp3);
  6082. if SecondReg <> NR_NO then
  6083. { Ensure the destination register is allocated over this region }
  6084. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6085. if (JumpLoc.getrefs = 0) then
  6086. RemoveDeadCodeAfterJump(hp3);
  6087. Result:=true;
  6088. exit;
  6089. end;
  6090. end;
  6091. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6092. var
  6093. hp1, hp2: tai;
  6094. ActiveReg: TRegister;
  6095. OldOffset: asizeint;
  6096. ThisConst: TCGInt;
  6097. function RegDeallocated: Boolean;
  6098. begin
  6099. TransferUsedRegs(TmpUsedRegs);
  6100. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6101. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6102. end;
  6103. begin
  6104. Result:=false;
  6105. hp1 := nil;
  6106. { replace
  6107. subX const,%reg1
  6108. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6109. dealloc %reg1
  6110. by
  6111. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6112. }
  6113. if MatchOpType(taicpu(p),top_const,top_reg) then
  6114. begin
  6115. ActiveReg := taicpu(p).oper[1]^.reg;
  6116. { Ensures the entire register was updated }
  6117. if (taicpu(p).opsize >= S_L) and
  6118. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6119. MatchInstruction(hp1,A_LEA,[]) and
  6120. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6121. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6122. (
  6123. { Cover the case where the register in the reference is also the destination register }
  6124. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6125. (
  6126. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6127. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6128. RegDeallocated
  6129. )
  6130. ) then
  6131. begin
  6132. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6133. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6134. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6135. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6136. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6137. {$ifdef x86_64}
  6138. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6139. begin
  6140. { Overflow; abort }
  6141. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6142. end
  6143. else
  6144. {$endif x86_64}
  6145. begin
  6146. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6147. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6148. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6149. RemoveCurrentP(p, hp1)
  6150. else
  6151. RemoveCurrentP(p);
  6152. result:=true;
  6153. Exit;
  6154. end;
  6155. end;
  6156. if (
  6157. { Save calling GetNextInstructionUsingReg again }
  6158. Assigned(hp1) or
  6159. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6160. ) and
  6161. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6162. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6163. begin
  6164. if taicpu(hp1).oper[0]^.typ = top_const then
  6165. begin
  6166. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6167. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6168. Result := True;
  6169. { Handle any overflows }
  6170. case taicpu(p).opsize of
  6171. S_B:
  6172. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6173. S_W:
  6174. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6175. S_L:
  6176. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6177. {$ifdef x86_64}
  6178. S_Q:
  6179. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6180. { Overflow; abort }
  6181. Result := False
  6182. else
  6183. taicpu(p).oper[0]^.val := ThisConst;
  6184. {$endif x86_64}
  6185. else
  6186. InternalError(2021102611);
  6187. end;
  6188. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6189. if Result then
  6190. begin
  6191. if (taicpu(p).oper[0]^.val < 0) and
  6192. (
  6193. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6194. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6195. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6196. ) then
  6197. begin
  6198. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6199. taicpu(p).opcode := A_SUB;
  6200. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6201. end
  6202. else
  6203. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6204. RemoveInstruction(hp1);
  6205. end;
  6206. end
  6207. else
  6208. begin
  6209. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6210. TransferUsedRegs(TmpUsedRegs);
  6211. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6212. hp2 := p;
  6213. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6214. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6215. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6216. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6217. begin
  6218. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6219. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6220. Asml.Remove(p);
  6221. Asml.InsertAfter(p, hp1);
  6222. p := hp1;
  6223. Result := True;
  6224. Exit;
  6225. end;
  6226. end;
  6227. end;
  6228. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6229. { * change "sub/add const1, reg" or "dec reg" followed by
  6230. "sub const2, reg" to one "sub ..., reg" }
  6231. {$ifdef i386}
  6232. if (taicpu(p).oper[0]^.val = 2) and
  6233. (ActiveReg = NR_ESP) and
  6234. { Don't do the sub/push optimization if the sub }
  6235. { comes from setting up the stack frame (JM) }
  6236. (not(GetLastInstruction(p,hp1)) or
  6237. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6238. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6239. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6240. begin
  6241. hp1 := tai(p.next);
  6242. while Assigned(hp1) and
  6243. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6244. not RegReadByInstruction(NR_ESP,hp1) and
  6245. not RegModifiedByInstruction(NR_ESP,hp1) do
  6246. hp1 := tai(hp1.next);
  6247. if Assigned(hp1) and
  6248. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6249. begin
  6250. taicpu(hp1).changeopsize(S_L);
  6251. if taicpu(hp1).oper[0]^.typ=top_reg then
  6252. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6253. hp1 := tai(p.next);
  6254. RemoveCurrentp(p, hp1);
  6255. Result:=true;
  6256. exit;
  6257. end;
  6258. end;
  6259. {$endif i386}
  6260. if DoArithCombineOpt(p) then
  6261. Result:=true;
  6262. end;
  6263. end;
  6264. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6265. var
  6266. TmpBool1,TmpBool2 : Boolean;
  6267. tmpref : treference;
  6268. hp1,hp2: tai;
  6269. mask, shiftval: tcgint;
  6270. begin
  6271. Result:=false;
  6272. { All these optimisations work on "shl/sal const,%reg" }
  6273. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6274. Exit;
  6275. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6276. (taicpu(p).oper[0]^.val <= 3) then
  6277. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6278. begin
  6279. { should we check the next instruction? }
  6280. TmpBool1 := True;
  6281. { have we found an add/sub which could be
  6282. integrated in the lea? }
  6283. TmpBool2 := False;
  6284. reference_reset(tmpref,2,[]);
  6285. TmpRef.index := taicpu(p).oper[1]^.reg;
  6286. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6287. while TmpBool1 and
  6288. GetNextInstruction(p, hp1) and
  6289. (tai(hp1).typ = ait_instruction) and
  6290. ((((taicpu(hp1).opcode = A_ADD) or
  6291. (taicpu(hp1).opcode = A_SUB)) and
  6292. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6293. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6294. (((taicpu(hp1).opcode = A_INC) or
  6295. (taicpu(hp1).opcode = A_DEC)) and
  6296. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6297. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6298. ((taicpu(hp1).opcode = A_LEA) and
  6299. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6300. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6301. (not GetNextInstruction(hp1,hp2) or
  6302. not instrReadsFlags(hp2)) Do
  6303. begin
  6304. TmpBool1 := False;
  6305. if taicpu(hp1).opcode=A_LEA then
  6306. begin
  6307. if (TmpRef.base = NR_NO) and
  6308. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6309. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6310. { Segment register isn't a concern here }
  6311. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6312. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6313. begin
  6314. TmpBool1 := True;
  6315. TmpBool2 := True;
  6316. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6317. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6318. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6319. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6320. RemoveInstruction(hp1);
  6321. end
  6322. end
  6323. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6324. begin
  6325. TmpBool1 := True;
  6326. TmpBool2 := True;
  6327. case taicpu(hp1).opcode of
  6328. A_ADD:
  6329. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6330. A_SUB:
  6331. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6332. else
  6333. internalerror(2019050536);
  6334. end;
  6335. RemoveInstruction(hp1);
  6336. end
  6337. else
  6338. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6339. (((taicpu(hp1).opcode = A_ADD) and
  6340. (TmpRef.base = NR_NO)) or
  6341. (taicpu(hp1).opcode = A_INC) or
  6342. (taicpu(hp1).opcode = A_DEC)) then
  6343. begin
  6344. TmpBool1 := True;
  6345. TmpBool2 := True;
  6346. case taicpu(hp1).opcode of
  6347. A_ADD:
  6348. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6349. A_INC:
  6350. inc(TmpRef.offset);
  6351. A_DEC:
  6352. dec(TmpRef.offset);
  6353. else
  6354. internalerror(2019050535);
  6355. end;
  6356. RemoveInstruction(hp1);
  6357. end;
  6358. end;
  6359. if TmpBool2
  6360. {$ifndef x86_64}
  6361. or
  6362. ((current_settings.optimizecputype < cpu_Pentium2) and
  6363. (taicpu(p).oper[0]^.val <= 3) and
  6364. not(cs_opt_size in current_settings.optimizerswitches))
  6365. {$endif x86_64}
  6366. then
  6367. begin
  6368. if not(TmpBool2) and
  6369. (taicpu(p).oper[0]^.val=1) then
  6370. begin
  6371. taicpu(p).opcode := A_ADD;
  6372. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6373. end
  6374. else
  6375. begin
  6376. taicpu(p).opcode := A_LEA;
  6377. taicpu(p).loadref(0, TmpRef);
  6378. end;
  6379. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6380. Result := True;
  6381. end;
  6382. end
  6383. {$ifndef x86_64}
  6384. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6385. begin
  6386. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6387. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6388. (unlike shl, which is only Tairable in the U pipe) }
  6389. if taicpu(p).oper[0]^.val=1 then
  6390. begin
  6391. taicpu(p).opcode := A_ADD;
  6392. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6393. Result := True;
  6394. end
  6395. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6396. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6397. else if (taicpu(p).opsize = S_L) and
  6398. (taicpu(p).oper[0]^.val<= 3) then
  6399. begin
  6400. reference_reset(tmpref,2,[]);
  6401. TmpRef.index := taicpu(p).oper[1]^.reg;
  6402. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6403. taicpu(p).opcode := A_LEA;
  6404. taicpu(p).loadref(0, TmpRef);
  6405. Result := True;
  6406. end;
  6407. end
  6408. {$endif x86_64}
  6409. else if
  6410. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6411. (
  6412. (
  6413. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6414. SetAndTest(hp1, hp2)
  6415. {$ifdef x86_64}
  6416. ) or
  6417. (
  6418. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6419. GetNextInstruction(hp1, hp2) and
  6420. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6421. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6422. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6423. {$endif x86_64}
  6424. )
  6425. ) and
  6426. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6427. begin
  6428. { Change:
  6429. shl x, %reg1
  6430. mov -(1<<x), %reg2
  6431. and %reg2, %reg1
  6432. Or:
  6433. shl x, %reg1
  6434. and -(1<<x), %reg1
  6435. To just:
  6436. shl x, %reg1
  6437. Since the and operation only zeroes bits that are already zero from the shl operation
  6438. }
  6439. case taicpu(p).oper[0]^.val of
  6440. 8:
  6441. mask:=$FFFFFFFFFFFFFF00;
  6442. 16:
  6443. mask:=$FFFFFFFFFFFF0000;
  6444. 32:
  6445. mask:=$FFFFFFFF00000000;
  6446. 63:
  6447. { Constant pre-calculated to prevent overflow errors with Int64 }
  6448. mask:=$8000000000000000;
  6449. else
  6450. begin
  6451. if taicpu(p).oper[0]^.val >= 64 then
  6452. { Shouldn't happen realistically, since the register
  6453. is guaranteed to be set to zero at this point }
  6454. mask := 0
  6455. else
  6456. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6457. end;
  6458. end;
  6459. if taicpu(hp1).oper[0]^.val = mask then
  6460. begin
  6461. { Everything checks out, perform the optimisation, as long as
  6462. the FLAGS register isn't being used}
  6463. TransferUsedRegs(TmpUsedRegs);
  6464. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6465. {$ifdef x86_64}
  6466. if (hp1 <> hp2) then
  6467. begin
  6468. { "shl/mov/and" version }
  6469. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6470. { Don't do the optimisation if the FLAGS register is in use }
  6471. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6472. begin
  6473. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6474. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6475. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6476. begin
  6477. RemoveInstruction(hp1);
  6478. Result := True;
  6479. end;
  6480. { Only set Result to True if the 'mov' instruction was removed }
  6481. RemoveInstruction(hp2);
  6482. end;
  6483. end
  6484. else
  6485. {$endif x86_64}
  6486. begin
  6487. { "shl/and" version }
  6488. { Don't do the optimisation if the FLAGS register is in use }
  6489. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6490. begin
  6491. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6492. RemoveInstruction(hp1);
  6493. Result := True;
  6494. end;
  6495. end;
  6496. Exit;
  6497. end
  6498. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6499. begin
  6500. { Even if the mask doesn't allow for its removal, we might be
  6501. able to optimise the mask for the "shl/and" version, which
  6502. may permit other peephole optimisations }
  6503. {$ifdef DEBUG_AOPTCPU}
  6504. mask := taicpu(hp1).oper[0]^.val and mask;
  6505. if taicpu(hp1).oper[0]^.val <> mask then
  6506. begin
  6507. DebugMsg(
  6508. SPeepholeOptimization +
  6509. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6510. ' to $' + debug_tostr(mask) +
  6511. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6512. taicpu(hp1).oper[0]^.val := mask;
  6513. end;
  6514. {$else DEBUG_AOPTCPU}
  6515. { If debugging is off, just set the operand even if it's the same }
  6516. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6517. {$endif DEBUG_AOPTCPU}
  6518. end;
  6519. end;
  6520. {
  6521. change
  6522. shl/sal const,reg
  6523. <op> ...(...,reg,1),...
  6524. into
  6525. <op> ...(...,reg,1 shl const),...
  6526. if const in 1..3
  6527. }
  6528. if MatchOpType(taicpu(p), top_const, top_reg) and
  6529. (taicpu(p).oper[0]^.val in [1..3]) and
  6530. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6531. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6532. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6533. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6534. MatchOpType(taicpu(hp1),top_ref))
  6535. ) and
  6536. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6537. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6538. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6539. begin
  6540. TransferUsedRegs(TmpUsedRegs);
  6541. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6542. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6543. begin
  6544. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6545. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6546. RemoveCurrentP(p);
  6547. Result:=true;
  6548. exit;
  6549. end;
  6550. end;
  6551. if MatchOpType(taicpu(p), top_const, top_reg) and
  6552. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6553. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6554. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6555. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6556. begin
  6557. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6558. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6559. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6560. {$ifdef x86_64}
  6561. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6562. {$endif x86_64}
  6563. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6564. begin
  6565. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6566. taicpu(hp1).opcode:=A_MOV;
  6567. taicpu(hp1).oper[0]^.val:=0;
  6568. end
  6569. else
  6570. begin
  6571. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6572. taicpu(hp1).oper[0]^.val:=shiftval;
  6573. end;
  6574. RemoveCurrentP(p);
  6575. Result:=true;
  6576. exit;
  6577. end;
  6578. end;
  6579. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6580. begin
  6581. case shr_size of
  6582. S_B:
  6583. { No valid combinations }
  6584. Result := False;
  6585. S_W:
  6586. Result := (Shift >= 8) and (movz_size = S_BW);
  6587. S_L:
  6588. Result :=
  6589. (Shift >= 24) { Any opsize is valid for this shift } or
  6590. ((Shift >= 16) and (movz_size = S_WL));
  6591. {$ifdef x86_64}
  6592. S_Q:
  6593. Result :=
  6594. (Shift >= 56) { Any opsize is valid for this shift } or
  6595. ((Shift >= 48) and (movz_size = S_WL));
  6596. {$endif x86_64}
  6597. else
  6598. InternalError(2022081510);
  6599. end;
  6600. end;
  6601. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6602. var
  6603. hp1, hp2: tai;
  6604. Shift: TCGInt;
  6605. LimitSize: Topsize;
  6606. DoNotMerge: Boolean;
  6607. begin
  6608. Result := False;
  6609. { All these optimisations work on "shr const,%reg" }
  6610. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6611. Exit;
  6612. DoNotMerge := False;
  6613. Shift := taicpu(p).oper[0]^.val;
  6614. LimitSize := taicpu(p).opsize;
  6615. hp1 := p;
  6616. repeat
  6617. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6618. Exit;
  6619. case taicpu(hp1).opcode of
  6620. A_TEST, A_CMP, A_Jcc:
  6621. { Skip over conditional jumps and relevant comparisons }
  6622. Continue;
  6623. A_MOVZX:
  6624. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6625. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6626. begin
  6627. { Since the original register is being read as is, subsequent
  6628. SHRs must not be merged at this point }
  6629. DoNotMerge := True;
  6630. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6631. begin
  6632. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6633. begin
  6634. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6635. taicpu(hp1).opcode := A_MOV;
  6636. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6637. case taicpu(hp1).opsize of
  6638. S_BW:
  6639. taicpu(hp1).opsize := S_W;
  6640. S_BL, S_WL:
  6641. taicpu(hp1).opsize := S_L;
  6642. else
  6643. InternalError(2022081503);
  6644. end;
  6645. { p itself hasn't changed, so no need to set Result to True }
  6646. Include(OptsToCheck, aoc_ForceNewIteration);
  6647. { See if there's anything afterwards that can be
  6648. optimised, since the input register hasn't changed }
  6649. Continue;
  6650. end;
  6651. { NOTE: If the MOVZX instruction reads and writes the same
  6652. register, defer this to the post-peephole optimisation stage }
  6653. Exit;
  6654. end;
  6655. end;
  6656. A_SHL, A_SAL, A_SHR:
  6657. if (taicpu(hp1).opsize <= LimitSize) and
  6658. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6659. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6660. begin
  6661. { Make sure the sizes don't exceed the register size limit
  6662. (measured by the shift value falling below the limit) }
  6663. if taicpu(hp1).opsize < LimitSize then
  6664. LimitSize := taicpu(hp1).opsize;
  6665. if taicpu(hp1).opcode = A_SHR then
  6666. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6667. else
  6668. begin
  6669. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6670. DoNotMerge := True;
  6671. end;
  6672. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6673. Exit;
  6674. { Since we've established that the combined shift is within
  6675. limits, we can actually combine the adjacent SHR
  6676. instructions even if they're different sizes }
  6677. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6678. begin
  6679. hp2 := tai(hp1.Previous);
  6680. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6681. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6682. RemoveInstruction(hp1);
  6683. hp1 := hp2;
  6684. { Though p has changed, only the constant has, and its
  6685. effects can still be detected on the next iteration of
  6686. the repeat..until loop }
  6687. Include(OptsToCheck, aoc_ForceNewIteration);
  6688. end;
  6689. { Move onto the next instruction }
  6690. Continue;
  6691. end;
  6692. else
  6693. ;
  6694. end;
  6695. Break;
  6696. until False;
  6697. end;
  6698. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6699. var
  6700. CurrentRef: TReference;
  6701. FullReg: TRegister;
  6702. hp1, hp2: tai;
  6703. begin
  6704. Result := False;
  6705. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6706. Exit;
  6707. { We assume you've checked if the operand is actually a reference by
  6708. this point. If it isn't, you'll most likely get an access violation }
  6709. CurrentRef := first_mov.oper[1]^.ref^;
  6710. { Memory must be aligned }
  6711. if (CurrentRef.offset mod 4) <> 0 then
  6712. Exit;
  6713. Inc(CurrentRef.offset);
  6714. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6715. if MatchOperand(second_mov.oper[0]^, 0) and
  6716. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6717. GetNextInstruction(second_mov, hp1) and
  6718. (hp1.typ = ait_instruction) and
  6719. (taicpu(hp1).opcode = A_MOV) and
  6720. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6721. (taicpu(hp1).oper[0]^.val = 0) then
  6722. begin
  6723. Inc(CurrentRef.offset);
  6724. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6725. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6726. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6727. begin
  6728. case taicpu(hp1).opsize of
  6729. S_B:
  6730. if GetNextInstruction(hp1, hp2) and
  6731. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6732. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6733. (taicpu(hp2).oper[0]^.val = 0) then
  6734. begin
  6735. Inc(CurrentRef.offset);
  6736. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6737. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6738. (taicpu(hp2).opsize = S_B) then
  6739. begin
  6740. RemoveInstruction(hp1);
  6741. RemoveInstruction(hp2);
  6742. first_mov.opsize := S_L;
  6743. if first_mov.oper[0]^.typ = top_reg then
  6744. begin
  6745. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6746. { Reuse second_mov as a MOVZX instruction }
  6747. second_mov.opcode := A_MOVZX;
  6748. second_mov.opsize := S_BL;
  6749. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6750. second_mov.loadreg(1, FullReg);
  6751. first_mov.oper[0]^.reg := FullReg;
  6752. asml.Remove(second_mov);
  6753. asml.InsertBefore(second_mov, first_mov);
  6754. end
  6755. else
  6756. { It's a value }
  6757. begin
  6758. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6759. RemoveInstruction(second_mov);
  6760. end;
  6761. Result := True;
  6762. Exit;
  6763. end;
  6764. end;
  6765. S_W:
  6766. begin
  6767. RemoveInstruction(hp1);
  6768. first_mov.opsize := S_L;
  6769. if first_mov.oper[0]^.typ = top_reg then
  6770. begin
  6771. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6772. { Reuse second_mov as a MOVZX instruction }
  6773. second_mov.opcode := A_MOVZX;
  6774. second_mov.opsize := S_BL;
  6775. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6776. second_mov.loadreg(1, FullReg);
  6777. first_mov.oper[0]^.reg := FullReg;
  6778. asml.Remove(second_mov);
  6779. asml.InsertBefore(second_mov, first_mov);
  6780. end
  6781. else
  6782. { It's a value }
  6783. begin
  6784. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6785. RemoveInstruction(second_mov);
  6786. end;
  6787. Result := True;
  6788. Exit;
  6789. end;
  6790. else
  6791. ;
  6792. end;
  6793. end;
  6794. end;
  6795. end;
  6796. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6797. { returns true if a "continue" should be done after this optimization }
  6798. var
  6799. hp1, hp2, hp3: tai;
  6800. begin
  6801. Result := false;
  6802. hp3 := nil;
  6803. if MatchOpType(taicpu(p),top_ref) and
  6804. GetNextInstruction(p, hp1) and
  6805. (hp1.typ = ait_instruction) and
  6806. (((taicpu(hp1).opcode = A_FLD) and
  6807. (taicpu(p).opcode = A_FSTP)) or
  6808. ((taicpu(p).opcode = A_FISTP) and
  6809. (taicpu(hp1).opcode = A_FILD))) and
  6810. MatchOpType(taicpu(hp1),top_ref) and
  6811. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6812. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6813. begin
  6814. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6815. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6816. GetNextInstruction(hp1, hp2) and
  6817. (((hp2.typ = ait_instruction) and
  6818. IsExitCode(hp2) and
  6819. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6820. not(assigned(current_procinfo.procdef.funcretsym) and
  6821. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6822. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6823. { fstp <temp>
  6824. fld <temp>
  6825. <dealloc> <temp>
  6826. }
  6827. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6828. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6829. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6830. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6831. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6832. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6833. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6834. )
  6835. )
  6836. ) then
  6837. begin
  6838. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6839. RemoveInstruction(hp1);
  6840. RemoveCurrentP(p, hp2);
  6841. { first case: exit code }
  6842. if hp2.typ = ait_instruction then
  6843. RemoveLastDeallocForFuncRes(p);
  6844. Result := true;
  6845. end
  6846. else
  6847. { we can do this only in fast math mode as fstp is rounding ...
  6848. ... still disabled as it breaks the compiler and/or rtl }
  6849. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6850. { ... or if another fstp equal to the first one follows }
  6851. GetNextInstruction(hp1,hp2) and
  6852. (hp2.typ = ait_instruction) and
  6853. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6854. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6855. begin
  6856. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6857. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6858. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6859. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6860. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6861. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6862. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6863. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6864. ) then
  6865. begin
  6866. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6867. RemoveCurrentP(p,hp2);
  6868. RemoveInstruction(hp1);
  6869. Result := true;
  6870. end
  6871. else if { fst can't store an extended/comp value }
  6872. (taicpu(p).opsize <> S_FX) and
  6873. (taicpu(p).opsize <> S_IQ) then
  6874. begin
  6875. if (taicpu(p).opcode = A_FSTP) then
  6876. taicpu(p).opcode := A_FST
  6877. else
  6878. taicpu(p).opcode := A_FIST;
  6879. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6880. RemoveInstruction(hp1);
  6881. Result := true;
  6882. end;
  6883. end;
  6884. end;
  6885. end;
  6886. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6887. var
  6888. hp1, hp2, hp3: tai;
  6889. begin
  6890. result:=false;
  6891. if MatchOpType(taicpu(p),top_reg) and
  6892. GetNextInstruction(p, hp1) and
  6893. (hp1.typ = Ait_Instruction) and
  6894. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6895. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6896. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6897. { change to
  6898. fld reg fxxx reg,st
  6899. fxxxp st, st1 (hp1)
  6900. Remark: non commutative operations must be reversed!
  6901. }
  6902. begin
  6903. case taicpu(hp1).opcode Of
  6904. A_FMULP,A_FADDP,
  6905. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6906. begin
  6907. case taicpu(hp1).opcode Of
  6908. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6909. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6910. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6911. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6912. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6913. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6914. else
  6915. internalerror(2019050534);
  6916. end;
  6917. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6918. taicpu(hp1).oper[1]^.reg := NR_ST;
  6919. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6920. RemoveCurrentP(p, hp1);
  6921. Result:=true;
  6922. exit;
  6923. end;
  6924. else
  6925. ;
  6926. end;
  6927. end
  6928. else
  6929. if MatchOpType(taicpu(p),top_ref) and
  6930. GetNextInstruction(p, hp2) and
  6931. (hp2.typ = Ait_Instruction) and
  6932. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6933. (taicpu(p).opsize in [S_FS, S_FL]) and
  6934. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6935. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6936. if GetLastInstruction(p, hp1) and
  6937. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6938. MatchOpType(taicpu(hp1),top_ref) and
  6939. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6940. if ((taicpu(hp2).opcode = A_FMULP) or
  6941. (taicpu(hp2).opcode = A_FADDP)) then
  6942. { change to
  6943. fld/fst mem1 (hp1) fld/fst mem1
  6944. fld mem1 (p) fadd/
  6945. faddp/ fmul st, st
  6946. fmulp st, st1 (hp2) }
  6947. begin
  6948. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6949. RemoveCurrentP(p, hp1);
  6950. if (taicpu(hp2).opcode = A_FADDP) then
  6951. taicpu(hp2).opcode := A_FADD
  6952. else
  6953. taicpu(hp2).opcode := A_FMUL;
  6954. taicpu(hp2).oper[1]^.reg := NR_ST;
  6955. end
  6956. else
  6957. { change to
  6958. fld/fst mem1 (hp1) fld/fst mem1
  6959. fld mem1 (p) fld st
  6960. }
  6961. begin
  6962. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6963. taicpu(p).changeopsize(S_FL);
  6964. taicpu(p).loadreg(0,NR_ST);
  6965. end
  6966. else
  6967. begin
  6968. case taicpu(hp2).opcode Of
  6969. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6970. { change to
  6971. fld/fst mem1 (hp1) fld/fst mem1
  6972. fld mem2 (p) fxxx mem2
  6973. fxxxp st, st1 (hp2) }
  6974. begin
  6975. case taicpu(hp2).opcode Of
  6976. A_FADDP: taicpu(p).opcode := A_FADD;
  6977. A_FMULP: taicpu(p).opcode := A_FMUL;
  6978. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6979. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6980. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6981. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6982. else
  6983. internalerror(2019050533);
  6984. end;
  6985. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6986. RemoveInstruction(hp2);
  6987. end
  6988. else
  6989. ;
  6990. end
  6991. end
  6992. end;
  6993. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6994. begin
  6995. Result := condition_in(cond1, cond2) or
  6996. { Not strictly subsets due to the actual flags checked, but because we're
  6997. comparing integers, E is a subset of AE and GE and their aliases }
  6998. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6999. end;
  7000. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7001. var
  7002. v: TCGInt;
  7003. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7004. FirstMatch, TempBool: Boolean;
  7005. NewReg: TRegister;
  7006. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7007. begin
  7008. Result:=false;
  7009. { All these optimisations need a next instruction }
  7010. if not GetNextInstruction(p, hp1) then
  7011. Exit;
  7012. { Search for:
  7013. cmp ###,###
  7014. j(c1) @lbl1
  7015. ...
  7016. @lbl:
  7017. cmp ###,### (same comparison as above)
  7018. j(c2) @lbl2
  7019. If c1 is a subset of c2, change to:
  7020. cmp ###,###
  7021. j(c1) @lbl2
  7022. (@lbl1 may become a dead label as a result)
  7023. }
  7024. { Also handle cases where there are multiple jumps in a row }
  7025. p_jump := hp1;
  7026. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7027. begin
  7028. if IsJumpToLabel(taicpu(p_jump)) then
  7029. begin
  7030. { Do jump optimisations first in case the condition becomes
  7031. unnecessary }
  7032. TempBool := True;
  7033. if DoJumpOptimizations(p_jump, TempBool) or
  7034. not TempBool then
  7035. begin
  7036. if Assigned(p_jump) then
  7037. begin
  7038. hp1 := p_jump;
  7039. if (p_jump.typ in [ait_align]) then
  7040. SkipAligns(p_jump, p_jump);
  7041. { CollapseZeroDistJump will be set to the label after the
  7042. jump if it optimises, whether or not it's live or dead }
  7043. if (p_jump.typ in [ait_label]) and
  7044. not (tai_label(p_jump).labsym.is_used) then
  7045. GetNextInstruction(p_jump, p_jump);
  7046. end;
  7047. TransferUsedRegs(TmpUsedRegs);
  7048. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7049. if not Assigned(p_jump) or
  7050. (
  7051. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7052. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7053. ) then
  7054. begin
  7055. { No more conditional jumps; conditional statement is no longer required }
  7056. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7057. RemoveCurrentP(p);
  7058. Result := True;
  7059. Exit;
  7060. end;
  7061. hp1 := p_jump;
  7062. Include(OptsToCheck, aoc_ForceNewIteration);
  7063. Continue;
  7064. end;
  7065. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7066. if GetNextInstruction(p_jump, hp2) and
  7067. (
  7068. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7069. not TempBool
  7070. ) then
  7071. begin
  7072. hp1 := p_jump;
  7073. Include(OptsToCheck, aoc_ForceNewIteration);
  7074. Continue;
  7075. end;
  7076. p_label := nil;
  7077. if Assigned(JumpLabel) then
  7078. p_label := getlabelwithsym(JumpLabel);
  7079. if Assigned(p_label) and
  7080. GetNextInstruction(p_label, p_dist) and
  7081. MatchInstruction(p_dist, A_CMP, []) and
  7082. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7083. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7084. GetNextInstruction(p_dist, hp1_dist) and
  7085. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7086. begin
  7087. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7088. if JumpLabel = JumpLabel_dist then
  7089. { This is an infinite loop }
  7090. Exit;
  7091. { Best optimisation when the first condition is a subset (or equal) of the second }
  7092. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7093. begin
  7094. { Any registers used here will already be allocated }
  7095. if Assigned(JumpLabel) then
  7096. JumpLabel.DecRefs;
  7097. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7098. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7099. Result := True;
  7100. { Don't exit yet. Since p and p_jump haven't actually been
  7101. removed, we can check for more on this iteration }
  7102. end
  7103. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7104. GetNextInstruction(hp1_dist, hp1_label) and
  7105. SkipAligns(hp1_label, hp1_label) and
  7106. (hp1_label.typ = ait_label) then
  7107. begin
  7108. JumpLabel_far := tai_label(hp1_label).labsym;
  7109. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7110. { This is an infinite loop }
  7111. Exit;
  7112. if Assigned(JumpLabel_far) then
  7113. begin
  7114. { In this situation, if the first jump branches, the second one will never,
  7115. branch so change the destination label to after the second jump }
  7116. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7117. if Assigned(JumpLabel) then
  7118. JumpLabel.DecRefs;
  7119. JumpLabel_far.IncRefs;
  7120. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7121. Result := True;
  7122. { Don't exit yet. Since p and p_jump haven't actually been
  7123. removed, we can check for more on this iteration }
  7124. Continue;
  7125. end;
  7126. end;
  7127. end;
  7128. end;
  7129. { Search for:
  7130. cmp ###,###
  7131. j(c1) @lbl1
  7132. cmp ###,### (same as first)
  7133. Remove second cmp
  7134. }
  7135. if GetNextInstruction(p_jump, hp2) and
  7136. (
  7137. (
  7138. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7139. (
  7140. (
  7141. MatchOpType(taicpu(p), top_const, top_reg) and
  7142. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7143. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7144. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7145. ) or (
  7146. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7147. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7148. )
  7149. )
  7150. ) or (
  7151. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7152. MatchOperand(taicpu(p).oper[0]^, 0) and
  7153. (taicpu(p).oper[1]^.typ = top_reg) and
  7154. MatchInstruction(hp2, A_TEST, []) and
  7155. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7156. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7157. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7158. )
  7159. ) then
  7160. begin
  7161. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7162. RemoveInstruction(hp2);
  7163. Result := True;
  7164. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7165. end;
  7166. GetNextInstruction(p_jump, p_jump);
  7167. end;
  7168. if (
  7169. { Don't call GetNextInstruction again if we already have it }
  7170. (hp1 = p_jump) or
  7171. GetNextInstruction(p, hp1)
  7172. ) and
  7173. MatchInstruction(hp1, A_Jcc, []) and
  7174. IsJumpToLabel(taicpu(hp1)) and
  7175. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7176. GetNextInstruction(hp1, hp2) then
  7177. begin
  7178. {
  7179. cmp x, y (or "cmp y, x")
  7180. je @lbl
  7181. mov x, y
  7182. @lbl:
  7183. (x and y can be constants, registers or references)
  7184. Change to:
  7185. mov x, y (x and y will always be equal in the end)
  7186. @lbl: (may beceome a dead label)
  7187. Also:
  7188. cmp x, y (or "cmp y, x")
  7189. jne @lbl
  7190. mov x, y
  7191. @lbl:
  7192. (x and y can be constants, registers or references)
  7193. Change to:
  7194. Absolutely nothing! (Except @lbl if it's still live)
  7195. }
  7196. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7197. (
  7198. (
  7199. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7200. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7201. ) or (
  7202. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7203. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7204. )
  7205. ) and
  7206. GetNextInstruction(hp2, hp1_label) and
  7207. SkipAligns(hp1_label, hp1_label) and
  7208. (hp1_label.typ = ait_label) and
  7209. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7210. begin
  7211. tai_label(hp1_label).labsym.DecRefs;
  7212. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7213. begin
  7214. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7215. RemoveInstruction(hp2);
  7216. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7217. end
  7218. else
  7219. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7220. RemoveInstruction(hp1);
  7221. RemoveCurrentp(p, hp2);
  7222. Result := True;
  7223. Exit;
  7224. end;
  7225. {
  7226. Try to optimise the following:
  7227. cmp $x,### ($x and $y can be registers or constants)
  7228. je @lbl1 (only reference)
  7229. cmp $y,### (### are identical)
  7230. @Lbl:
  7231. sete %reg1
  7232. Change to:
  7233. cmp $x,###
  7234. sete %reg2 (allocate new %reg2)
  7235. cmp $y,###
  7236. sete %reg1
  7237. orb %reg2,%reg1
  7238. (dealloc %reg2)
  7239. This adds an instruction (so don't perform under -Os), but it removes
  7240. a conditional branch.
  7241. }
  7242. if not (cs_opt_size in current_settings.optimizerswitches) and
  7243. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7244. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7245. { The first operand of CMP instructions can only be a register or
  7246. immediate anyway, so no need to check }
  7247. GetNextInstruction(hp2, p_label) and
  7248. (p_label.typ = ait_label) and
  7249. (tai_label(p_label).labsym.getrefs = 1) and
  7250. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7251. GetNextInstruction(p_label, p_dist) and
  7252. MatchInstruction(p_dist, A_SETcc, []) and
  7253. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7254. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7255. begin
  7256. TransferUsedRegs(TmpUsedRegs);
  7257. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7258. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7259. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7260. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7261. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7262. { Get the instruction after the SETcc instruction so we can
  7263. allocate a new register over the entire range }
  7264. GetNextInstruction(p_dist, hp1_dist) then
  7265. begin
  7266. { Register can appear in p if it's not used afterwards, so only
  7267. allocate between hp1 and hp1_dist }
  7268. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7269. if NewReg <> NR_NO then
  7270. begin
  7271. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7272. { Change the jump instruction into a SETcc instruction }
  7273. taicpu(hp1).opcode := A_SETcc;
  7274. taicpu(hp1).opsize := S_B;
  7275. taicpu(hp1).loadreg(0, NewReg);
  7276. { This is now a dead label }
  7277. tai_label(p_label).labsym.decrefs;
  7278. { Prefer adding before the next instruction so the FLAGS
  7279. register is deallicated first }
  7280. AsmL.InsertBefore(
  7281. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7282. hp1_dist
  7283. );
  7284. Result := True;
  7285. { Don't exit yet, as p wasn't changed and hp1, while
  7286. modified, is still intact and might be optimised by the
  7287. SETcc optimisation below }
  7288. end;
  7289. end;
  7290. end;
  7291. end;
  7292. if taicpu(p).oper[0]^.typ = top_const then
  7293. begin
  7294. if (taicpu(p).oper[0]^.val = 0) and
  7295. (taicpu(p).oper[1]^.typ = top_reg) and
  7296. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7297. begin
  7298. hp2 := p;
  7299. FirstMatch := True;
  7300. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7301. anything meaningful once it's converted to "test %reg,%reg";
  7302. additionally, some jumps will always (or never) branch, so
  7303. evaluate every jump immediately following the
  7304. comparison, optimising the conditions if possible.
  7305. Similarly with SETcc... those that are always set to 0 or 1
  7306. are changed to MOV instructions }
  7307. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7308. (
  7309. GetNextInstruction(hp2, hp1) and
  7310. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7311. ) do
  7312. begin
  7313. FirstMatch := False;
  7314. case taicpu(hp1).condition of
  7315. C_B, C_C, C_NAE, C_O:
  7316. { For B/NAE:
  7317. Will never branch since an unsigned integer can never be below zero
  7318. For C/O:
  7319. Result cannot overflow because 0 is being subtracted
  7320. }
  7321. begin
  7322. if taicpu(hp1).opcode = A_Jcc then
  7323. begin
  7324. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7325. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7326. RemoveInstruction(hp1);
  7327. { Since hp1 was deleted, hp2 must not be updated }
  7328. Continue;
  7329. end
  7330. else
  7331. begin
  7332. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7333. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7334. taicpu(hp1).opcode := A_MOV;
  7335. taicpu(hp1).ops := 2;
  7336. taicpu(hp1).condition := C_None;
  7337. taicpu(hp1).opsize := S_B;
  7338. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7339. taicpu(hp1).loadconst(0, 0);
  7340. end;
  7341. end;
  7342. C_BE, C_NA:
  7343. begin
  7344. { Will only branch if equal to zero }
  7345. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7346. taicpu(hp1).condition := C_E;
  7347. end;
  7348. C_A, C_NBE:
  7349. begin
  7350. { Will only branch if not equal to zero }
  7351. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7352. taicpu(hp1).condition := C_NE;
  7353. end;
  7354. C_AE, C_NB, C_NC, C_NO:
  7355. begin
  7356. { Will always branch }
  7357. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7358. if taicpu(hp1).opcode = A_Jcc then
  7359. begin
  7360. MakeUnconditional(taicpu(hp1));
  7361. { Any jumps/set that follow will now be dead code }
  7362. RemoveDeadCodeAfterJump(taicpu(hp1));
  7363. Break;
  7364. end
  7365. else
  7366. begin
  7367. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7368. taicpu(hp1).opcode := A_MOV;
  7369. taicpu(hp1).ops := 2;
  7370. taicpu(hp1).condition := C_None;
  7371. taicpu(hp1).opsize := S_B;
  7372. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7373. taicpu(hp1).loadconst(0, 1);
  7374. end;
  7375. end;
  7376. C_None:
  7377. InternalError(2020012201);
  7378. C_P, C_PE, C_NP, C_PO:
  7379. { We can't handle parity checks and they should never be generated
  7380. after a general-purpose CMP (it's used in some floating-point
  7381. comparisons that don't use CMP) }
  7382. InternalError(2020012202);
  7383. else
  7384. { Zero/Equality, Sign, their complements and all of the
  7385. signed comparisons do not need to be converted };
  7386. end;
  7387. hp2 := hp1;
  7388. end;
  7389. { Convert the instruction to a TEST }
  7390. taicpu(p).opcode := A_TEST;
  7391. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7392. Result := True;
  7393. Exit;
  7394. end
  7395. else if (taicpu(p).oper[0]^.val = 1) and
  7396. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7397. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7398. begin
  7399. { Convert; To:
  7400. cmp $1,r/m cmp $0,r/m
  7401. jl @lbl jle @lbl
  7402. (Also do inverted conditions)
  7403. }
  7404. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7405. taicpu(p).oper[0]^.val := 0;
  7406. if taicpu(hp1).condition in [C_L, C_NGE] then
  7407. taicpu(hp1).condition := C_LE
  7408. else
  7409. taicpu(hp1).condition := C_NLE;
  7410. { If the instruction is now "cmp $0,%reg", convert it to a
  7411. TEST (and effectively do the work of the "cmp $0,%reg" in
  7412. the block above)
  7413. }
  7414. if (taicpu(p).oper[1]^.typ = top_reg) then
  7415. begin
  7416. taicpu(p).opcode := A_TEST;
  7417. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7418. end;
  7419. Result := True;
  7420. Exit;
  7421. end
  7422. else if (taicpu(p).oper[1]^.typ = top_reg)
  7423. {$ifdef x86_64}
  7424. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7425. {$endif x86_64}
  7426. then
  7427. begin
  7428. { cmp register,$8000 neg register
  7429. je target --> jo target
  7430. .... only if register is deallocated before jump.}
  7431. case Taicpu(p).opsize of
  7432. S_B: v:=$80;
  7433. S_W: v:=$8000;
  7434. S_L: v:=qword($80000000);
  7435. else
  7436. internalerror(2013112905);
  7437. end;
  7438. if (taicpu(p).oper[0]^.val=v) and
  7439. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7440. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7441. begin
  7442. TransferUsedRegs(TmpUsedRegs);
  7443. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7444. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7445. begin
  7446. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7447. Taicpu(p).opcode:=A_NEG;
  7448. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7449. Taicpu(p).clearop(1);
  7450. Taicpu(p).ops:=1;
  7451. if Taicpu(hp1).condition=C_E then
  7452. Taicpu(hp1).condition:=C_O
  7453. else
  7454. Taicpu(hp1).condition:=C_NO;
  7455. Result:=true;
  7456. exit;
  7457. end;
  7458. end;
  7459. end;
  7460. end;
  7461. if TrySwapMovCmp(p, hp1) then
  7462. begin
  7463. Result := True;
  7464. Exit;
  7465. end;
  7466. end;
  7467. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7468. var
  7469. hp1: tai;
  7470. begin
  7471. {
  7472. remove the second (v)pxor from
  7473. pxor reg,reg
  7474. ...
  7475. pxor reg,reg
  7476. }
  7477. Result:=false;
  7478. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7479. MatchOpType(taicpu(p),top_reg,top_reg) and
  7480. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7481. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7482. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7483. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7484. begin
  7485. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7486. RemoveInstruction(hp1);
  7487. Result:=true;
  7488. Exit;
  7489. end
  7490. {
  7491. replace
  7492. pxor reg1,reg1
  7493. movapd/s reg1,reg2
  7494. dealloc reg1
  7495. by
  7496. pxor reg2,reg2
  7497. }
  7498. else if GetNextInstruction(p,hp1) and
  7499. { we mix single and double opperations here because we assume that the compiler
  7500. generates vmovapd only after double operations and vmovaps only after single operations }
  7501. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7502. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7503. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7504. (taicpu(p).oper[0]^.typ=top_reg) then
  7505. begin
  7506. TransferUsedRegs(TmpUsedRegs);
  7507. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7508. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7509. begin
  7510. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7511. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7512. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7513. RemoveInstruction(hp1);
  7514. result:=true;
  7515. end;
  7516. end;
  7517. end;
  7518. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7519. var
  7520. hp1: tai;
  7521. begin
  7522. {
  7523. remove the second (v)pxor from
  7524. (v)pxor reg,reg
  7525. ...
  7526. (v)pxor reg,reg
  7527. }
  7528. Result:=false;
  7529. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7530. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7531. begin
  7532. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7533. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7534. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7535. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7536. begin
  7537. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7538. RemoveInstruction(hp1);
  7539. Result:=true;
  7540. Exit;
  7541. end;
  7542. {$ifdef x86_64}
  7543. {
  7544. replace
  7545. vpxor reg1,reg1,reg1
  7546. vmov reg,mem
  7547. by
  7548. movq $0,mem
  7549. }
  7550. if GetNextInstruction(p,hp1) and
  7551. MatchInstruction(hp1,A_VMOVSD,[]) and
  7552. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7553. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7554. begin
  7555. TransferUsedRegs(TmpUsedRegs);
  7556. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7557. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7558. begin
  7559. taicpu(hp1).loadconst(0,0);
  7560. taicpu(hp1).opcode:=A_MOV;
  7561. taicpu(hp1).opsize:=S_Q;
  7562. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7563. RemoveCurrentP(p);
  7564. result:=true;
  7565. Exit;
  7566. end;
  7567. end;
  7568. {$endif x86_64}
  7569. end
  7570. {
  7571. replace
  7572. vpxor reg1,reg1,reg2
  7573. by
  7574. vpxor reg2,reg2,reg2
  7575. to avoid unncessary data dependencies
  7576. }
  7577. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7578. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7579. begin
  7580. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7581. { avoid unncessary data dependency }
  7582. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7583. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7584. result:=true;
  7585. exit;
  7586. end;
  7587. Result:=OptPass1VOP(p);
  7588. end;
  7589. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7590. var
  7591. hp1 : tai;
  7592. begin
  7593. result:=false;
  7594. { replace
  7595. IMul const,%mreg1,%mreg2
  7596. Mov %reg2,%mreg3
  7597. dealloc %mreg3
  7598. by
  7599. Imul const,%mreg1,%mreg23
  7600. }
  7601. if (taicpu(p).ops=3) and
  7602. GetNextInstruction(p,hp1) and
  7603. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7604. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7605. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7606. begin
  7607. TransferUsedRegs(TmpUsedRegs);
  7608. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7609. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7610. begin
  7611. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7612. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7613. RemoveInstruction(hp1);
  7614. result:=true;
  7615. end;
  7616. end;
  7617. end;
  7618. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7619. var
  7620. hp1 : tai;
  7621. begin
  7622. result:=false;
  7623. { replace
  7624. IMul %reg0,%reg1,%reg2
  7625. Mov %reg2,%reg3
  7626. dealloc %reg2
  7627. by
  7628. Imul %reg0,%reg1,%reg3
  7629. }
  7630. if GetNextInstruction(p,hp1) and
  7631. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7632. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7633. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7634. begin
  7635. TransferUsedRegs(TmpUsedRegs);
  7636. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7637. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7638. begin
  7639. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7640. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7641. RemoveInstruction(hp1);
  7642. result:=true;
  7643. end;
  7644. end;
  7645. end;
  7646. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7647. var
  7648. hp1: tai;
  7649. begin
  7650. Result:=false;
  7651. { get rid of
  7652. (v)cvtss2sd reg0,<reg1,>reg2
  7653. (v)cvtss2sd reg2,<reg2,>reg0
  7654. }
  7655. if GetNextInstruction(p,hp1) and
  7656. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7657. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7658. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7659. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7660. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7661. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7662. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7663. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7664. )
  7665. ) then
  7666. begin
  7667. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7668. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7669. begin
  7670. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7671. RemoveCurrentP(p);
  7672. RemoveInstruction(hp1);
  7673. end
  7674. else
  7675. begin
  7676. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7677. if taicpu(hp1).opcode=A_CVTSD2SS then
  7678. begin
  7679. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7680. taicpu(p).opcode:=A_MOVAPS;
  7681. end
  7682. else
  7683. begin
  7684. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7685. taicpu(p).opcode:=A_VMOVAPS;
  7686. end;
  7687. taicpu(p).ops:=2;
  7688. RemoveInstruction(hp1);
  7689. end;
  7690. Result:=true;
  7691. Exit;
  7692. end;
  7693. end;
  7694. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7695. var
  7696. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7697. ThisReg: TRegister;
  7698. begin
  7699. Result := False;
  7700. if not GetNextInstruction(p,hp1) then
  7701. Exit;
  7702. {
  7703. convert
  7704. j<c> .L1
  7705. mov 1,reg
  7706. jmp .L2
  7707. .L1
  7708. mov 0,reg
  7709. .L2
  7710. into
  7711. mov 0,reg
  7712. set<not(c)> reg
  7713. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7714. would destroy the flag contents
  7715. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7716. executed at the same time as a previous comparison.
  7717. set<not(c)> reg
  7718. movzx reg, reg
  7719. }
  7720. if MatchInstruction(hp1,A_MOV,[]) and
  7721. (taicpu(hp1).oper[0]^.typ = top_const) and
  7722. (
  7723. (
  7724. (taicpu(hp1).oper[1]^.typ = top_reg)
  7725. {$ifdef i386}
  7726. { Under i386, ESI, EDI, EBP and ESP
  7727. don't have an 8-bit representation }
  7728. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7729. {$endif i386}
  7730. ) or (
  7731. {$ifdef i386}
  7732. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7733. {$endif i386}
  7734. (taicpu(hp1).opsize = S_B)
  7735. )
  7736. ) and
  7737. GetNextInstruction(hp1,hp2) and
  7738. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7739. GetNextInstruction(hp2,hp3) and
  7740. SkipAligns(hp3, hp3) and
  7741. (hp3.typ=ait_label) and
  7742. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7743. GetNextInstruction(hp3,hp4) and
  7744. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7745. (taicpu(hp4).oper[0]^.typ = top_const) and
  7746. (
  7747. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7748. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7749. ) and
  7750. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7751. GetNextInstruction(hp4,hp5) and
  7752. SkipAligns(hp5, hp5) and
  7753. (hp5.typ=ait_label) and
  7754. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7755. begin
  7756. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7757. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7758. tai_label(hp3).labsym.DecRefs;
  7759. { If this isn't the only reference to the middle label, we can
  7760. still make a saving - only that the first jump and everything
  7761. that follows will remain. }
  7762. if (tai_label(hp3).labsym.getrefs = 0) then
  7763. begin
  7764. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7765. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7766. else
  7767. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7768. { remove jump, first label and second MOV (also catching any aligns) }
  7769. repeat
  7770. if not GetNextInstruction(hp2, hp3) then
  7771. InternalError(2021040810);
  7772. RemoveInstruction(hp2);
  7773. hp2 := hp3;
  7774. until hp2 = hp5;
  7775. { Don't decrement reference count before the removal loop
  7776. above, otherwise GetNextInstruction won't stop on the
  7777. the label }
  7778. tai_label(hp5).labsym.DecRefs;
  7779. end
  7780. else
  7781. begin
  7782. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7783. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7784. else
  7785. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7786. end;
  7787. taicpu(p).opcode:=A_SETcc;
  7788. taicpu(p).opsize:=S_B;
  7789. taicpu(p).is_jmp:=False;
  7790. if taicpu(hp1).opsize=S_B then
  7791. begin
  7792. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7793. if taicpu(hp1).oper[1]^.typ = top_reg then
  7794. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7795. RemoveInstruction(hp1);
  7796. end
  7797. else
  7798. begin
  7799. { Will be a register because the size can't be S_B otherwise }
  7800. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7801. taicpu(p).loadreg(0, ThisReg);
  7802. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7803. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7804. begin
  7805. case taicpu(hp1).opsize of
  7806. S_W:
  7807. taicpu(hp1).opsize := S_BW;
  7808. S_L:
  7809. taicpu(hp1).opsize := S_BL;
  7810. {$ifdef x86_64}
  7811. S_Q:
  7812. begin
  7813. taicpu(hp1).opsize := S_BL;
  7814. { Change the destination register to 32-bit }
  7815. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7816. end;
  7817. {$endif x86_64}
  7818. else
  7819. InternalError(2021040820);
  7820. end;
  7821. taicpu(hp1).opcode := A_MOVZX;
  7822. taicpu(hp1).loadreg(0, ThisReg);
  7823. end
  7824. else
  7825. begin
  7826. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7827. { hp1 is already a MOV instruction with the correct register }
  7828. taicpu(hp1).loadconst(0, 0);
  7829. { Inserting it right before p will guarantee that the flags are also tracked }
  7830. asml.Remove(hp1);
  7831. asml.InsertBefore(hp1, p);
  7832. end;
  7833. end;
  7834. Result:=true;
  7835. exit;
  7836. end
  7837. else if (hp1.typ = ait_label) then
  7838. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7839. end;
  7840. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7841. var
  7842. hp1, hp2, hp3: tai;
  7843. SourceRef, TargetRef: TReference;
  7844. CurrentReg: TRegister;
  7845. begin
  7846. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7847. if not UseAVX then
  7848. InternalError(2021100501);
  7849. Result := False;
  7850. { Look for the following to simplify:
  7851. vmovdqa/u x(mem1), %xmmreg
  7852. vmovdqa/u %xmmreg, y(mem2)
  7853. vmovdqa/u x+16(mem1), %xmmreg
  7854. vmovdqa/u %xmmreg, y+16(mem2)
  7855. Change to:
  7856. vmovdqa/u x(mem1), %ymmreg
  7857. vmovdqa/u %ymmreg, y(mem2)
  7858. vpxor %ymmreg, %ymmreg, %ymmreg
  7859. ( The VPXOR instruction is to zero the upper half, thus removing the
  7860. need to call the potentially expensive VZEROUPPER instruction. Other
  7861. peephole optimisations can remove VPXOR if it's unnecessary )
  7862. }
  7863. TransferUsedRegs(TmpUsedRegs);
  7864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7865. { NOTE: In the optimisations below, if the references dictate that an
  7866. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7867. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7868. if (taicpu(p).opsize = S_XMM) and
  7869. MatchOpType(taicpu(p), top_ref, top_reg) and
  7870. GetNextInstruction(p, hp1) and
  7871. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7872. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7873. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7874. begin
  7875. SourceRef := taicpu(p).oper[0]^.ref^;
  7876. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7877. if GetNextInstruction(hp1, hp2) and
  7878. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7879. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7880. begin
  7881. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7882. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7883. Inc(SourceRef.offset, 16);
  7884. { Reuse the register in the first block move }
  7885. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7886. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7887. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7888. begin
  7889. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7890. Inc(TargetRef.offset, 16);
  7891. if GetNextInstruction(hp2, hp3) and
  7892. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7893. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7894. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7895. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7896. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7897. begin
  7898. { Update the register tracking to the new size }
  7899. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7900. { Remember that the offsets are 16 ahead }
  7901. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7902. if not (
  7903. ((SourceRef.offset mod 32) = 16) and
  7904. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7905. ) then
  7906. taicpu(p).opcode := A_VMOVDQU;
  7907. taicpu(p).opsize := S_YMM;
  7908. taicpu(p).oper[1]^.reg := CurrentReg;
  7909. if not (
  7910. ((TargetRef.offset mod 32) = 16) and
  7911. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7912. ) then
  7913. taicpu(hp1).opcode := A_VMOVDQU;
  7914. taicpu(hp1).opsize := S_YMM;
  7915. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7916. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7917. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7918. if (pi_uses_ymm in current_procinfo.flags) then
  7919. RemoveInstruction(hp2)
  7920. else
  7921. begin
  7922. taicpu(hp2).opcode := A_VPXOR;
  7923. taicpu(hp2).opsize := S_YMM;
  7924. taicpu(hp2).loadreg(0, CurrentReg);
  7925. taicpu(hp2).loadreg(1, CurrentReg);
  7926. taicpu(hp2).loadreg(2, CurrentReg);
  7927. taicpu(hp2).ops := 3;
  7928. end;
  7929. RemoveInstruction(hp3);
  7930. Result := True;
  7931. Exit;
  7932. end;
  7933. end
  7934. else
  7935. begin
  7936. { See if the next references are 16 less rather than 16 greater }
  7937. Dec(SourceRef.offset, 32); { -16 the other way }
  7938. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7939. begin
  7940. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7941. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7942. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7943. GetNextInstruction(hp2, hp3) and
  7944. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7945. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7946. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7947. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7948. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7949. begin
  7950. { Update the register tracking to the new size }
  7951. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7952. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7953. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7954. if not(
  7955. ((SourceRef.offset mod 32) = 0) and
  7956. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7957. ) then
  7958. taicpu(hp2).opcode := A_VMOVDQU;
  7959. taicpu(hp2).opsize := S_YMM;
  7960. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7961. if not (
  7962. ((TargetRef.offset mod 32) = 0) and
  7963. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7964. ) then
  7965. taicpu(hp3).opcode := A_VMOVDQU;
  7966. taicpu(hp3).opsize := S_YMM;
  7967. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7968. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7969. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7970. if (pi_uses_ymm in current_procinfo.flags) then
  7971. RemoveInstruction(hp1)
  7972. else
  7973. begin
  7974. taicpu(hp1).opcode := A_VPXOR;
  7975. taicpu(hp1).opsize := S_YMM;
  7976. taicpu(hp1).loadreg(0, CurrentReg);
  7977. taicpu(hp1).loadreg(1, CurrentReg);
  7978. taicpu(hp1).loadreg(2, CurrentReg);
  7979. taicpu(hp1).ops := 3;
  7980. Asml.Remove(hp1);
  7981. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7982. end;
  7983. RemoveCurrentP(p, hp2);
  7984. Result := True;
  7985. Exit;
  7986. end;
  7987. end;
  7988. end;
  7989. end;
  7990. end;
  7991. end;
  7992. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7993. var
  7994. hp2, hp3, first_assignment: tai;
  7995. IncCount, OperIdx: Integer;
  7996. OrigLabel: TAsmLabel;
  7997. begin
  7998. Count := 0;
  7999. Result := False;
  8000. first_assignment := nil;
  8001. if (LoopCount >= 20) then
  8002. begin
  8003. { Guard against infinite loops }
  8004. Exit;
  8005. end;
  8006. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8007. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8008. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8009. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8010. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8011. Exit;
  8012. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8013. {
  8014. change
  8015. jmp .L1
  8016. ...
  8017. .L1:
  8018. mov ##, ## ( multiple movs possible )
  8019. jmp/ret
  8020. into
  8021. mov ##, ##
  8022. jmp/ret
  8023. }
  8024. if not Assigned(hp1) then
  8025. begin
  8026. hp1 := GetLabelWithSym(OrigLabel);
  8027. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8028. Exit;
  8029. end;
  8030. hp2 := hp1;
  8031. while Assigned(hp2) do
  8032. begin
  8033. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8034. SkipLabels(hp2,hp2);
  8035. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8036. Break;
  8037. case taicpu(hp2).opcode of
  8038. A_MOVSD:
  8039. begin
  8040. if taicpu(hp2).ops = 0 then
  8041. { Wrong MOVSD }
  8042. Break;
  8043. Inc(Count);
  8044. if Count >= 5 then
  8045. { Too many to be worthwhile }
  8046. Break;
  8047. GetNextInstruction(hp2, hp2);
  8048. Continue;
  8049. end;
  8050. A_MOV,
  8051. A_MOVD,
  8052. A_MOVQ,
  8053. A_MOVSX,
  8054. {$ifdef x86_64}
  8055. A_MOVSXD,
  8056. {$endif x86_64}
  8057. A_MOVZX,
  8058. A_MOVAPS,
  8059. A_MOVUPS,
  8060. A_MOVSS,
  8061. A_MOVAPD,
  8062. A_MOVUPD,
  8063. A_MOVDQA,
  8064. A_MOVDQU,
  8065. A_VMOVSS,
  8066. A_VMOVAPS,
  8067. A_VMOVUPS,
  8068. A_VMOVSD,
  8069. A_VMOVAPD,
  8070. A_VMOVUPD,
  8071. A_VMOVDQA,
  8072. A_VMOVDQU:
  8073. begin
  8074. Inc(Count);
  8075. if Count >= 5 then
  8076. { Too many to be worthwhile }
  8077. Break;
  8078. GetNextInstruction(hp2, hp2);
  8079. Continue;
  8080. end;
  8081. A_JMP:
  8082. begin
  8083. { Guard against infinite loops }
  8084. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8085. Exit;
  8086. { Analyse this jump first in case it also duplicates assignments }
  8087. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8088. begin
  8089. { Something did change! }
  8090. Result := True;
  8091. Inc(Count, IncCount);
  8092. if Count >= 5 then
  8093. begin
  8094. { Too many to be worthwhile }
  8095. Exit;
  8096. end;
  8097. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8098. Break;
  8099. end;
  8100. Result := True;
  8101. Break;
  8102. end;
  8103. A_RET:
  8104. begin
  8105. Result := True;
  8106. Break;
  8107. end;
  8108. else
  8109. Break;
  8110. end;
  8111. end;
  8112. if Result then
  8113. begin
  8114. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8115. if Count = 0 then
  8116. begin
  8117. Result := False;
  8118. Exit;
  8119. end;
  8120. hp3 := p;
  8121. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8122. while True do
  8123. begin
  8124. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8125. SkipLabels(hp1,hp1);
  8126. if (hp1.typ <> ait_instruction) then
  8127. InternalError(2021040720);
  8128. case taicpu(hp1).opcode of
  8129. A_JMP:
  8130. begin
  8131. { Change the original jump to the new destination }
  8132. OrigLabel.decrefs;
  8133. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8134. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8135. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8136. if not Assigned(first_assignment) then
  8137. InternalError(2021040810)
  8138. else
  8139. p := first_assignment;
  8140. Exit;
  8141. end;
  8142. A_RET:
  8143. begin
  8144. { Now change the jump into a RET instruction }
  8145. ConvertJumpToRET(p, hp1);
  8146. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8147. if not Assigned(first_assignment) then
  8148. InternalError(2021040811)
  8149. else
  8150. p := first_assignment;
  8151. Exit;
  8152. end;
  8153. else
  8154. begin
  8155. { Duplicate the MOV instruction }
  8156. hp3:=tai(hp1.getcopy);
  8157. if first_assignment = nil then
  8158. first_assignment := hp3;
  8159. asml.InsertBefore(hp3, p);
  8160. { Make sure the compiler knows about any final registers written here }
  8161. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8162. with taicpu(hp3).oper[OperIdx]^ do
  8163. begin
  8164. case typ of
  8165. top_ref:
  8166. begin
  8167. if (ref^.base <> NR_NO) and
  8168. (getsupreg(ref^.base) <> RS_ESP) and
  8169. (getsupreg(ref^.base) <> RS_EBP)
  8170. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8171. then
  8172. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8173. if (ref^.index <> NR_NO) and
  8174. (getsupreg(ref^.index) <> RS_ESP) and
  8175. (getsupreg(ref^.index) <> RS_EBP)
  8176. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8177. (ref^.index <> ref^.base) then
  8178. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8179. end;
  8180. top_reg:
  8181. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8182. else
  8183. ;
  8184. end;
  8185. end;
  8186. end;
  8187. end;
  8188. if not GetNextInstruction(hp1, hp1) then
  8189. { Should have dropped out earlier }
  8190. InternalError(2021040710);
  8191. end;
  8192. end;
  8193. end;
  8194. const
  8195. WriteOp: array[0..3] of set of TInsChange = (
  8196. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8197. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8198. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8199. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8200. RegWriteFlags: array[0..7] of set of TInsChange = (
  8201. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8202. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8203. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8204. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8205. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8206. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8207. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8208. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8209. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8210. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8211. var
  8212. hp2: tai;
  8213. X: Integer;
  8214. begin
  8215. { If we have something like:
  8216. op ###,###
  8217. mov ###,###
  8218. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8219. interfere in regards to what they write to.
  8220. NOTE: p must be a 2-operand instruction
  8221. }
  8222. Result := False;
  8223. if (hp1.typ <> ait_instruction) or
  8224. taicpu(hp1).is_jmp or
  8225. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8226. Exit;
  8227. { NOP is a pipeline fence, likely marking the beginning of the function
  8228. epilogue, so drop out. Similarly, drop out if POP or RET are
  8229. encountered }
  8230. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8231. Exit;
  8232. if (taicpu(hp1).opcode = A_MOVSD) and
  8233. (taicpu(hp1).ops = 0) then
  8234. { Wrong MOVSD }
  8235. Exit;
  8236. { Check for writes to specific registers first }
  8237. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8238. for X := 0 to 7 do
  8239. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8240. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8241. Exit;
  8242. for X := 0 to taicpu(hp1).ops - 1 do
  8243. begin
  8244. { Check to see if this operand writes to something }
  8245. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8246. { And matches something in the CMP/TEST instruction }
  8247. (
  8248. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8249. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8250. (
  8251. { If it's a register, make sure the register written to doesn't
  8252. appear in the cmp instruction as part of a reference }
  8253. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8254. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8255. )
  8256. ) then
  8257. Exit;
  8258. end;
  8259. { Check p to make sure it doesn't write to something that affects hp1 }
  8260. { Check for writes to specific registers first }
  8261. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8262. for X := 0 to 7 do
  8263. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8264. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8265. Exit;
  8266. for X := 0 to taicpu(p).ops - 1 do
  8267. begin
  8268. { Check to see if this operand writes to something }
  8269. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8270. { And matches something in hp1 }
  8271. (taicpu(p).oper[X]^.typ = top_reg) and
  8272. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8273. Exit;
  8274. end;
  8275. { The instruction can be safely moved }
  8276. asml.Remove(hp1);
  8277. { Try to insert after the last instructions where the FLAGS register is not
  8278. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8279. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8280. asml.InsertBefore(hp1, hp2)
  8281. { Failing that, try to insert after the last instructions where the
  8282. FLAGS register is not yet in use }
  8283. else if GetLastInstruction(p, hp2) and
  8284. (
  8285. (hp2.typ <> ait_instruction) or
  8286. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8287. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8288. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8289. ) then
  8290. asml.InsertAfter(hp1, hp2)
  8291. else
  8292. { Note, if p.Previous is nil (even if it should logically never be the
  8293. case), FindRegAllocBackward immediately exits with False and so we
  8294. safely land here (we can't just pass p because FindRegAllocBackward
  8295. immediately exits on an instruction). [Kit] }
  8296. asml.InsertBefore(hp1, p);
  8297. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8298. { We can't trust UsedRegs because we're looking backwards, although we
  8299. know the registers are allocated after p at the very least, so manually
  8300. create tai_regalloc objects if needed }
  8301. for X := 0 to taicpu(hp1).ops - 1 do
  8302. case taicpu(hp1).oper[X]^.typ of
  8303. top_reg:
  8304. begin
  8305. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8306. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8307. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8308. end;
  8309. top_ref:
  8310. begin
  8311. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8312. begin
  8313. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8314. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8315. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8316. end;
  8317. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8318. begin
  8319. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8320. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8321. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8322. end;
  8323. end;
  8324. else
  8325. ;
  8326. end;
  8327. Result := True;
  8328. end;
  8329. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8330. var
  8331. hp2: tai;
  8332. X: Integer;
  8333. begin
  8334. { If we have something like:
  8335. cmp ###,%reg1
  8336. mov 0,%reg2
  8337. And no modified registers are shared, move the instruction to before
  8338. the comparison as this means it can be optimised without worrying
  8339. about the FLAGS register. (CMP/MOV is generated by
  8340. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8341. As long as the second instruction doesn't use the flags or one of the
  8342. registers used by CMP or TEST (also check any references that use the
  8343. registers), then it can be moved prior to the comparison.
  8344. }
  8345. Result := False;
  8346. if not TrySwapMovOp(p, hp1) then
  8347. Exit;
  8348. if taicpu(hp1).opcode = A_LEA then
  8349. { The flags will be overwritten by the CMP/TEST instruction }
  8350. ConvertLEA(taicpu(hp1));
  8351. Result := True;
  8352. { Can we move it one further back? }
  8353. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8354. { Check to see if CMP/TEST is a comparison against zero }
  8355. (
  8356. (
  8357. (taicpu(p).opcode = A_CMP) and
  8358. MatchOperand(taicpu(p).oper[0]^, 0)
  8359. ) or
  8360. (
  8361. (taicpu(p).opcode = A_TEST) and
  8362. (
  8363. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8364. MatchOperand(taicpu(p).oper[0]^, -1)
  8365. )
  8366. )
  8367. ) and
  8368. { These instructions set the zero flag if the result is zero }
  8369. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8370. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8371. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8372. TrySwapMovOp(hp2, hp1);
  8373. end;
  8374. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8375. function IsXCHGAcceptable: Boolean; inline;
  8376. begin
  8377. { Always accept if optimising for size }
  8378. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8379. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8380. than 3, so it becomes a saving compared to three MOVs with two of
  8381. them able to execute simultaneously. [Kit] }
  8382. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8383. end;
  8384. var
  8385. NewRef: TReference;
  8386. hp1, hp2, hp3, hp4: Tai;
  8387. {$ifndef x86_64}
  8388. OperIdx: Integer;
  8389. {$endif x86_64}
  8390. NewInstr : Taicpu;
  8391. NewAligh : Tai_align;
  8392. DestLabel: TAsmLabel;
  8393. TempTracking: TAllUsedRegs;
  8394. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8395. var
  8396. NextInstr: tai;
  8397. begin
  8398. Result := False;
  8399. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8400. if not GetNextInstruction(InputInstr, NextInstr) or
  8401. (
  8402. { The FLAGS register isn't always tracked properly, so do not
  8403. perform this optimisation if a conditional statement follows }
  8404. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8405. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8406. ) then
  8407. begin
  8408. reference_reset(NewRef, 1, []);
  8409. NewRef.base := taicpu(p).oper[0]^.reg;
  8410. NewRef.scalefactor := 1;
  8411. if taicpu(InputInstr).opcode = A_ADD then
  8412. begin
  8413. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8414. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8415. end
  8416. else
  8417. begin
  8418. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8419. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8420. end;
  8421. taicpu(p).opcode := A_LEA;
  8422. taicpu(p).loadref(0, NewRef);
  8423. RemoveInstruction(InputInstr);
  8424. Result := True;
  8425. end;
  8426. end;
  8427. begin
  8428. Result:=false;
  8429. { This optimisation adds an instruction, so only do it for speed }
  8430. if not (cs_opt_size in current_settings.optimizerswitches) and
  8431. MatchOpType(taicpu(p), top_const, top_reg) and
  8432. (taicpu(p).oper[0]^.val = 0) then
  8433. begin
  8434. { To avoid compiler warning }
  8435. DestLabel := nil;
  8436. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8437. InternalError(2021040750);
  8438. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8439. Exit;
  8440. case hp1.typ of
  8441. ait_align,
  8442. ait_label:
  8443. begin
  8444. { Change:
  8445. mov $0,%reg mov $0,%reg
  8446. @Lbl1: @Lbl1:
  8447. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8448. je @Lbl2 jne @Lbl2
  8449. To: To:
  8450. mov $0,%reg mov $0,%reg
  8451. jmp @Lbl2 jmp @Lbl3
  8452. (align) (align)
  8453. @Lbl1: @Lbl1:
  8454. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8455. je @Lbl2 je @Lbl2
  8456. @Lbl3: <-- Only if label exists
  8457. (Not if it's optimised for size)
  8458. }
  8459. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8460. Exit;
  8461. if (hp2.typ = ait_instruction) and
  8462. (
  8463. { Register sizes must exactly match }
  8464. (
  8465. (taicpu(hp2).opcode = A_CMP) and
  8466. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8467. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8468. ) or (
  8469. (taicpu(hp2).opcode = A_TEST) and
  8470. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8471. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8472. )
  8473. ) and GetNextInstruction(hp2, hp3) and
  8474. (hp3.typ = ait_instruction) and
  8475. (taicpu(hp3).opcode = A_JCC) and
  8476. (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
  8477. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8478. begin
  8479. { Check condition of jump }
  8480. { Always true? }
  8481. if condition_in(C_E, taicpu(hp3).condition) then
  8482. begin
  8483. { Copy label symbol and obtain matching label entry for the
  8484. conditional jump, as this will be our destination}
  8485. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8486. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8487. Result := True;
  8488. end
  8489. { Always false? }
  8490. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8491. begin
  8492. { This is only worth it if there's a jump to take }
  8493. case hp2.typ of
  8494. ait_instruction:
  8495. begin
  8496. if taicpu(hp2).opcode = A_JMP then
  8497. begin
  8498. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8499. { An unconditional jump follows the conditional jump which will always be false,
  8500. so use this jump's destination for the new jump }
  8501. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8502. Result := True;
  8503. end
  8504. else if taicpu(hp2).opcode = A_JCC then
  8505. begin
  8506. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8507. if condition_in(C_E, taicpu(hp2).condition) then
  8508. begin
  8509. { A second conditional jump follows the conditional jump which will always be false,
  8510. while the second jump is always True, so use this jump's destination for the new jump }
  8511. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8512. Result := True;
  8513. end;
  8514. { Don't risk it if the jump isn't always true (Result remains False) }
  8515. end;
  8516. end;
  8517. else
  8518. { If anything else don't optimise };
  8519. end;
  8520. end;
  8521. if Result then
  8522. begin
  8523. { Just so we have something to insert as a paremeter}
  8524. reference_reset(NewRef, 1, []);
  8525. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8526. { Now actually load the correct parameter (this also
  8527. increases the reference count) }
  8528. NewInstr.loadsymbol(0, DestLabel, 0);
  8529. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8530. begin
  8531. { Get instruction before original label (may not be p under -O3) }
  8532. if not GetLastInstruction(hp1, hp2) then
  8533. { Shouldn't fail here }
  8534. InternalError(2021040701);
  8535. { Before the aligns too }
  8536. while (hp2.typ = ait_align) do
  8537. if not GetLastInstruction(hp2, hp2) then
  8538. { Shouldn't fail here }
  8539. InternalError(2021040702);
  8540. end
  8541. else
  8542. hp2 := p;
  8543. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8544. AsmL.InsertAfter(NewInstr, hp2);
  8545. { Add new alignment field }
  8546. (* AsmL.InsertAfter(
  8547. cai_align.create_max(
  8548. current_settings.alignment.jumpalign,
  8549. current_settings.alignment.jumpalignskipmax
  8550. ),
  8551. NewInstr
  8552. ); *)
  8553. end;
  8554. Exit;
  8555. end;
  8556. end;
  8557. else
  8558. ;
  8559. end;
  8560. end;
  8561. if not GetNextInstruction(p, hp1) then
  8562. Exit;
  8563. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8564. and DoMovCmpMemOpt(p, hp1) then
  8565. begin
  8566. Result := True;
  8567. Exit;
  8568. end
  8569. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8570. begin
  8571. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8572. further, but we can't just put this jump optimisation in pass 1
  8573. because it tends to perform worse when conditional jumps are
  8574. nearby (e.g. when converting CMOV instructions). [Kit] }
  8575. CopyUsedRegs(TempTracking);
  8576. UpdateUsedRegs(tai(p.Next));
  8577. if OptPass2JMP(hp1) then
  8578. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8579. Result := OptPass1MOV(p);
  8580. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8581. returned True and the instruction is still a MOV, thus checking
  8582. the optimisations below }
  8583. { If OptPass2JMP returned False, no optimisations were done to
  8584. the jump and there are no further optimisations that can be done
  8585. to the MOV instruction on this pass }
  8586. { Restore register state }
  8587. RestoreUsedRegs(TempTracking);
  8588. ReleaseUsedRegs(TempTracking);
  8589. end
  8590. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8591. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8592. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8593. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8594. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8595. begin
  8596. { Change:
  8597. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8598. addl/q $x,%reg2 subl/q $x,%reg2
  8599. To:
  8600. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8601. }
  8602. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8603. { be lazy, checking separately for sub would be slightly better }
  8604. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8605. begin
  8606. TransferUsedRegs(TmpUsedRegs);
  8607. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8608. if TryMovArith2Lea(hp1) then
  8609. begin
  8610. Result := True;
  8611. Exit;
  8612. end
  8613. end
  8614. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8615. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8616. { Same as above, but also adds or subtracts to %reg2 in between.
  8617. It's still valid as long as the flags aren't in use }
  8618. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8619. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8620. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8621. { be lazy, checking separately for sub would be slightly better }
  8622. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8623. begin
  8624. TransferUsedRegs(TmpUsedRegs);
  8625. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8626. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8627. if TryMovArith2Lea(hp2) then
  8628. begin
  8629. Result := True;
  8630. Exit;
  8631. end;
  8632. end;
  8633. end
  8634. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8635. {$ifdef x86_64}
  8636. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8637. {$else x86_64}
  8638. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8639. {$endif x86_64}
  8640. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8641. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8642. { mov reg1, reg2 mov reg1, reg2
  8643. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8644. begin
  8645. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8646. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8647. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8648. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8649. TransferUsedRegs(TmpUsedRegs);
  8650. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8651. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8652. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8653. then
  8654. begin
  8655. RemoveCurrentP(p, hp1);
  8656. Result:=true;
  8657. end;
  8658. exit;
  8659. end
  8660. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8661. IsXCHGAcceptable and
  8662. { XCHG doesn't support 8-byte registers }
  8663. (taicpu(p).opsize <> S_B) and
  8664. MatchInstruction(hp1, A_MOV, []) and
  8665. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8666. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8667. GetNextInstruction(hp1, hp2) and
  8668. MatchInstruction(hp2, A_MOV, []) and
  8669. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8670. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8671. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8672. begin
  8673. { mov %reg1,%reg2
  8674. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8675. mov %reg2,%reg3
  8676. (%reg2 not used afterwards)
  8677. Note that xchg takes 3 cycles to execute, and generally mov's take
  8678. only one cycle apiece, but the first two mov's can be executed in
  8679. parallel, only taking 2 cycles overall. Older processors should
  8680. therefore only optimise for size. [Kit]
  8681. }
  8682. TransferUsedRegs(TmpUsedRegs);
  8683. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8684. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8685. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8686. begin
  8687. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8688. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8689. taicpu(hp1).opcode := A_XCHG;
  8690. RemoveCurrentP(p, hp1);
  8691. RemoveInstruction(hp2);
  8692. Result := True;
  8693. Exit;
  8694. end;
  8695. end
  8696. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8697. MatchInstruction(hp1, A_SAR, []) then
  8698. begin
  8699. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8700. begin
  8701. { the use of %edx also covers the opsize being S_L }
  8702. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8703. begin
  8704. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8705. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8706. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8707. begin
  8708. { Change:
  8709. movl %eax,%edx
  8710. sarl $31,%edx
  8711. To:
  8712. cltd
  8713. }
  8714. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8715. RemoveInstruction(hp1);
  8716. taicpu(p).opcode := A_CDQ;
  8717. taicpu(p).opsize := S_NO;
  8718. taicpu(p).clearop(1);
  8719. taicpu(p).clearop(0);
  8720. taicpu(p).ops:=0;
  8721. Result := True;
  8722. end
  8723. else if (cs_opt_size in current_settings.optimizerswitches) and
  8724. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8725. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8726. begin
  8727. { Change:
  8728. movl %edx,%eax
  8729. sarl $31,%edx
  8730. To:
  8731. movl %edx,%eax
  8732. cltd
  8733. Note that this creates a dependency between the two instructions,
  8734. so only perform if optimising for size.
  8735. }
  8736. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8737. taicpu(hp1).opcode := A_CDQ;
  8738. taicpu(hp1).opsize := S_NO;
  8739. taicpu(hp1).clearop(1);
  8740. taicpu(hp1).clearop(0);
  8741. taicpu(hp1).ops:=0;
  8742. end;
  8743. {$ifndef x86_64}
  8744. end
  8745. { Don't bother if CMOV is supported, because a more optimal
  8746. sequence would have been generated for the Abs() intrinsic }
  8747. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8748. { the use of %eax also covers the opsize being S_L }
  8749. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8750. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8751. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8752. GetNextInstruction(hp1, hp2) and
  8753. MatchInstruction(hp2, A_XOR, [S_L]) and
  8754. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8755. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8756. GetNextInstruction(hp2, hp3) and
  8757. MatchInstruction(hp3, A_SUB, [S_L]) and
  8758. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8759. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8760. begin
  8761. { Change:
  8762. movl %eax,%edx
  8763. sarl $31,%eax
  8764. xorl %eax,%edx
  8765. subl %eax,%edx
  8766. (Instruction that uses %edx)
  8767. (%eax deallocated)
  8768. (%edx deallocated)
  8769. To:
  8770. cltd
  8771. xorl %edx,%eax <-- Note the registers have swapped
  8772. subl %edx,%eax
  8773. (Instruction that uses %eax) <-- %eax rather than %edx
  8774. }
  8775. TransferUsedRegs(TmpUsedRegs);
  8776. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8777. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8778. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8779. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8780. begin
  8781. if GetNextInstruction(hp3, hp4) and
  8782. not RegModifiedByInstruction(NR_EDX, hp4) and
  8783. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8784. begin
  8785. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8786. taicpu(p).opcode := A_CDQ;
  8787. taicpu(p).clearop(1);
  8788. taicpu(p).clearop(0);
  8789. taicpu(p).ops:=0;
  8790. RemoveInstruction(hp1);
  8791. taicpu(hp2).loadreg(0, NR_EDX);
  8792. taicpu(hp2).loadreg(1, NR_EAX);
  8793. taicpu(hp3).loadreg(0, NR_EDX);
  8794. taicpu(hp3).loadreg(1, NR_EAX);
  8795. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8796. { Convert references in the following instruction (hp4) from %edx to %eax }
  8797. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8798. with taicpu(hp4).oper[OperIdx]^ do
  8799. case typ of
  8800. top_reg:
  8801. if getsupreg(reg) = RS_EDX then
  8802. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8803. top_ref:
  8804. begin
  8805. if getsupreg(reg) = RS_EDX then
  8806. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8807. if getsupreg(reg) = RS_EDX then
  8808. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8809. end;
  8810. else
  8811. ;
  8812. end;
  8813. end;
  8814. end;
  8815. {$else x86_64}
  8816. end;
  8817. end
  8818. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8819. { the use of %rdx also covers the opsize being S_Q }
  8820. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8821. begin
  8822. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8823. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8824. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8825. begin
  8826. { Change:
  8827. movq %rax,%rdx
  8828. sarq $63,%rdx
  8829. To:
  8830. cqto
  8831. }
  8832. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8833. RemoveInstruction(hp1);
  8834. taicpu(p).opcode := A_CQO;
  8835. taicpu(p).opsize := S_NO;
  8836. taicpu(p).clearop(1);
  8837. taicpu(p).clearop(0);
  8838. taicpu(p).ops:=0;
  8839. Result := True;
  8840. end
  8841. else if (cs_opt_size in current_settings.optimizerswitches) and
  8842. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8843. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8844. begin
  8845. { Change:
  8846. movq %rdx,%rax
  8847. sarq $63,%rdx
  8848. To:
  8849. movq %rdx,%rax
  8850. cqto
  8851. Note that this creates a dependency between the two instructions,
  8852. so only perform if optimising for size.
  8853. }
  8854. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8855. taicpu(hp1).opcode := A_CQO;
  8856. taicpu(hp1).opsize := S_NO;
  8857. taicpu(hp1).clearop(1);
  8858. taicpu(hp1).clearop(0);
  8859. taicpu(hp1).ops:=0;
  8860. {$endif x86_64}
  8861. end;
  8862. end;
  8863. end
  8864. else if MatchInstruction(hp1, A_MOV, []) and
  8865. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8866. { Though "GetNextInstruction" could be factored out, along with
  8867. the instructions that depend on hp2, it is an expensive call that
  8868. should be delayed for as long as possible, hence we do cheaper
  8869. checks first that are likely to be False. [Kit] }
  8870. begin
  8871. if (
  8872. (
  8873. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8874. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8875. (
  8876. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8877. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8878. )
  8879. ) or
  8880. (
  8881. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8882. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8883. (
  8884. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8885. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8886. )
  8887. )
  8888. ) and
  8889. GetNextInstruction(hp1, hp2) and
  8890. MatchInstruction(hp2, A_SAR, []) and
  8891. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8892. begin
  8893. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8894. begin
  8895. { Change:
  8896. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8897. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8898. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8899. To:
  8900. movl r/m,%eax <- Note the change in register
  8901. cltd
  8902. }
  8903. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8904. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8905. taicpu(p).loadreg(1, NR_EAX);
  8906. taicpu(hp1).opcode := A_CDQ;
  8907. taicpu(hp1).clearop(1);
  8908. taicpu(hp1).clearop(0);
  8909. taicpu(hp1).ops:=0;
  8910. RemoveInstruction(hp2);
  8911. (*
  8912. {$ifdef x86_64}
  8913. end
  8914. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8915. { This code sequence does not get generated - however it might become useful
  8916. if and when 128-bit signed integer types make an appearance, so the code
  8917. is kept here for when it is eventually needed. [Kit] }
  8918. (
  8919. (
  8920. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8921. (
  8922. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8923. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8924. )
  8925. ) or
  8926. (
  8927. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8928. (
  8929. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8930. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8931. )
  8932. )
  8933. ) and
  8934. GetNextInstruction(hp1, hp2) and
  8935. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8936. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8937. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8938. begin
  8939. { Change:
  8940. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8941. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8942. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8943. To:
  8944. movq r/m,%rax <- Note the change in register
  8945. cqto
  8946. }
  8947. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8948. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8949. taicpu(p).loadreg(1, NR_RAX);
  8950. taicpu(hp1).opcode := A_CQO;
  8951. taicpu(hp1).clearop(1);
  8952. taicpu(hp1).clearop(0);
  8953. taicpu(hp1).ops:=0;
  8954. RemoveInstruction(hp2);
  8955. {$endif x86_64}
  8956. *)
  8957. end;
  8958. end;
  8959. {$ifdef x86_64}
  8960. end
  8961. else if (taicpu(p).opsize = S_L) and
  8962. (taicpu(p).oper[1]^.typ = top_reg) and
  8963. (
  8964. MatchInstruction(hp1, A_MOV,[]) and
  8965. (taicpu(hp1).opsize = S_L) and
  8966. (taicpu(hp1).oper[1]^.typ = top_reg)
  8967. ) and (
  8968. GetNextInstruction(hp1, hp2) and
  8969. (tai(hp2).typ=ait_instruction) and
  8970. (taicpu(hp2).opsize = S_Q) and
  8971. (
  8972. (
  8973. MatchInstruction(hp2, A_ADD,[]) and
  8974. (taicpu(hp2).opsize = S_Q) and
  8975. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8976. (
  8977. (
  8978. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8979. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8980. ) or (
  8981. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8982. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8983. )
  8984. )
  8985. ) or (
  8986. MatchInstruction(hp2, A_LEA,[]) and
  8987. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8988. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8989. (
  8990. (
  8991. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8992. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8993. ) or (
  8994. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8995. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8996. )
  8997. ) and (
  8998. (
  8999. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9000. ) or (
  9001. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9002. )
  9003. )
  9004. )
  9005. )
  9006. ) and (
  9007. GetNextInstruction(hp2, hp3) and
  9008. MatchInstruction(hp3, A_SHR,[]) and
  9009. (taicpu(hp3).opsize = S_Q) and
  9010. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9011. (taicpu(hp3).oper[0]^.val = 1) and
  9012. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9013. ) then
  9014. begin
  9015. { Change movl x, reg1d movl x, reg1d
  9016. movl y, reg2d movl y, reg2d
  9017. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9018. shrq $1, reg1q shrq $1, reg1q
  9019. ( reg1d and reg2d can be switched around in the first two instructions )
  9020. To movl x, reg1d
  9021. addl y, reg1d
  9022. rcrl $1, reg1d
  9023. This corresponds to the common expression (x + y) shr 1, where
  9024. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9025. smaller code, but won't account for x + y causing an overflow). [Kit]
  9026. }
  9027. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9028. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9029. { Change first MOV command to have the same register as the final output }
  9030. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9031. else
  9032. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9033. { Change second MOV command to an ADD command. This is easier than
  9034. converting the existing command because it means we don't have to
  9035. touch 'y', which might be a complicated reference, and also the
  9036. fact that the third command might either be ADD or LEA. [Kit] }
  9037. taicpu(hp1).opcode := A_ADD;
  9038. { Delete old ADD/LEA instruction }
  9039. RemoveInstruction(hp2);
  9040. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9041. taicpu(hp3).opcode := A_RCR;
  9042. taicpu(hp3).changeopsize(S_L);
  9043. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9044. {$endif x86_64}
  9045. end;
  9046. if FuncMov2Func(p, hp1) then
  9047. begin
  9048. Result := True;
  9049. Exit;
  9050. end;
  9051. end;
  9052. {$push}
  9053. {$q-}{$r-}
  9054. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9055. var
  9056. ThisReg: TRegister;
  9057. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9058. TargetSubReg: TSubRegister;
  9059. hp1, hp2: tai;
  9060. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9061. { Store list of found instructions so we don't have to call
  9062. GetNextInstructionUsingReg multiple times }
  9063. InstrList: array of taicpu;
  9064. InstrMax, Index: Integer;
  9065. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9066. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9067. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9068. WorkingValue: TCgInt;
  9069. PreMessage: string;
  9070. { Data flow analysis }
  9071. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9072. BitwiseOnly, OrXorUsed,
  9073. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9074. function CheckOverflowConditions: Boolean;
  9075. begin
  9076. Result := True;
  9077. if (TestValSignedMax > SignedUpperLimit) then
  9078. UpperSignedOverflow := True;
  9079. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9080. LowerSignedOverflow := True;
  9081. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9082. LowerUnsignedOverflow := True;
  9083. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9084. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9085. begin
  9086. { Absolute overflow }
  9087. Result := False;
  9088. Exit;
  9089. end;
  9090. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9091. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9092. ShiftDownOverflow := True;
  9093. if (TestValMin < 0) or (TestValMax < 0) then
  9094. begin
  9095. LowerUnsignedOverflow := True;
  9096. UpperUnsignedOverflow := True;
  9097. end;
  9098. end;
  9099. function AdjustInitialLoadAndSize: Boolean;
  9100. begin
  9101. Result := False;
  9102. if not p_removed then
  9103. begin
  9104. if TargetSize = MinSize then
  9105. begin
  9106. { Convert the input MOVZX to a MOV }
  9107. if (taicpu(p).oper[0]^.typ = top_reg) and
  9108. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9109. begin
  9110. { Or remove it completely! }
  9111. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9112. RemoveCurrentP(p);
  9113. p_removed := True;
  9114. end
  9115. else
  9116. begin
  9117. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9118. taicpu(p).opcode := A_MOV;
  9119. taicpu(p).oper[1]^.reg := ThisReg;
  9120. taicpu(p).opsize := TargetSize;
  9121. end;
  9122. Result := True;
  9123. end
  9124. else if TargetSize <> MaxSize then
  9125. begin
  9126. case MaxSize of
  9127. S_L:
  9128. if TargetSize = S_W then
  9129. begin
  9130. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9131. taicpu(p).opsize := S_BW;
  9132. taicpu(p).oper[1]^.reg := ThisReg;
  9133. Result := True;
  9134. end
  9135. else
  9136. InternalError(2020112341);
  9137. S_W:
  9138. if TargetSize = S_L then
  9139. begin
  9140. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9141. taicpu(p).opsize := S_BL;
  9142. taicpu(p).oper[1]^.reg := ThisReg;
  9143. Result := True;
  9144. end
  9145. else
  9146. InternalError(2020112342);
  9147. else
  9148. ;
  9149. end;
  9150. end
  9151. else if not hp1_removed and not RegInUse then
  9152. begin
  9153. { If we have something like:
  9154. movzbl (oper),%regd
  9155. add x, %regd
  9156. movzbl %regb, %regd
  9157. We can reduce the register size to the input of the final
  9158. movzbl instruction. Overflows won't have any effect.
  9159. }
  9160. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9161. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9162. begin
  9163. TargetSize := S_B;
  9164. setsubreg(ThisReg, R_SUBL);
  9165. Result := True;
  9166. end
  9167. else if (taicpu(p).opsize = S_WL) and
  9168. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9169. begin
  9170. TargetSize := S_W;
  9171. setsubreg(ThisReg, R_SUBW);
  9172. Result := True;
  9173. end;
  9174. if Result then
  9175. begin
  9176. { Convert the input MOVZX to a MOV }
  9177. if (taicpu(p).oper[0]^.typ = top_reg) and
  9178. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9179. begin
  9180. { Or remove it completely! }
  9181. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9182. RemoveCurrentP(p);
  9183. p_removed := True;
  9184. end
  9185. else
  9186. begin
  9187. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9188. taicpu(p).opcode := A_MOV;
  9189. taicpu(p).oper[1]^.reg := ThisReg;
  9190. taicpu(p).opsize := TargetSize;
  9191. end;
  9192. end;
  9193. end;
  9194. end;
  9195. end;
  9196. procedure AdjustFinalLoad;
  9197. begin
  9198. if not LowerUnsignedOverflow then
  9199. begin
  9200. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9201. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9202. begin
  9203. { Convert the output MOVZX to a MOV }
  9204. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9205. begin
  9206. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9207. if (MinSize = S_B) or
  9208. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9209. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9210. begin
  9211. { Remove it completely! }
  9212. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9213. { Be careful; if p = hp1 and p was also removed, p
  9214. will become a dangling pointer }
  9215. if p = hp1 then
  9216. begin
  9217. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9218. p_removed := True;
  9219. end
  9220. else
  9221. RemoveInstruction(hp1);
  9222. hp1_removed := True;
  9223. end;
  9224. end
  9225. else
  9226. begin
  9227. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9228. taicpu(hp1).opcode := A_MOV;
  9229. taicpu(hp1).oper[0]^.reg := ThisReg;
  9230. taicpu(hp1).opsize := TargetSize;
  9231. end;
  9232. end
  9233. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9234. begin
  9235. { Need to change the size of the output }
  9236. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9237. taicpu(hp1).oper[0]^.reg := ThisReg;
  9238. taicpu(hp1).opsize := S_BL;
  9239. end;
  9240. end;
  9241. end;
  9242. function CompressInstructions: Boolean;
  9243. var
  9244. LocalIndex: Integer;
  9245. begin
  9246. Result := False;
  9247. { The objective here is to try to find a combination that
  9248. removes one of the MOV/Z instructions. }
  9249. if (
  9250. (taicpu(p).oper[0]^.typ <> top_reg) or
  9251. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9252. ) and
  9253. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9254. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9255. begin
  9256. { Make a preference to remove the second MOVZX instruction }
  9257. case taicpu(hp1).opsize of
  9258. S_BL, S_WL:
  9259. begin
  9260. TargetSize := S_L;
  9261. TargetSubReg := R_SUBD;
  9262. end;
  9263. S_BW:
  9264. begin
  9265. TargetSize := S_W;
  9266. TargetSubReg := R_SUBW;
  9267. end;
  9268. else
  9269. InternalError(2020112302);
  9270. end;
  9271. end
  9272. else
  9273. begin
  9274. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9275. begin
  9276. { Exceeded lower bound but not upper bound }
  9277. TargetSize := MaxSize;
  9278. end
  9279. else if not LowerUnsignedOverflow then
  9280. begin
  9281. { Size didn't exceed lower bound }
  9282. TargetSize := MinSize;
  9283. end
  9284. else
  9285. Exit;
  9286. end;
  9287. case TargetSize of
  9288. S_B:
  9289. TargetSubReg := R_SUBL;
  9290. S_W:
  9291. TargetSubReg := R_SUBW;
  9292. S_L:
  9293. TargetSubReg := R_SUBD;
  9294. else
  9295. InternalError(2020112350);
  9296. end;
  9297. { Update the register to its new size }
  9298. setsubreg(ThisReg, TargetSubReg);
  9299. RegInUse := False;
  9300. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9301. begin
  9302. { Check to see if the active register is used afterwards;
  9303. if not, we can change it and make a saving. }
  9304. TransferUsedRegs(TmpUsedRegs);
  9305. { The target register may be marked as in use to cross
  9306. a jump to a distant label, so exclude it }
  9307. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9308. hp2 := p;
  9309. repeat
  9310. { Explicitly check for the excluded register (don't include the first
  9311. instruction as it may be reading from here }
  9312. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9313. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9314. begin
  9315. RegInUse := True;
  9316. Break;
  9317. end;
  9318. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9319. if not GetNextInstruction(hp2, hp2) then
  9320. InternalError(2020112340);
  9321. until (hp2 = hp1);
  9322. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9323. { We might still be able to get away with this }
  9324. RegInUse := not
  9325. (
  9326. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9327. (hp2.typ = ait_instruction) and
  9328. (
  9329. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9330. instruction that doesn't actually contain ThisReg }
  9331. (cs_opt_level3 in current_settings.optimizerswitches) or
  9332. RegInInstruction(ThisReg, hp2)
  9333. ) and
  9334. RegLoadedWithNewValue(ThisReg, hp2)
  9335. );
  9336. if not RegInUse then
  9337. begin
  9338. { Force the register size to the same as this instruction so it can be removed}
  9339. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9340. begin
  9341. TargetSize := S_L;
  9342. TargetSubReg := R_SUBD;
  9343. end
  9344. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9345. begin
  9346. TargetSize := S_W;
  9347. TargetSubReg := R_SUBW;
  9348. end;
  9349. ThisReg := taicpu(hp1).oper[1]^.reg;
  9350. setsubreg(ThisReg, TargetSubReg);
  9351. RegChanged := True;
  9352. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9353. TransferUsedRegs(TmpUsedRegs);
  9354. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9355. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9356. if p = hp1 then
  9357. begin
  9358. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9359. p_removed := True;
  9360. end
  9361. else
  9362. RemoveInstruction(hp1);
  9363. hp1_removed := True;
  9364. { Instruction will become "mov %reg,%reg" }
  9365. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9366. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9367. begin
  9368. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9369. RemoveCurrentP(p);
  9370. p_removed := True;
  9371. end
  9372. else
  9373. taicpu(p).oper[1]^.reg := ThisReg;
  9374. Result := True;
  9375. end
  9376. else
  9377. begin
  9378. if TargetSize <> MaxSize then
  9379. begin
  9380. { Since the register is in use, we have to force it to
  9381. MaxSize otherwise part of it may become undefined later on }
  9382. TargetSize := MaxSize;
  9383. case TargetSize of
  9384. S_B:
  9385. TargetSubReg := R_SUBL;
  9386. S_W:
  9387. TargetSubReg := R_SUBW;
  9388. S_L:
  9389. TargetSubReg := R_SUBD;
  9390. else
  9391. InternalError(2020112351);
  9392. end;
  9393. setsubreg(ThisReg, TargetSubReg);
  9394. end;
  9395. AdjustFinalLoad;
  9396. end;
  9397. end
  9398. else
  9399. AdjustFinalLoad;
  9400. Result := AdjustInitialLoadAndSize or Result;
  9401. { Now go through every instruction we found and change the
  9402. size. If TargetSize = MaxSize, then almost no changes are
  9403. needed and Result can remain False if it hasn't been set
  9404. yet.
  9405. If RegChanged is True, then the register requires changing
  9406. and so the point about TargetSize = MaxSize doesn't apply. }
  9407. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9408. begin
  9409. for LocalIndex := 0 to InstrMax do
  9410. begin
  9411. { If p_removed is true, then the original MOV/Z was removed
  9412. and removing the AND instruction may not be safe if it
  9413. appears first }
  9414. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9415. InternalError(2020112310);
  9416. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9417. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9418. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9419. InstrList[LocalIndex].opsize := TargetSize;
  9420. end;
  9421. Result := True;
  9422. end;
  9423. end;
  9424. begin
  9425. Result := False;
  9426. p_removed := False;
  9427. hp1_removed := False;
  9428. ThisReg := taicpu(p).oper[1]^.reg;
  9429. { Check for:
  9430. movs/z ###,%ecx (or %cx or %rcx)
  9431. ...
  9432. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9433. (dealloc %ecx)
  9434. Change to:
  9435. mov ###,%cl (if ### = %cl, then remove completely)
  9436. ...
  9437. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9438. }
  9439. if (getsupreg(ThisReg) = RS_ECX) and
  9440. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9441. (hp1.typ = ait_instruction) and
  9442. (
  9443. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9444. instruction that doesn't actually contain ECX }
  9445. (cs_opt_level3 in current_settings.optimizerswitches) or
  9446. RegInInstruction(NR_ECX, hp1) or
  9447. (
  9448. { It's common for the shift/rotate's read/write register to be
  9449. initialised in between, so under -O2 and under, search ahead
  9450. one more instruction
  9451. }
  9452. GetNextInstruction(hp1, hp1) and
  9453. (hp1.typ = ait_instruction) and
  9454. RegInInstruction(NR_ECX, hp1)
  9455. )
  9456. ) and
  9457. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9458. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9459. begin
  9460. TransferUsedRegs(TmpUsedRegs);
  9461. hp2 := p;
  9462. repeat
  9463. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9464. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9465. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9466. begin
  9467. case taicpu(p).opsize of
  9468. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9469. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9470. begin
  9471. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9472. RemoveCurrentP(p);
  9473. end
  9474. else
  9475. begin
  9476. taicpu(p).opcode := A_MOV;
  9477. taicpu(p).opsize := S_B;
  9478. taicpu(p).oper[1]^.reg := NR_CL;
  9479. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9480. end;
  9481. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9482. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9483. begin
  9484. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9485. RemoveCurrentP(p);
  9486. end
  9487. else
  9488. begin
  9489. taicpu(p).opcode := A_MOV;
  9490. taicpu(p).opsize := S_W;
  9491. taicpu(p).oper[1]^.reg := NR_CX;
  9492. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9493. end;
  9494. {$ifdef x86_64}
  9495. S_LQ:
  9496. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9497. begin
  9498. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9499. RemoveCurrentP(p);
  9500. end
  9501. else
  9502. begin
  9503. taicpu(p).opcode := A_MOV;
  9504. taicpu(p).opsize := S_L;
  9505. taicpu(p).oper[1]^.reg := NR_ECX;
  9506. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9507. end;
  9508. {$endif x86_64}
  9509. else
  9510. InternalError(2021120401);
  9511. end;
  9512. Result := True;
  9513. Exit;
  9514. end;
  9515. end;
  9516. { This is anything but quick! }
  9517. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9518. Exit;
  9519. SetLength(InstrList, 0);
  9520. InstrMax := -1;
  9521. case taicpu(p).opsize of
  9522. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9523. begin
  9524. {$if defined(i386) or defined(i8086)}
  9525. { If the target size is 8-bit, make sure we can actually encode it }
  9526. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9527. Exit;
  9528. {$endif i386 or i8086}
  9529. LowerLimit := $FF;
  9530. SignedLowerLimit := $7F;
  9531. SignedLowerLimitBottom := -128;
  9532. MinSize := S_B;
  9533. if taicpu(p).opsize = S_BW then
  9534. begin
  9535. MaxSize := S_W;
  9536. UpperLimit := $FFFF;
  9537. SignedUpperLimit := $7FFF;
  9538. SignedUpperLimitBottom := -32768;
  9539. end
  9540. else
  9541. begin
  9542. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9543. MaxSize := S_L;
  9544. UpperLimit := $FFFFFFFF;
  9545. SignedUpperLimit := $7FFFFFFF;
  9546. SignedUpperLimitBottom := -2147483648;
  9547. end;
  9548. end;
  9549. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9550. begin
  9551. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9552. LowerLimit := $FFFF;
  9553. SignedLowerLimit := $7FFF;
  9554. SignedLowerLimitBottom := -32768;
  9555. UpperLimit := $FFFFFFFF;
  9556. SignedUpperLimit := $7FFFFFFF;
  9557. SignedUpperLimitBottom := -2147483648;
  9558. MinSize := S_W;
  9559. MaxSize := S_L;
  9560. end;
  9561. {$ifdef x86_64}
  9562. S_LQ:
  9563. begin
  9564. { Both the lower and upper limits are set to 32-bit. If a limit
  9565. is breached, then optimisation is impossible }
  9566. LowerLimit := $FFFFFFFF;
  9567. SignedLowerLimit := $7FFFFFFF;
  9568. SignedLowerLimitBottom := -2147483648;
  9569. UpperLimit := $FFFFFFFF;
  9570. SignedUpperLimit := $7FFFFFFF;
  9571. SignedUpperLimitBottom := -2147483648;
  9572. MinSize := S_L;
  9573. MaxSize := S_L;
  9574. end;
  9575. {$endif x86_64}
  9576. else
  9577. InternalError(2020112301);
  9578. end;
  9579. TestValMin := 0;
  9580. TestValMax := LowerLimit;
  9581. TestValSignedMax := SignedLowerLimit;
  9582. TryShiftDownLimit := LowerLimit;
  9583. TryShiftDown := S_NO;
  9584. ShiftDownOverflow := False;
  9585. RegChanged := False;
  9586. BitwiseOnly := True;
  9587. OrXorUsed := False;
  9588. UpperSignedOverflow := False;
  9589. LowerSignedOverflow := False;
  9590. UpperUnsignedOverflow := False;
  9591. LowerUnsignedOverflow := False;
  9592. hp1 := p;
  9593. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9594. (hp1.typ = ait_instruction) and
  9595. (
  9596. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9597. instruction that doesn't actually contain ThisReg }
  9598. (cs_opt_level3 in current_settings.optimizerswitches) or
  9599. { This allows this Movx optimisation to work through the SETcc instructions
  9600. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9601. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9602. skip over these SETcc instructions). }
  9603. (taicpu(hp1).opcode = A_SETcc) or
  9604. RegInInstruction(ThisReg, hp1)
  9605. ) do
  9606. begin
  9607. case taicpu(hp1).opcode of
  9608. A_INC,A_DEC:
  9609. begin
  9610. { Has to be an exact match on the register }
  9611. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9612. Break;
  9613. if taicpu(hp1).opcode = A_INC then
  9614. begin
  9615. Inc(TestValMin);
  9616. Inc(TestValMax);
  9617. Inc(TestValSignedMax);
  9618. end
  9619. else
  9620. begin
  9621. Dec(TestValMin);
  9622. Dec(TestValMax);
  9623. Dec(TestValSignedMax);
  9624. end;
  9625. end;
  9626. A_TEST, A_CMP:
  9627. begin
  9628. if (
  9629. { Too high a risk of non-linear behaviour that breaks DFA
  9630. here, unless it's cmp $0,%reg, which is equivalent to
  9631. test %reg,%reg }
  9632. OrXorUsed and
  9633. (taicpu(hp1).opcode = A_CMP) and
  9634. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9635. ) or
  9636. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9637. { Has to be an exact match on the register }
  9638. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9639. (
  9640. { Permit "test %reg,%reg" }
  9641. (taicpu(hp1).opcode = A_TEST) and
  9642. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9643. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9644. ) or
  9645. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9646. { Make sure the comparison value is not smaller than the
  9647. smallest allowed signed value for the minimum size (e.g.
  9648. -128 for 8-bit) }
  9649. not (
  9650. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9651. { Is it in the negative range? }
  9652. (
  9653. (taicpu(hp1).oper[0]^.val < 0) and
  9654. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9655. )
  9656. ) then
  9657. Break;
  9658. { Check to see if the active register is used afterwards }
  9659. TransferUsedRegs(TmpUsedRegs);
  9660. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9661. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9662. begin
  9663. { Make sure the comparison or any previous instructions
  9664. hasn't pushed the test values outside of the range of
  9665. MinSize }
  9666. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9667. begin
  9668. { Exceeded lower bound but not upper bound }
  9669. Exit;
  9670. end
  9671. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9672. begin
  9673. { Size didn't exceed lower bound }
  9674. TargetSize := MinSize;
  9675. end
  9676. else
  9677. Break;
  9678. case TargetSize of
  9679. S_B:
  9680. TargetSubReg := R_SUBL;
  9681. S_W:
  9682. TargetSubReg := R_SUBW;
  9683. S_L:
  9684. TargetSubReg := R_SUBD;
  9685. else
  9686. InternalError(2021051002);
  9687. end;
  9688. if TargetSize <> MaxSize then
  9689. begin
  9690. { Update the register to its new size }
  9691. setsubreg(ThisReg, TargetSubReg);
  9692. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9693. taicpu(hp1).oper[1]^.reg := ThisReg;
  9694. taicpu(hp1).opsize := TargetSize;
  9695. { Convert the input MOVZX to a MOV if necessary }
  9696. AdjustInitialLoadAndSize;
  9697. if (InstrMax >= 0) then
  9698. begin
  9699. for Index := 0 to InstrMax do
  9700. begin
  9701. { If p_removed is true, then the original MOV/Z was removed
  9702. and removing the AND instruction may not be safe if it
  9703. appears first }
  9704. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9705. InternalError(2020112311);
  9706. if InstrList[Index].oper[0]^.typ = top_reg then
  9707. InstrList[Index].oper[0]^.reg := ThisReg;
  9708. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9709. InstrList[Index].opsize := MinSize;
  9710. end;
  9711. end;
  9712. Result := True;
  9713. end;
  9714. Exit;
  9715. end;
  9716. end;
  9717. A_SETcc:
  9718. begin
  9719. { This allows this Movx optimisation to work through the SETcc instructions
  9720. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9721. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9722. skip over these SETcc instructions). }
  9723. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9724. { Of course, break out if the current register is used }
  9725. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9726. Break
  9727. else
  9728. { We must use Continue so the instruction doesn't get added
  9729. to InstrList }
  9730. Continue;
  9731. end;
  9732. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9733. begin
  9734. if
  9735. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9736. { Has to be an exact match on the register }
  9737. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9738. (
  9739. (
  9740. (taicpu(hp1).oper[0]^.typ = top_const) and
  9741. (
  9742. (
  9743. (taicpu(hp1).opcode = A_SHL) and
  9744. (
  9745. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9746. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9747. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9748. )
  9749. ) or (
  9750. (taicpu(hp1).opcode <> A_SHL) and
  9751. (
  9752. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9753. { Is it in the negative range? }
  9754. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9755. )
  9756. )
  9757. )
  9758. ) or (
  9759. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9760. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9761. )
  9762. ) then
  9763. Break;
  9764. { Only process OR and XOR if there are only bitwise operations,
  9765. since otherwise they can too easily fool the data flow
  9766. analysis (they can cause non-linear behaviour) }
  9767. case taicpu(hp1).opcode of
  9768. A_ADD:
  9769. begin
  9770. if OrXorUsed then
  9771. { Too high a risk of non-linear behaviour that breaks DFA here }
  9772. Break
  9773. else
  9774. BitwiseOnly := False;
  9775. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9776. begin
  9777. TestValMin := TestValMin * 2;
  9778. TestValMax := TestValMax * 2;
  9779. TestValSignedMax := TestValSignedMax * 2;
  9780. end
  9781. else
  9782. begin
  9783. WorkingValue := taicpu(hp1).oper[0]^.val;
  9784. TestValMin := TestValMin + WorkingValue;
  9785. TestValMax := TestValMax + WorkingValue;
  9786. TestValSignedMax := TestValSignedMax + WorkingValue;
  9787. end;
  9788. end;
  9789. A_SUB:
  9790. begin
  9791. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9792. begin
  9793. TestValMin := 0;
  9794. TestValMax := 0;
  9795. TestValSignedMax := 0;
  9796. end
  9797. else
  9798. begin
  9799. if OrXorUsed then
  9800. { Too high a risk of non-linear behaviour that breaks DFA here }
  9801. Break
  9802. else
  9803. BitwiseOnly := False;
  9804. WorkingValue := taicpu(hp1).oper[0]^.val;
  9805. TestValMin := TestValMin - WorkingValue;
  9806. TestValMax := TestValMax - WorkingValue;
  9807. TestValSignedMax := TestValSignedMax - WorkingValue;
  9808. end;
  9809. end;
  9810. A_AND:
  9811. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9812. begin
  9813. { we might be able to go smaller if AND appears first }
  9814. if InstrMax = -1 then
  9815. case MinSize of
  9816. S_B:
  9817. ;
  9818. S_W:
  9819. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9820. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9821. begin
  9822. TryShiftDown := S_B;
  9823. TryShiftDownLimit := $FF;
  9824. end;
  9825. S_L:
  9826. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9827. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9828. begin
  9829. TryShiftDown := S_B;
  9830. TryShiftDownLimit := $FF;
  9831. end
  9832. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9833. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9834. begin
  9835. TryShiftDown := S_W;
  9836. TryShiftDownLimit := $FFFF;
  9837. end;
  9838. else
  9839. InternalError(2020112320);
  9840. end;
  9841. WorkingValue := taicpu(hp1).oper[0]^.val;
  9842. TestValMin := TestValMin and WorkingValue;
  9843. TestValMax := TestValMax and WorkingValue;
  9844. TestValSignedMax := TestValSignedMax and WorkingValue;
  9845. end;
  9846. A_OR:
  9847. begin
  9848. if not BitwiseOnly then
  9849. Break;
  9850. OrXorUsed := True;
  9851. WorkingValue := taicpu(hp1).oper[0]^.val;
  9852. TestValMin := TestValMin or WorkingValue;
  9853. TestValMax := TestValMax or WorkingValue;
  9854. TestValSignedMax := TestValSignedMax or WorkingValue;
  9855. end;
  9856. A_XOR:
  9857. begin
  9858. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9859. begin
  9860. TestValMin := 0;
  9861. TestValMax := 0;
  9862. TestValSignedMax := 0;
  9863. end
  9864. else
  9865. begin
  9866. if not BitwiseOnly then
  9867. Break;
  9868. OrXorUsed := True;
  9869. WorkingValue := taicpu(hp1).oper[0]^.val;
  9870. TestValMin := TestValMin xor WorkingValue;
  9871. TestValMax := TestValMax xor WorkingValue;
  9872. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9873. end;
  9874. end;
  9875. A_SHL:
  9876. begin
  9877. BitwiseOnly := False;
  9878. WorkingValue := taicpu(hp1).oper[0]^.val;
  9879. TestValMin := TestValMin shl WorkingValue;
  9880. TestValMax := TestValMax shl WorkingValue;
  9881. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9882. end;
  9883. A_SHR,
  9884. { The first instruction was MOVZX, so the value won't be negative }
  9885. A_SAR:
  9886. begin
  9887. if InstrMax <> -1 then
  9888. BitwiseOnly := False
  9889. else
  9890. { we might be able to go smaller if SHR appears first }
  9891. case MinSize of
  9892. S_B:
  9893. ;
  9894. S_W:
  9895. if (taicpu(hp1).oper[0]^.val >= 8) then
  9896. begin
  9897. TryShiftDown := S_B;
  9898. TryShiftDownLimit := $FF;
  9899. TryShiftDownSignedLimit := $7F;
  9900. TryShiftDownSignedLimitLower := -128;
  9901. end;
  9902. S_L:
  9903. if (taicpu(hp1).oper[0]^.val >= 24) then
  9904. begin
  9905. TryShiftDown := S_B;
  9906. TryShiftDownLimit := $FF;
  9907. TryShiftDownSignedLimit := $7F;
  9908. TryShiftDownSignedLimitLower := -128;
  9909. end
  9910. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9911. begin
  9912. TryShiftDown := S_W;
  9913. TryShiftDownLimit := $FFFF;
  9914. TryShiftDownSignedLimit := $7FFF;
  9915. TryShiftDownSignedLimitLower := -32768;
  9916. end;
  9917. else
  9918. InternalError(2020112321);
  9919. end;
  9920. WorkingValue := taicpu(hp1).oper[0]^.val;
  9921. if taicpu(hp1).opcode = A_SAR then
  9922. begin
  9923. TestValMin := SarInt64(TestValMin, WorkingValue);
  9924. TestValMax := SarInt64(TestValMax, WorkingValue);
  9925. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9926. end
  9927. else
  9928. begin
  9929. TestValMin := TestValMin shr WorkingValue;
  9930. TestValMax := TestValMax shr WorkingValue;
  9931. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9932. end;
  9933. end;
  9934. else
  9935. InternalError(2020112303);
  9936. end;
  9937. end;
  9938. (*
  9939. A_IMUL:
  9940. case taicpu(hp1).ops of
  9941. 2:
  9942. begin
  9943. if not MatchOpType(hp1, top_reg, top_reg) or
  9944. { Has to be an exact match on the register }
  9945. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9946. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9947. Break;
  9948. TestValMin := TestValMin * TestValMin;
  9949. TestValMax := TestValMax * TestValMax;
  9950. TestValSignedMax := TestValSignedMax * TestValMax;
  9951. end;
  9952. 3:
  9953. begin
  9954. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9955. { Has to be an exact match on the register }
  9956. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9957. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9958. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9959. { Is it in the negative range? }
  9960. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9961. Break;
  9962. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9963. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9964. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9965. end;
  9966. else
  9967. Break;
  9968. end;
  9969. A_IDIV:
  9970. case taicpu(hp1).ops of
  9971. 3:
  9972. begin
  9973. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9974. { Has to be an exact match on the register }
  9975. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9976. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9977. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9978. { Is it in the negative range? }
  9979. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9980. Break;
  9981. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9982. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9983. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9984. end;
  9985. else
  9986. Break;
  9987. end;
  9988. *)
  9989. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9990. begin
  9991. { If there are no instructions in between, then we might be able to make a saving }
  9992. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9993. Break;
  9994. { We have something like:
  9995. movzbw %dl,%dx
  9996. ...
  9997. movswl %dx,%edx
  9998. Change the latter to a zero-extension then enter the
  9999. A_MOVZX case branch.
  10000. }
  10001. {$ifdef x86_64}
  10002. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10003. begin
  10004. { this becomes a zero extension from 32-bit to 64-bit, but
  10005. the upper 32 bits are already zero, so just delete the
  10006. instruction }
  10007. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10008. RemoveInstruction(hp1);
  10009. Result := True;
  10010. Exit;
  10011. end
  10012. else
  10013. {$endif x86_64}
  10014. begin
  10015. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10016. taicpu(hp1).opcode := A_MOVZX;
  10017. {$ifdef x86_64}
  10018. case taicpu(hp1).opsize of
  10019. S_BQ:
  10020. begin
  10021. taicpu(hp1).opsize := S_BL;
  10022. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10023. end;
  10024. S_WQ:
  10025. begin
  10026. taicpu(hp1).opsize := S_WL;
  10027. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10028. end;
  10029. S_LQ:
  10030. begin
  10031. taicpu(hp1).opcode := A_MOV;
  10032. taicpu(hp1).opsize := S_L;
  10033. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10034. { In this instance, we need to break out because the
  10035. instruction is no longer MOVZX or MOVSXD }
  10036. Result := True;
  10037. Exit;
  10038. end;
  10039. else
  10040. ;
  10041. end;
  10042. {$endif x86_64}
  10043. Result := CompressInstructions;
  10044. Exit;
  10045. end;
  10046. end;
  10047. A_MOVZX:
  10048. begin
  10049. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10050. Break;
  10051. if (InstrMax = -1) then
  10052. begin
  10053. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10054. begin
  10055. { Optimise around i40003 }
  10056. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10057. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10058. {$ifndef x86_64}
  10059. and (
  10060. (taicpu(p).oper[0]^.typ <> top_reg) or
  10061. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10062. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10063. )
  10064. {$endif not x86_64}
  10065. then
  10066. begin
  10067. if (taicpu(p).oper[0]^.typ = top_reg) then
  10068. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10069. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10070. taicpu(p).opsize := S_BL;
  10071. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10072. RemoveInstruction(hp1);
  10073. Result := True;
  10074. Exit;
  10075. end;
  10076. end
  10077. else
  10078. begin
  10079. { Will return false if the second parameter isn't ThisReg
  10080. (can happen on -O2 and under) }
  10081. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10082. begin
  10083. { The two MOVZX instructions are adjacent, so remove the first one }
  10084. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10085. RemoveCurrentP(p);
  10086. Result := True;
  10087. Exit;
  10088. end;
  10089. Break;
  10090. end;
  10091. end;
  10092. Result := CompressInstructions;
  10093. Exit;
  10094. end;
  10095. else
  10096. { This includes ADC, SBB and IDIV }
  10097. Break;
  10098. end;
  10099. if not CheckOverflowConditions then
  10100. Break;
  10101. { Contains highest index (so instruction count - 1) }
  10102. Inc(InstrMax);
  10103. if InstrMax > High(InstrList) then
  10104. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10105. InstrList[InstrMax] := taicpu(hp1);
  10106. end;
  10107. end;
  10108. {$pop}
  10109. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10110. var
  10111. hp1 : tai;
  10112. begin
  10113. Result:=false;
  10114. if (taicpu(p).ops >= 2) and
  10115. ((taicpu(p).oper[0]^.typ = top_const) or
  10116. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10117. (taicpu(p).oper[1]^.typ = top_reg) and
  10118. ((taicpu(p).ops = 2) or
  10119. ((taicpu(p).oper[2]^.typ = top_reg) and
  10120. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10121. GetLastInstruction(p,hp1) and
  10122. MatchInstruction(hp1,A_MOV,[]) and
  10123. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10124. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10125. begin
  10126. TransferUsedRegs(TmpUsedRegs);
  10127. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10128. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10129. { change
  10130. mov reg1,reg2
  10131. imul y,reg2 to imul y,reg1,reg2 }
  10132. begin
  10133. taicpu(p).ops := 3;
  10134. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10135. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10136. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10137. RemoveInstruction(hp1);
  10138. result:=true;
  10139. end;
  10140. end;
  10141. end;
  10142. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10143. var
  10144. ThisLabel: TAsmLabel;
  10145. begin
  10146. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10147. ThisLabel.decrefs;
  10148. taicpu(p).condition := C_None;
  10149. taicpu(p).opcode := A_RET;
  10150. taicpu(p).is_jmp := false;
  10151. taicpu(p).ops := taicpu(ret_p).ops;
  10152. case taicpu(ret_p).ops of
  10153. 0:
  10154. taicpu(p).clearop(0);
  10155. 1:
  10156. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10157. else
  10158. internalerror(2016041301);
  10159. end;
  10160. { If the original label is now dead, it might turn out that the label
  10161. immediately follows p. As a result, everything beyond it, which will
  10162. be just some final register configuration and a RET instruction, is
  10163. now dead code. [Kit] }
  10164. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10165. running RemoveDeadCodeAfterJump for each RET instruction, because
  10166. this optimisation rarely happens and most RETs appear at the end of
  10167. routines where there is nothing that can be stripped. [Kit] }
  10168. if not ThisLabel.is_used then
  10169. RemoveDeadCodeAfterJump(p);
  10170. end;
  10171. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10172. var
  10173. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10174. Unconditional, PotentialModified: Boolean;
  10175. OperPtr: POper;
  10176. NewRef: TReference;
  10177. InstrList: array of taicpu;
  10178. InstrMax, Index: Integer;
  10179. const
  10180. {$ifdef DEBUG_AOPTCPU}
  10181. SNoFlags: shortstring = ' so the flags aren''t modified';
  10182. {$else DEBUG_AOPTCPU}
  10183. SNoFlags = '';
  10184. {$endif DEBUG_AOPTCPU}
  10185. begin
  10186. Result:=false;
  10187. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10188. begin
  10189. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10190. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10191. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10192. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10193. GetNextInstruction(hp1, hp2) and
  10194. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10195. { Change from: To:
  10196. set(C) %reg j(~C) label
  10197. test %reg,%reg/cmp $0,%reg
  10198. je label
  10199. set(C) %reg j(C) label
  10200. test %reg,%reg/cmp $0,%reg
  10201. jne label
  10202. (Also do something similar with sete/setne instead of je/jne)
  10203. }
  10204. begin
  10205. { Before we do anything else, we need to check the instructions
  10206. in between SETcc and TEST to make sure they don't modify the
  10207. FLAGS register - if -O2 or under, there won't be any
  10208. instructions between SET and TEST }
  10209. TransferUsedRegs(TmpUsedRegs);
  10210. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10211. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10212. begin
  10213. next := p;
  10214. SetLength(InstrList, 0);
  10215. InstrMax := -1;
  10216. PotentialModified := False;
  10217. { Make a note of every instruction that modifies the FLAGS
  10218. register }
  10219. while GetNextInstruction(next, next) and (next <> hp1) do
  10220. begin
  10221. if next.typ <> ait_instruction then
  10222. { GetNextInstructionUsingReg should have returned False }
  10223. InternalError(2021051701);
  10224. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10225. begin
  10226. case taicpu(next).opcode of
  10227. A_SETcc,
  10228. A_CMOVcc,
  10229. A_Jcc:
  10230. begin
  10231. if PotentialModified then
  10232. { Not safe because the flags were modified earlier }
  10233. Exit
  10234. else
  10235. { Condition is the same as the initial SETcc, so this is safe
  10236. (don't add to instruction list though) }
  10237. Continue;
  10238. end;
  10239. A_ADD:
  10240. begin
  10241. if (taicpu(next).opsize = S_B) or
  10242. { LEA doesn't support 8-bit operands }
  10243. (taicpu(next).oper[1]^.typ <> top_reg) or
  10244. { Must write to a register }
  10245. (taicpu(next).oper[0]^.typ = top_ref) then
  10246. { Require a constant or a register }
  10247. Exit;
  10248. PotentialModified := True;
  10249. end;
  10250. A_SUB:
  10251. begin
  10252. if (taicpu(next).opsize = S_B) or
  10253. { LEA doesn't support 8-bit operands }
  10254. (taicpu(next).oper[1]^.typ <> top_reg) or
  10255. { Must write to a register }
  10256. (taicpu(next).oper[0]^.typ <> top_const) or
  10257. (taicpu(next).oper[0]^.val = $80000000) then
  10258. { Can't subtract a register with LEA - also
  10259. check that the value isn't -2^31, as this
  10260. can't be negated }
  10261. Exit;
  10262. PotentialModified := True;
  10263. end;
  10264. A_SAL,
  10265. A_SHL:
  10266. begin
  10267. if (taicpu(next).opsize = S_B) or
  10268. { LEA doesn't support 8-bit operands }
  10269. (taicpu(next).oper[1]^.typ <> top_reg) or
  10270. { Must write to a register }
  10271. (taicpu(next).oper[0]^.typ <> top_const) or
  10272. (taicpu(next).oper[0]^.val < 0) or
  10273. (taicpu(next).oper[0]^.val > 3) then
  10274. Exit;
  10275. PotentialModified := True;
  10276. end;
  10277. A_IMUL:
  10278. begin
  10279. if (taicpu(next).ops <> 3) or
  10280. (taicpu(next).oper[1]^.typ <> top_reg) or
  10281. { Must write to a register }
  10282. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10283. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10284. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10285. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10286. Exit
  10287. else
  10288. PotentialModified := True;
  10289. end;
  10290. else
  10291. { Don't know how to change this, so abort }
  10292. Exit;
  10293. end;
  10294. { Contains highest index (so instruction count - 1) }
  10295. Inc(InstrMax);
  10296. if InstrMax > High(InstrList) then
  10297. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10298. InstrList[InstrMax] := taicpu(next);
  10299. end;
  10300. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10301. end;
  10302. if not Assigned(next) or (next <> hp1) then
  10303. { It should be equal to hp1 }
  10304. InternalError(2021051702);
  10305. { Cycle through each instruction and check to see if we can
  10306. change them to versions that don't modify the flags }
  10307. if (InstrMax >= 0) then
  10308. begin
  10309. for Index := 0 to InstrMax do
  10310. case InstrList[Index].opcode of
  10311. A_ADD:
  10312. begin
  10313. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10314. InstrList[Index].opcode := A_LEA;
  10315. reference_reset(NewRef, 1, []);
  10316. NewRef.base := InstrList[Index].oper[1]^.reg;
  10317. if InstrList[Index].oper[0]^.typ = top_reg then
  10318. begin
  10319. NewRef.index := InstrList[Index].oper[0]^.reg;
  10320. NewRef.scalefactor := 1;
  10321. end
  10322. else
  10323. NewRef.offset := InstrList[Index].oper[0]^.val;
  10324. InstrList[Index].loadref(0, NewRef);
  10325. end;
  10326. A_SUB:
  10327. begin
  10328. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10329. InstrList[Index].opcode := A_LEA;
  10330. reference_reset(NewRef, 1, []);
  10331. NewRef.base := InstrList[Index].oper[1]^.reg;
  10332. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10333. InstrList[Index].loadref(0, NewRef);
  10334. end;
  10335. A_SHL,
  10336. A_SAL:
  10337. begin
  10338. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10339. InstrList[Index].opcode := A_LEA;
  10340. reference_reset(NewRef, 1, []);
  10341. NewRef.index := InstrList[Index].oper[1]^.reg;
  10342. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10343. InstrList[Index].loadref(0, NewRef);
  10344. end;
  10345. A_IMUL:
  10346. begin
  10347. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10348. InstrList[Index].opcode := A_LEA;
  10349. reference_reset(NewRef, 1, []);
  10350. NewRef.index := InstrList[Index].oper[1]^.reg;
  10351. case InstrList[Index].oper[0]^.val of
  10352. 2, 4, 8:
  10353. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10354. else {3, 5 and 9}
  10355. begin
  10356. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10357. NewRef.base := InstrList[Index].oper[1]^.reg;
  10358. end;
  10359. end;
  10360. InstrList[Index].loadref(0, NewRef);
  10361. end;
  10362. else
  10363. InternalError(2021051710);
  10364. end;
  10365. end;
  10366. { Mark the FLAGS register as used across this whole block }
  10367. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10368. end;
  10369. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10370. JumpC := taicpu(hp2).condition;
  10371. Unconditional := False;
  10372. if conditions_equal(JumpC, C_E) then
  10373. SetC := inverse_cond(taicpu(p).condition)
  10374. else if conditions_equal(JumpC, C_NE) then
  10375. SetC := taicpu(p).condition
  10376. else
  10377. { We've got something weird here (and inefficent) }
  10378. begin
  10379. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10380. SetC := C_NONE;
  10381. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10382. if condition_in(C_AE, JumpC) then
  10383. Unconditional := True
  10384. else
  10385. { Not sure what to do with this jump - drop out }
  10386. Exit;
  10387. end;
  10388. RemoveInstruction(hp1);
  10389. if Unconditional then
  10390. MakeUnconditional(taicpu(hp2))
  10391. else
  10392. begin
  10393. if SetC = C_NONE then
  10394. InternalError(2018061402);
  10395. taicpu(hp2).SetCondition(SetC);
  10396. end;
  10397. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10398. TmpUsedRegs }
  10399. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10400. begin
  10401. RemoveCurrentp(p, hp2);
  10402. if taicpu(hp2).opcode = A_SETcc then
  10403. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10404. else
  10405. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10406. end
  10407. else
  10408. if taicpu(hp2).opcode = A_SETcc then
  10409. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10410. else
  10411. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10412. Result := True;
  10413. end
  10414. else if
  10415. { Make sure the instructions are adjacent }
  10416. (
  10417. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10418. GetNextInstruction(p, hp1)
  10419. ) and
  10420. MatchInstruction(hp1, A_MOV, [S_B]) and
  10421. { Writing to memory is allowed }
  10422. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10423. begin
  10424. {
  10425. Watch out for sequences such as:
  10426. set(c)b %regb
  10427. movb %regb,(ref)
  10428. movb $0,1(ref)
  10429. movb $0,2(ref)
  10430. movb $0,3(ref)
  10431. Much more efficient to turn it into:
  10432. movl $0,%regl
  10433. set(c)b %regb
  10434. movl %regl,(ref)
  10435. Or:
  10436. set(c)b %regb
  10437. movzbl %regb,%regl
  10438. movl %regl,(ref)
  10439. }
  10440. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10441. GetNextInstruction(hp1, hp2) and
  10442. MatchInstruction(hp2, A_MOV, [S_B]) and
  10443. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10444. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10445. begin
  10446. { Don't do anything else except set Result to True }
  10447. end
  10448. else
  10449. begin
  10450. if taicpu(p).oper[0]^.typ = top_reg then
  10451. begin
  10452. TransferUsedRegs(TmpUsedRegs);
  10453. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10454. end;
  10455. { If it's not a register, it's a memory address }
  10456. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10457. begin
  10458. { Even if the register is still in use, we can minimise the
  10459. pipeline stall by changing the MOV into another SETcc. }
  10460. taicpu(hp1).opcode := A_SETcc;
  10461. taicpu(hp1).condition := taicpu(p).condition;
  10462. if taicpu(hp1).oper[1]^.typ = top_ref then
  10463. begin
  10464. { Swapping the operand pointers like this is probably a
  10465. bit naughty, but it is far faster than using loadoper
  10466. to transfer the reference from oper[1] to oper[0] if
  10467. you take into account the extra procedure calls and
  10468. the memory allocation and deallocation required }
  10469. OperPtr := taicpu(hp1).oper[1];
  10470. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10471. taicpu(hp1).oper[0] := OperPtr;
  10472. end
  10473. else
  10474. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10475. taicpu(hp1).clearop(1);
  10476. taicpu(hp1).ops := 1;
  10477. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10478. end
  10479. else
  10480. begin
  10481. if taicpu(hp1).oper[1]^.typ = top_reg then
  10482. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10483. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10484. RemoveInstruction(hp1);
  10485. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10486. end
  10487. end;
  10488. Result := True;
  10489. end;
  10490. end;
  10491. end;
  10492. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10493. var
  10494. hp1: tai;
  10495. Count: Integer;
  10496. OrigLabel: TAsmLabel;
  10497. begin
  10498. result := False;
  10499. { Sometimes, the optimisations below can permit this }
  10500. RemoveDeadCodeAfterJump(p);
  10501. 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
  10502. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10503. begin
  10504. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10505. { Also a side-effect of optimisations }
  10506. if CollapseZeroDistJump(p, OrigLabel) then
  10507. begin
  10508. Result := True;
  10509. Exit;
  10510. end;
  10511. hp1 := GetLabelWithSym(OrigLabel);
  10512. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10513. begin
  10514. if taicpu(hp1).opcode = A_RET then
  10515. begin
  10516. {
  10517. change
  10518. jmp .L1
  10519. ...
  10520. .L1:
  10521. ret
  10522. into
  10523. ret
  10524. }
  10525. begin
  10526. ConvertJumpToRET(p, hp1);
  10527. result:=true;
  10528. end;
  10529. end
  10530. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10531. not (cs_opt_size in current_settings.optimizerswitches) and
  10532. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10533. begin
  10534. Result := True;
  10535. Exit;
  10536. end;
  10537. end;
  10538. end;
  10539. end;
  10540. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10541. begin
  10542. Result := assigned(p) and
  10543. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10544. (taicpu(p).oper[1]^.typ = top_reg) and
  10545. (
  10546. (taicpu(p).oper[0]^.typ = top_reg) or
  10547. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10548. it is not expected that this can cause a seg. violation }
  10549. (
  10550. (taicpu(p).oper[0]^.typ = top_ref) and
  10551. { TODO: Can we detect which references become constants at this
  10552. stage so we don't have to do a blanket ban? }
  10553. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10554. (
  10555. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10556. (
  10557. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10558. not RefModified and
  10559. { If the reference also appears in the condition, then we know it's safe, otherwise
  10560. any kind of access violation would have occurred already }
  10561. Assigned(cond_p) and
  10562. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10563. (cond_p.typ = ait_instruction) and
  10564. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10565. { Just consider 2-operand comparison instructions for now to be safe }
  10566. (taicpu(cond_p).ops = 2) and
  10567. (
  10568. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10569. (
  10570. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10571. { Don't risk identical registers but different offsets, as we may have constructs
  10572. such as buffer streams with things like length fields that indicate whether
  10573. any more data follows. And there are probably some contrived examples where
  10574. writing to offsets behind the one being read also lead to access violations }
  10575. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10576. (
  10577. { Check that we're not modifying a register that appears in the reference }
  10578. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10579. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10580. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10581. )
  10582. )
  10583. )
  10584. )
  10585. )
  10586. )
  10587. );
  10588. end;
  10589. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10590. begin
  10591. { Update integer registers, ignoring deallocations }
  10592. repeat
  10593. while assigned(p) and
  10594. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10595. (p.typ = ait_label) or
  10596. ((p.typ = ait_marker) and
  10597. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10598. p := tai(p.next);
  10599. while assigned(p) and
  10600. (p.typ=ait_RegAlloc) Do
  10601. begin
  10602. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10603. begin
  10604. case tai_regalloc(p).ratype of
  10605. ra_alloc :
  10606. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10607. else
  10608. ;
  10609. end;
  10610. end;
  10611. p := tai(p.next);
  10612. end;
  10613. until not(assigned(p)) or
  10614. (not(p.typ in SkipInstr) and
  10615. not((p.typ = ait_label) and
  10616. labelCanBeSkipped(tai_label(p))));
  10617. end;
  10618. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10619. var
  10620. hp1,hp2: tai;
  10621. carryadd_opcode : TAsmOp;
  10622. symbol: TAsmSymbol;
  10623. increg, tmpreg: TRegister;
  10624. RefModified: Boolean;
  10625. {$ifndef i8086}
  10626. { Code and variables specific to CMOV optimisations }
  10627. hp3,hp4,hp5,
  10628. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10629. l, c, w, x : Longint;
  10630. condition, second_condition : TAsmCond;
  10631. FoundMatchingJump, RegMatch: Boolean;
  10632. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10633. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10634. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10635. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10636. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10637. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10638. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10639. new register to store the constant }
  10640. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10641. var
  10642. RegSize: TSubRegister;
  10643. CurrentVal: TCGInt;
  10644. ANewReg: TRegister;
  10645. X: ShortInt;
  10646. begin
  10647. Result := False;
  10648. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10649. Exit;
  10650. if StoredCount >= MAX_CMOV_REGISTERS then
  10651. { Arrays are full }
  10652. Exit;
  10653. { Remember that CMOV can't encode 8-bit registers }
  10654. case taicpu(p).opsize of
  10655. S_W:
  10656. RegSize := R_SUBW;
  10657. S_L:
  10658. RegSize := R_SUBD;
  10659. {$ifdef x86_64}
  10660. S_Q:
  10661. RegSize := R_SUBQ;
  10662. {$endif x86_64}
  10663. else
  10664. InternalError(2021100401);
  10665. end;
  10666. { See if the value has already been reserved for another CMOV instruction }
  10667. CurrentVal := taicpu(p).oper[0]^.val;
  10668. for X := 0 to StoredCount - 1 do
  10669. if ConstVals[X] = CurrentVal then
  10670. begin
  10671. ConstRegs[StoredCount] := ConstRegs[X];
  10672. ConstSizes[StoredCount] := RegSize;
  10673. ConstVals[StoredCount] := CurrentVal;
  10674. Result := True;
  10675. Inc(StoredCount);
  10676. { Don't increase CMOVCount this time, since we're re-using a register }
  10677. Exit;
  10678. end;
  10679. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10680. if ANewReg = NR_NO then
  10681. { No free registers }
  10682. Exit;
  10683. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10684. up vying for the same register }
  10685. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10686. ConstRegs[StoredCount] := ANewReg;
  10687. ConstSizes[StoredCount] := RegSize;
  10688. ConstVals[StoredCount] := CurrentVal;
  10689. Inc(StoredCount);
  10690. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10691. MOV required adds complexity and will cause diminishing returns
  10692. sooner than normal. This is more of an approximate weighting than
  10693. anything else. }
  10694. Inc(CMOVCount);
  10695. Result := True;
  10696. end;
  10697. {$endif i8086}
  10698. begin
  10699. result:=false;
  10700. if GetNextInstruction(p,hp1) then
  10701. begin
  10702. if (hp1.typ=ait_label) then
  10703. begin
  10704. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10705. Exit;
  10706. end
  10707. else if (hp1.typ<>ait_instruction) then
  10708. Exit;
  10709. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10710. if (
  10711. (
  10712. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10713. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10714. (Taicpu(hp1).oper[0]^.val=1)
  10715. ) or
  10716. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10717. ) and
  10718. GetNextInstruction(hp1,hp2) and
  10719. SkipAligns(hp2, hp2) and
  10720. (hp2.typ = ait_label) and
  10721. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10722. { jb @@1 cmc
  10723. inc/dec operand --> adc/sbb operand,0
  10724. @@1:
  10725. ... and ...
  10726. jnb @@1
  10727. inc/dec operand --> adc/sbb operand,0
  10728. @@1: }
  10729. begin
  10730. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10731. begin
  10732. case taicpu(hp1).opcode of
  10733. A_INC,
  10734. A_ADD:
  10735. carryadd_opcode:=A_ADC;
  10736. A_DEC,
  10737. A_SUB:
  10738. carryadd_opcode:=A_SBB;
  10739. else
  10740. InternalError(2021011001);
  10741. end;
  10742. Taicpu(p).clearop(0);
  10743. Taicpu(p).ops:=0;
  10744. Taicpu(p).is_jmp:=false;
  10745. Taicpu(p).opcode:=A_CMC;
  10746. Taicpu(p).condition:=C_NONE;
  10747. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10748. Taicpu(hp1).ops:=2;
  10749. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10750. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10751. else
  10752. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10753. Taicpu(hp1).loadconst(0,0);
  10754. Taicpu(hp1).opcode:=carryadd_opcode;
  10755. result:=true;
  10756. exit;
  10757. end
  10758. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10759. begin
  10760. case taicpu(hp1).opcode of
  10761. A_INC,
  10762. A_ADD:
  10763. carryadd_opcode:=A_ADC;
  10764. A_DEC,
  10765. A_SUB:
  10766. carryadd_opcode:=A_SBB;
  10767. else
  10768. InternalError(2021011002);
  10769. end;
  10770. Taicpu(hp1).ops:=2;
  10771. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10772. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10773. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10774. else
  10775. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10776. Taicpu(hp1).loadconst(0,0);
  10777. Taicpu(hp1).opcode:=carryadd_opcode;
  10778. RemoveCurrentP(p, hp1);
  10779. result:=true;
  10780. exit;
  10781. end
  10782. {
  10783. jcc @@1 setcc tmpreg
  10784. inc/dec/add/sub operand -> (movzx tmpreg)
  10785. @@1: add/sub tmpreg,operand
  10786. While this increases code size slightly, it makes the code much faster if the
  10787. jump is unpredictable
  10788. }
  10789. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10790. begin
  10791. { search for an available register which is volatile }
  10792. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10793. if increg <> NR_NO then
  10794. begin
  10795. { We don't need to check if tmpreg is in hp1 or not, because
  10796. it will be marked as in use at p (if not, this is
  10797. indictive of a compiler bug). }
  10798. TAsmLabel(symbol).decrefs;
  10799. Taicpu(p).clearop(0);
  10800. Taicpu(p).ops:=1;
  10801. Taicpu(p).is_jmp:=false;
  10802. Taicpu(p).opcode:=A_SETcc;
  10803. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10804. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10805. Taicpu(p).loadreg(0,increg);
  10806. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10807. begin
  10808. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10809. R_SUBW:
  10810. begin
  10811. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10812. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10813. end;
  10814. R_SUBD:
  10815. begin
  10816. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10817. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10818. end;
  10819. {$ifdef x86_64}
  10820. R_SUBQ:
  10821. begin
  10822. { MOVZX doesn't have a 64-bit variant, because
  10823. the 32-bit version implicitly zeroes the
  10824. upper 32-bits of the destination register }
  10825. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10826. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10827. setsubreg(tmpreg, R_SUBQ);
  10828. end;
  10829. {$endif x86_64}
  10830. else
  10831. Internalerror(2020030601);
  10832. end;
  10833. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10834. asml.InsertAfter(hp2,p);
  10835. end
  10836. else
  10837. tmpreg := increg;
  10838. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10839. begin
  10840. Taicpu(hp1).ops:=2;
  10841. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10842. end;
  10843. Taicpu(hp1).loadreg(0,tmpreg);
  10844. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10845. Result := True;
  10846. { p is no longer a Jcc instruction, so exit }
  10847. Exit;
  10848. end;
  10849. end;
  10850. end;
  10851. { Detect the following:
  10852. jmp<cond> @Lbl1
  10853. jmp @Lbl2
  10854. ...
  10855. @Lbl1:
  10856. ret
  10857. Change to:
  10858. jmp<inv_cond> @Lbl2
  10859. ret
  10860. }
  10861. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10862. begin
  10863. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10864. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10865. MatchInstruction(hp2,A_RET,[S_NO]) then
  10866. begin
  10867. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10868. { Change label address to that of the unconditional jump }
  10869. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10870. TAsmLabel(symbol).DecRefs;
  10871. taicpu(hp1).opcode := A_RET;
  10872. taicpu(hp1).is_jmp := false;
  10873. taicpu(hp1).ops := taicpu(hp2).ops;
  10874. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10875. case taicpu(hp2).ops of
  10876. 0:
  10877. taicpu(hp1).clearop(0);
  10878. 1:
  10879. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10880. else
  10881. internalerror(2016041302);
  10882. end;
  10883. end;
  10884. {$ifndef i8086}
  10885. end
  10886. {
  10887. convert
  10888. j<c> .L1
  10889. mov 1,reg
  10890. jmp .L2
  10891. .L1
  10892. mov 0,reg
  10893. .L2
  10894. into
  10895. mov 0,reg
  10896. set<not(c)> reg
  10897. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10898. would destroy the flag contents
  10899. }
  10900. else if MatchInstruction(hp1,A_MOV,[]) and
  10901. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10902. {$ifdef i386}
  10903. (
  10904. { Under i386, ESI, EDI, EBP and ESP
  10905. don't have an 8-bit representation }
  10906. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10907. ) and
  10908. {$endif i386}
  10909. (taicpu(hp1).oper[0]^.val=1) and
  10910. GetNextInstruction(hp1,hp2) and
  10911. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10912. GetNextInstruction(hp2,hp3) and
  10913. { skip align }
  10914. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10915. (hp3.typ=ait_label) and
  10916. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10917. (tai_label(hp3).labsym.getrefs=1) and
  10918. GetNextInstruction(hp3,hp4) and
  10919. MatchInstruction(hp4,A_MOV,[]) and
  10920. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10921. (taicpu(hp4).oper[0]^.val=0) and
  10922. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10923. GetNextInstruction(hp4,hp5) and
  10924. (hp5.typ=ait_label) and
  10925. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10926. (tai_label(hp5).labsym.getrefs=1) then
  10927. begin
  10928. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10929. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10930. { remove last label }
  10931. RemoveInstruction(hp5);
  10932. { remove second label }
  10933. RemoveInstruction(hp3);
  10934. { if align is present remove it }
  10935. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10936. RemoveInstruction(hp3);
  10937. { remove jmp }
  10938. RemoveInstruction(hp2);
  10939. if taicpu(hp1).opsize=S_B then
  10940. RemoveInstruction(hp1)
  10941. else
  10942. taicpu(hp1).loadconst(0,0);
  10943. taicpu(hp4).opcode:=A_SETcc;
  10944. taicpu(hp4).opsize:=S_B;
  10945. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10946. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10947. taicpu(hp4).opercnt:=1;
  10948. taicpu(hp4).ops:=1;
  10949. taicpu(hp4).freeop(1);
  10950. RemoveCurrentP(p);
  10951. Result:=true;
  10952. exit;
  10953. end
  10954. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10955. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10956. begin
  10957. { check for
  10958. jCC xxx
  10959. <several movs>
  10960. xxx:
  10961. Also spot:
  10962. Jcc xxx
  10963. <several movs>
  10964. jmp xxx
  10965. Change to:
  10966. <several cmovs with inverted condition>
  10967. jmp xxx (only for the 2nd case)
  10968. }
  10969. hp2 := p;
  10970. hp_lblxxx := hp1;
  10971. hp_flagalloc := nil;
  10972. hp_stop := nil;
  10973. FoundMatchingJump := False;
  10974. { Remember the first instruction in the first block of MOVs }
  10975. hpmov1 := hp1;
  10976. TransferUsedRegs(TmpUsedRegs);
  10977. while assigned(hp_lblxxx) and
  10978. { stop on labels }
  10979. (hp_lblxxx.typ <> ait_label) do
  10980. begin
  10981. { Keep track of all integer registers that are used }
  10982. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10983. if hp_lblxxx.typ = ait_instruction then
  10984. begin
  10985. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10986. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10987. begin
  10988. hp_stop := hp_lblxxx;
  10989. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10990. begin
  10991. { We found Jcc xxx; <several movs>; Jmp xxx }
  10992. FoundMatchingJump := True;
  10993. Break;
  10994. end;
  10995. { If it's not the jump we're looking for, it's
  10996. possibly the "if..else" variant }
  10997. end
  10998. { Check to see if we have a valid MOV instruction instead }
  10999. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11000. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11001. Break
  11002. else
  11003. { This will be a valid MOV }
  11004. hp_stop := hp_lblxxx;
  11005. end;
  11006. hp2 := hp_lblxxx;
  11007. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11008. end;
  11009. { Just make sure the last MOV is included if there's no jump }
  11010. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11011. hp_stop := hp_lblxxx;
  11012. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11013. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11014. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11015. jmp yyy; xxx:; movs; yyy:" variation }
  11016. if assigned(hp_lblxxx) and
  11017. (
  11018. { If we found JMP xxx, we don't actually need a label
  11019. (hp_lblxxx is the JMP instruction instead) }
  11020. FoundMatchingJump or
  11021. { Make sure we actually have the right label }
  11022. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11023. ) then
  11024. begin
  11025. { Use TmpUsedRegs to track registers that we reserve }
  11026. { When allocating temporary registers, try to look one
  11027. instruction back, as defining them before a CMP or TEST
  11028. instruction will be faster, and also avoid picking a
  11029. register that was only just deallocated }
  11030. if GetLastInstruction(p, hp_prev) and
  11031. MatchInstruction(hp_prev, [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
  11032. begin
  11033. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11034. for l := 0 to 1 do
  11035. with taicpu(hp_prev).oper[l]^ do
  11036. case typ of
  11037. top_reg:
  11038. if getregtype(reg) = R_INTREGISTER then
  11039. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11040. top_ref:
  11041. begin
  11042. if
  11043. {$ifdef x86_64}
  11044. (ref^.base <> NR_RIP) and
  11045. {$endif x86_64}
  11046. (ref^.base <> NR_NO) then
  11047. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11048. if (ref^.index <> NR_NO) then
  11049. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11050. end
  11051. else
  11052. ;
  11053. end;
  11054. { When inserting instructions before hp_prev, try to insert
  11055. them before the allocation of the FLAGS register }
  11056. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11057. { If not found, set it equal to hp_prev so it's something sensible }
  11058. hp_flagalloc := hp_prev;
  11059. hp_prev2 := nil;
  11060. { When dealing with a comparison against zero, take
  11061. note of the instruction before it to see if we can
  11062. move instructions further back in order to benefit
  11063. PostPeepholeOptTestOr.
  11064. }
  11065. if (
  11066. (
  11067. (taicpu(hp_prev).opcode = A_CMP) and
  11068. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11069. ) or
  11070. (
  11071. (taicpu(hp_prev).opcode = A_TEST) and
  11072. (
  11073. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11074. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11075. )
  11076. )
  11077. ) and
  11078. GetLastInstruction(hp_prev, hp_prev2) then
  11079. begin
  11080. if (hp_prev2.typ = ait_instruction) and
  11081. { These instructions set the zero flag if the result is zero }
  11082. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11083. begin
  11084. { Also mark all the registers in this previous instruction
  11085. as 'in use', even if they've just been deallocated }
  11086. for l := 0 to 1 do
  11087. with taicpu(hp_prev2).oper[l]^ do
  11088. case typ of
  11089. top_reg:
  11090. if getregtype(reg) = R_INTREGISTER then
  11091. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11092. top_ref:
  11093. begin
  11094. if
  11095. {$ifdef x86_64}
  11096. (ref^.base <> NR_RIP) and
  11097. {$endif x86_64}
  11098. (ref^.base <> NR_NO) then
  11099. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11100. if (ref^.index <> NR_NO) then
  11101. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11102. end
  11103. else
  11104. ;
  11105. end;
  11106. end
  11107. else
  11108. { Unsuitable instruction }
  11109. hp_prev2 := nil;
  11110. end;
  11111. end
  11112. else
  11113. begin
  11114. hp_prev := p;
  11115. { When inserting instructions before hp_prev, try to insert
  11116. them before the allocation of the FLAGS register }
  11117. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11118. { If not found, set it equal to p so it's something sensible }
  11119. hp_flagalloc := p;
  11120. hp_prev2 := nil;
  11121. end;
  11122. l := 0;
  11123. c := 0;
  11124. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11125. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11126. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11127. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11128. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11129. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11130. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11131. RefModified := False;
  11132. while assigned(hp1) and
  11133. { Stop on the label we found }
  11134. (hp1 <> hp_lblxxx) do
  11135. begin
  11136. case hp1.typ of
  11137. ait_instruction:
  11138. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11139. begin
  11140. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11141. begin
  11142. Inc(l);
  11143. { MOV instruction will be writing to a register }
  11144. if Assigned(hp_prev) and
  11145. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11146. (hp_prev.typ = ait_instruction) and
  11147. (taicpu(hp_prev).ops = 2) and
  11148. (
  11149. (
  11150. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11151. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11152. ) or
  11153. (
  11154. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11155. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11156. )
  11157. ) then
  11158. { It is no longer safe to use the reference in the condition.
  11159. this prevents problems such as:
  11160. mov (%reg),%reg
  11161. mov (%reg),...
  11162. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11163. (fixes #40165)
  11164. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11165. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11166. }
  11167. RefModified := True;
  11168. end
  11169. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11170. { CMOV with constants grows the code size }
  11171. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11172. begin
  11173. { Register was reserved by TryCMOVConst and
  11174. stored on ConstRegs[c] }
  11175. end
  11176. else
  11177. Break;
  11178. end
  11179. else
  11180. Break;
  11181. else
  11182. ;
  11183. end;
  11184. GetNextInstruction(hp1,hp1);
  11185. end;
  11186. if (hp1 = hp_lblxxx) then
  11187. begin
  11188. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11189. begin
  11190. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11191. TmpUsedRegs[R_INTREGISTER].Clear;
  11192. x := 0;
  11193. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11194. condition := inverse_cond(taicpu(p).condition);
  11195. UpdateUsedRegs(tai(p.next));
  11196. hp1 := hpmov1;
  11197. repeat
  11198. if not Assigned(hp1) then
  11199. InternalError(2018062900);
  11200. if (hp1.typ = ait_instruction) then
  11201. begin
  11202. { Extra safeguard }
  11203. if (taicpu(hp1).opcode <> A_MOV) then
  11204. InternalError(2018062901);
  11205. if taicpu(hp1).oper[0]^.typ = top_const then
  11206. begin
  11207. if x >= MAX_CMOV_REGISTERS then
  11208. InternalError(2021100410);
  11209. { If it's in TmpUsedRegs, then this register
  11210. is being used more than once and hence has
  11211. already had its value defined (it gets
  11212. added to UsedRegs through AllocRegBetween
  11213. below) }
  11214. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11215. begin
  11216. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11217. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11218. asml.InsertBefore(hp_new, hp_flagalloc);
  11219. if Assigned(hp_prev2) then
  11220. TrySwapMovOp(hp_prev2, hp_new);
  11221. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11222. ConstMovs[X] := hp_new;
  11223. end
  11224. else
  11225. { We just need an instruction between hp_prev and hp1
  11226. where we know the register is marked as in use }
  11227. hp_new := hpmov1;
  11228. { Keep track of largest write for this register so it can be optimised later }
  11229. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11230. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11231. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11232. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11233. Inc(x);
  11234. end;
  11235. taicpu(hp1).opcode := A_CMOVcc;
  11236. taicpu(hp1).condition := condition;
  11237. end;
  11238. UpdateUsedRegs(tai(hp1.next));
  11239. GetNextInstruction(hp1, hp1);
  11240. until (hp1 = hp_lblxxx);
  11241. { Update initialisation MOVs to the smallest possible size }
  11242. for c := 0 to x - 1 do
  11243. if Assigned(ConstMovs[c]) then
  11244. begin
  11245. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11246. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11247. end;
  11248. hp2 := hp_lblxxx;
  11249. repeat
  11250. if not Assigned(hp2) then
  11251. InternalError(2018062910);
  11252. case hp2.typ of
  11253. ait_label:
  11254. { What we expected - break out of the loop (it won't be a dead label at the top of
  11255. a cluster because that was optimised at an earlier stage) }
  11256. Break;
  11257. ait_align:
  11258. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11259. begin
  11260. hp2 := tai(hp2.Next);
  11261. Continue;
  11262. end;
  11263. ait_instruction:
  11264. begin
  11265. if taicpu(hp2).opcode<>A_JMP then
  11266. InternalError(2018062912);
  11267. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11268. Break;
  11269. end
  11270. else
  11271. begin
  11272. { Might be a comment or temporary allocation entry }
  11273. if not (hp2.typ in SkipInstr) then
  11274. InternalError(2018062911);
  11275. hp2 := tai(hp2.Next);
  11276. Continue;
  11277. end;
  11278. end;
  11279. until False;
  11280. { Now we can safely decrement the reference count }
  11281. tasmlabel(symbol).decrefs;
  11282. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11283. { Remove the original jump }
  11284. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11285. if hp2.typ=ait_instruction then
  11286. begin
  11287. p := hp2;
  11288. Result := True;
  11289. end
  11290. else
  11291. begin
  11292. UpdateUsedRegs(tai(hp2.next));
  11293. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11294. { Remove the label if this is its final reference }
  11295. if (tasmlabel(symbol).getrefs=0) then
  11296. begin
  11297. { Make sure the aligns get stripped too }
  11298. hp1 := tai(hp_lblxxx.Previous);
  11299. while Assigned(hp1) and (hp1.typ = ait_align) do
  11300. begin
  11301. hp_lblxxx := hp1;
  11302. hp1 := tai(hp_lblxxx.Previous);
  11303. end;
  11304. StripLabelFast(hp_lblxxx);
  11305. end;
  11306. end;
  11307. Exit;
  11308. end;
  11309. end
  11310. else if assigned(hp_lblxxx) and
  11311. { check further for
  11312. jCC xxx
  11313. <several movs 1>
  11314. jmp yyy
  11315. xxx:
  11316. <several movs 2>
  11317. yyy:
  11318. }
  11319. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11320. { hp1 should be pointing to jmp yyy }
  11321. MatchInstruction(hp1, A_JMP, []) and
  11322. { real label and jump, no further references to the
  11323. label are allowed }
  11324. (TAsmLabel(symbol).getrefs=1) and
  11325. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11326. begin
  11327. hp_jump := hp1;
  11328. { Don't set c to zero }
  11329. l := 0;
  11330. w := 0;
  11331. GetNextInstruction(hp_lblxxx, hpmov2);
  11332. hp2 := hp_lblxxx;
  11333. hp_lblyyy := hpmov2;
  11334. while assigned(hp_lblyyy) and
  11335. { stop on labels }
  11336. (hp_lblyyy.typ <> ait_label) do
  11337. begin
  11338. { Keep track of all integer registers that are used }
  11339. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11340. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11341. Break;
  11342. hp2 := hp_lblyyy;
  11343. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11344. end;
  11345. { Analyse the second batch of MOVs to see if the setup is valid }
  11346. RefModified := False;
  11347. hp1 := hpmov2;
  11348. while assigned(hp1) and
  11349. (hp1 <> hp_lblyyy) do
  11350. begin
  11351. case hp1.typ of
  11352. ait_instruction:
  11353. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11354. begin
  11355. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11356. begin
  11357. Inc(l);
  11358. { MOV instruction will be writing to a register }
  11359. if Assigned(hp_prev) and
  11360. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11361. (hp_prev.typ = ait_instruction) and
  11362. (taicpu(hp_prev).ops = 2) and
  11363. (
  11364. (
  11365. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11366. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11367. ) or
  11368. (
  11369. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11370. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11371. )
  11372. ) then
  11373. { It is no longer safe to use the reference in the condition.
  11374. this prevents problems such as:
  11375. mov (%reg),%reg
  11376. mov (%reg),...
  11377. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11378. (fixes #40165)
  11379. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11380. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11381. }
  11382. RefModified := True;
  11383. end
  11384. else if not (cs_opt_size in current_settings.optimizerswitches)
  11385. { CMOV with constants grows the code size }
  11386. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11387. begin
  11388. { Register was reserved by TryCMOVConst and
  11389. stored on ConstRegs[c] }
  11390. end
  11391. else
  11392. Break;
  11393. end
  11394. else
  11395. Break;
  11396. else
  11397. ;
  11398. end;
  11399. GetNextInstruction(hp1,hp1);
  11400. end;
  11401. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11402. TmpUsedRegs[R_INTREGISTER].Clear;
  11403. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11404. (hp1 = hp_lblyyy) and
  11405. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11406. begin
  11407. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11408. second_condition := taicpu(p).condition;
  11409. condition := inverse_cond(taicpu(p).condition);
  11410. UpdateUsedRegs(tai(p.next));
  11411. { Scan through the first set of MOVs to update UsedRegs,
  11412. but don't process them yet }
  11413. hp1 := hpmov1;
  11414. repeat
  11415. if not Assigned(hp1) then
  11416. InternalError(2018062901);
  11417. UpdateUsedRegs(tai(hp1.next));
  11418. GetNextInstruction(hp1, hp1);
  11419. until (hp1 = hp_lblxxx);
  11420. UpdateUsedRegs(tai(hp_lblxxx.next));
  11421. { Process the second set of MOVs first,
  11422. because if a destination register is
  11423. shared between the first and second MOV
  11424. sets, it is more efficient to turn the
  11425. first one into a MOV instruction and place
  11426. it before the CMP if possible, but we
  11427. won't know which registers are shared
  11428. until we've processed at least one list,
  11429. so we might as well make it the second
  11430. one since that won't be modified again. }
  11431. hp1 := hpmov2;
  11432. repeat
  11433. if not Assigned(hp1) then
  11434. InternalError(2018062902);
  11435. if (hp1.typ = ait_instruction) then
  11436. begin
  11437. { Extra safeguard }
  11438. if (taicpu(hp1).opcode <> A_MOV) then
  11439. InternalError(2018062903);
  11440. if taicpu(hp1).oper[0]^.typ = top_const then
  11441. begin
  11442. RegMatch := False;
  11443. for x := 0 to c - 1 do
  11444. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11445. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11446. begin
  11447. RegMatch := True;
  11448. { If it's in TmpUsedRegs, then this register
  11449. is being used more than once and hence has
  11450. already had its value defined (it gets
  11451. added to UsedRegs through AllocRegBetween
  11452. below) }
  11453. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11454. begin
  11455. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11456. asml.InsertBefore(hp_new, hp_flagalloc);
  11457. if Assigned(hp_prev2) then
  11458. TrySwapMovOp(hp_prev2, hp_new);
  11459. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11460. ConstMovs[X] := hp_new;
  11461. end
  11462. else
  11463. { We just need an instruction between hp_prev and hp1
  11464. where we know the register is marked as in use }
  11465. hp_new := hpmov2;
  11466. { Keep track of largest write for this register so it can be optimised later }
  11467. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11468. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11469. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11470. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11471. Break;
  11472. end;
  11473. if not RegMatch then
  11474. InternalError(2021100411);
  11475. end;
  11476. taicpu(hp1).opcode := A_CMOVcc;
  11477. taicpu(hp1).condition := second_condition;
  11478. { Store these writes to search for
  11479. duplicates later on }
  11480. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11481. Inc(w);
  11482. end;
  11483. UpdateUsedRegs(tai(hp1.next));
  11484. GetNextInstruction(hp1, hp1);
  11485. until (hp1 = hp_lblyyy);
  11486. { Now do the first set of MOVs }
  11487. hp1 := hpmov1;
  11488. repeat
  11489. if not Assigned(hp1) then
  11490. InternalError(2018062904);
  11491. if (hp1.typ = ait_instruction) then
  11492. begin
  11493. RegMatch := False;
  11494. { Extra safeguard }
  11495. if (taicpu(hp1).opcode <> A_MOV) then
  11496. InternalError(2018062905);
  11497. { Search through the RegWrites list to see
  11498. if there are any opposing CMOV pairs that
  11499. write to the same register }
  11500. for x := 0 to w - 1 do
  11501. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11502. begin
  11503. { We have a match. Keep this as a MOV }
  11504. { Move ahead in preparation }
  11505. GetNextInstruction(hp1, hp1);
  11506. RegMatch := True;
  11507. Break;
  11508. end;
  11509. if RegMatch then
  11510. Continue;
  11511. if taicpu(hp1).oper[0]^.typ = top_const then
  11512. begin
  11513. RegMatch := False;
  11514. for x := 0 to c - 1 do
  11515. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11516. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11517. begin
  11518. RegMatch := True;
  11519. { If it's in TmpUsedRegs, then this register
  11520. is being used more than once and hence has
  11521. already had its value defined (it gets
  11522. added to UsedRegs through AllocRegBetween
  11523. below) }
  11524. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11525. begin
  11526. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11527. asml.InsertBefore(hp_new, hp_flagalloc);
  11528. if Assigned(hp_prev2) then
  11529. TrySwapMovOp(hp_prev2, hp_new);
  11530. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11531. ConstMovs[X] := hp_new;
  11532. end
  11533. else
  11534. { We just need an instruction between hp_prev and hp1
  11535. where we know the register is marked as in use }
  11536. hp_new := hpmov1;
  11537. { Keep track of largest write for this register so it can be optimised later }
  11538. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11539. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11540. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11541. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11542. Break;
  11543. end;
  11544. if not RegMatch then
  11545. InternalError(2021100412);
  11546. end;
  11547. taicpu(hp1).opcode := A_CMOVcc;
  11548. taicpu(hp1).condition := condition;
  11549. end;
  11550. GetNextInstruction(hp1, hp1);
  11551. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11552. { Update initialisation MOVs to the smallest possible size }
  11553. for x := 0 to c - 1 do
  11554. if Assigned(ConstMovs[x]) then
  11555. begin
  11556. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11557. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11558. end;
  11559. UpdateUsedRegs(tai(hp_jump.next));
  11560. UpdateUsedRegs(tai(hp_lblyyy.next));
  11561. { Get first instruction after label }
  11562. hp1 := p;
  11563. GetNextInstruction(hp_lblyyy, p);
  11564. { Don't dereference yet, as doing so will cause
  11565. GetNextInstruction to skip the label and
  11566. optional align marker. [Kit] }
  11567. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11568. { remove Jcc }
  11569. RemoveInstruction(hp1);
  11570. { Now we can safely decrement it }
  11571. tasmlabel(symbol).decrefs;
  11572. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11573. { Make sure the aligns get stripped too }
  11574. hp1 := tai(hp_lblxxx.Previous);
  11575. while Assigned(hp1) and (hp1.typ = ait_align) do
  11576. begin
  11577. hp_lblxxx := hp1;
  11578. hp1 := tai(hp_lblxxx.Previous);
  11579. end;
  11580. StripLabelFast(hp_lblxxx);
  11581. { remove jmp }
  11582. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11583. RemoveInstruction(hp_jump);
  11584. { As before, now we can safely decrement it }
  11585. TAsmLabel(symbol).decrefs;
  11586. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11587. if TAsmLabel(symbol).getrefs = 0 then
  11588. begin
  11589. { Make sure the aligns get stripped too }
  11590. hp1 := tai(hp_lblyyy.Previous);
  11591. while Assigned(hp1) and (hp1.typ = ait_align) do
  11592. begin
  11593. hp_lblyyy := hp1;
  11594. hp1 := tai(hp_lblyyy.Previous);
  11595. end;
  11596. StripLabelFast(hp_lblyyy);
  11597. end;
  11598. if Assigned(p) then
  11599. result := True;
  11600. exit;
  11601. end;
  11602. end;
  11603. end;
  11604. {$endif i8086}
  11605. end;
  11606. end;
  11607. end;
  11608. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11609. var
  11610. hp1,hp2,hp3: tai;
  11611. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11612. NewSize: TOpSize;
  11613. NewRegSize: TSubRegister;
  11614. Limit: TCgInt;
  11615. SwapOper: POper;
  11616. begin
  11617. result:=false;
  11618. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11619. GetNextInstruction(p,hp1) and
  11620. (hp1.typ = ait_instruction);
  11621. if reg_and_hp1_is_instr and
  11622. (
  11623. (taicpu(hp1).opcode <> A_LEA) or
  11624. { If the LEA instruction can be converted into an arithmetic instruction,
  11625. it may be possible to then fold it. }
  11626. (
  11627. { If the flags register is in use, don't change the instruction
  11628. to an ADD otherwise this will scramble the flags. [Kit] }
  11629. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11630. ConvertLEA(taicpu(hp1))
  11631. )
  11632. ) and
  11633. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11634. GetNextInstruction(hp1,hp2) and
  11635. MatchInstruction(hp2,A_MOV,[]) and
  11636. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11637. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11638. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11639. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11640. {$ifdef i386}
  11641. { not all registers have byte size sub registers on i386 }
  11642. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11643. {$endif i386}
  11644. (((taicpu(hp1).ops=2) and
  11645. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11646. ((taicpu(hp1).ops=1) and
  11647. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11648. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11649. begin
  11650. { change movsX/movzX reg/ref, reg2
  11651. add/sub/or/... reg3/$const, reg2
  11652. mov reg2 reg/ref
  11653. to add/sub/or/... reg3/$const, reg/ref }
  11654. { by example:
  11655. movswl %si,%eax movswl %si,%eax p
  11656. decl %eax addl %edx,%eax hp1
  11657. movw %ax,%si movw %ax,%si hp2
  11658. ->
  11659. movswl %si,%eax movswl %si,%eax p
  11660. decw %eax addw %edx,%eax hp1
  11661. movw %ax,%si movw %ax,%si hp2
  11662. }
  11663. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11664. {
  11665. ->
  11666. movswl %si,%eax movswl %si,%eax p
  11667. decw %si addw %dx,%si hp1
  11668. movw %ax,%si movw %ax,%si hp2
  11669. }
  11670. case taicpu(hp1).ops of
  11671. 1:
  11672. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11673. 2:
  11674. begin
  11675. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11676. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11677. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11678. end;
  11679. else
  11680. internalerror(2008042702);
  11681. end;
  11682. {
  11683. ->
  11684. decw %si addw %dx,%si p
  11685. }
  11686. DebugMsg(SPeepholeOptimization + 'var3',p);
  11687. RemoveCurrentP(p, hp1);
  11688. RemoveInstruction(hp2);
  11689. Result := True;
  11690. Exit;
  11691. end;
  11692. if reg_and_hp1_is_instr and
  11693. (taicpu(hp1).opcode = A_MOV) and
  11694. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11695. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11696. {$ifdef x86_64}
  11697. { check for implicit extension to 64 bit }
  11698. or
  11699. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11700. (taicpu(hp1).opsize=S_Q) and
  11701. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11702. )
  11703. {$endif x86_64}
  11704. )
  11705. then
  11706. begin
  11707. { change
  11708. movx %reg1,%reg2
  11709. mov %reg2,%reg3
  11710. dealloc %reg2
  11711. into
  11712. movx %reg,%reg3
  11713. }
  11714. TransferUsedRegs(TmpUsedRegs);
  11715. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11716. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11717. begin
  11718. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11719. {$ifdef x86_64}
  11720. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11721. (taicpu(hp1).opsize=S_Q) then
  11722. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11723. else
  11724. {$endif x86_64}
  11725. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11726. RemoveInstruction(hp1);
  11727. Result := True;
  11728. Exit;
  11729. end;
  11730. end;
  11731. if reg_and_hp1_is_instr and
  11732. ((taicpu(hp1).opcode=A_MOV) or
  11733. (taicpu(hp1).opcode=A_ADD) or
  11734. (taicpu(hp1).opcode=A_SUB) or
  11735. (taicpu(hp1).opcode=A_CMP) or
  11736. (taicpu(hp1).opcode=A_OR) or
  11737. (taicpu(hp1).opcode=A_XOR) or
  11738. (taicpu(hp1).opcode=A_AND)
  11739. ) and
  11740. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11741. begin
  11742. AndTest := (taicpu(hp1).opcode=A_AND) and
  11743. GetNextInstruction(hp1, hp2) and
  11744. (hp2.typ = ait_instruction) and
  11745. (
  11746. (
  11747. (taicpu(hp2).opcode=A_TEST) and
  11748. (
  11749. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11750. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11751. (
  11752. { If the AND and TEST instructions share a constant, this is also valid }
  11753. (taicpu(hp1).oper[0]^.typ = top_const) and
  11754. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11755. )
  11756. ) and
  11757. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11758. ) or
  11759. (
  11760. (taicpu(hp2).opcode=A_CMP) and
  11761. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11762. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11763. )
  11764. );
  11765. { change
  11766. movx (oper),%reg2
  11767. and $x,%reg2
  11768. test %reg2,%reg2
  11769. dealloc %reg2
  11770. into
  11771. op %reg1,%reg3
  11772. if the second op accesses only the bits stored in reg1
  11773. }
  11774. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11775. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11776. (taicpu(hp1).oper[0]^.typ = top_const) and
  11777. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11778. AndTest then
  11779. begin
  11780. { Check if the AND constant is in range }
  11781. case taicpu(p).opsize of
  11782. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11783. begin
  11784. NewSize := S_B;
  11785. Limit := $FF;
  11786. end;
  11787. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11788. begin
  11789. NewSize := S_W;
  11790. Limit := $FFFF;
  11791. end;
  11792. {$ifdef x86_64}
  11793. S_LQ:
  11794. begin
  11795. NewSize := S_L;
  11796. Limit := $FFFFFFFF;
  11797. end;
  11798. {$endif x86_64}
  11799. else
  11800. InternalError(2021120303);
  11801. end;
  11802. if (
  11803. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11804. { Check for negative operands }
  11805. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11806. ) and
  11807. GetNextInstruction(hp2,hp3) and
  11808. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11809. (taicpu(hp3).condition in [C_E,C_NE]) then
  11810. begin
  11811. TransferUsedRegs(TmpUsedRegs);
  11812. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11813. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11814. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11815. begin
  11816. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11817. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11818. taicpu(hp1).opcode := A_TEST;
  11819. taicpu(hp1).opsize := NewSize;
  11820. RemoveInstruction(hp2);
  11821. RemoveCurrentP(p, hp1);
  11822. Result:=true;
  11823. exit;
  11824. end;
  11825. end;
  11826. end;
  11827. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11828. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11829. (taicpu(hp1).opsize=S_B)) or
  11830. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11831. (taicpu(hp1).opsize=S_W))
  11832. {$ifdef x86_64}
  11833. or ((taicpu(p).opsize=S_LQ) and
  11834. (taicpu(hp1).opsize=S_L))
  11835. {$endif x86_64}
  11836. ) and
  11837. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11838. begin
  11839. { change
  11840. movx %reg1,%reg2
  11841. op %reg2,%reg3
  11842. dealloc %reg2
  11843. into
  11844. op %reg1,%reg3
  11845. if the second op accesses only the bits stored in reg1
  11846. }
  11847. TransferUsedRegs(TmpUsedRegs);
  11848. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11849. if AndTest then
  11850. begin
  11851. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11852. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11853. end
  11854. else
  11855. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11856. if not RegUsed then
  11857. begin
  11858. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11859. if taicpu(p).oper[0]^.typ=top_reg then
  11860. begin
  11861. case taicpu(hp1).opsize of
  11862. S_B:
  11863. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11864. S_W:
  11865. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11866. S_L:
  11867. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11868. else
  11869. Internalerror(2020102301);
  11870. end;
  11871. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11872. end
  11873. else
  11874. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11875. RemoveCurrentP(p);
  11876. if AndTest then
  11877. RemoveInstruction(hp2);
  11878. result:=true;
  11879. exit;
  11880. end;
  11881. end
  11882. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11883. (
  11884. { Bitwise operations only }
  11885. (taicpu(hp1).opcode=A_AND) or
  11886. (taicpu(hp1).opcode=A_TEST) or
  11887. (
  11888. (taicpu(hp1).oper[0]^.typ = top_const) and
  11889. (
  11890. (taicpu(hp1).opcode=A_OR) or
  11891. (taicpu(hp1).opcode=A_XOR)
  11892. )
  11893. )
  11894. ) and
  11895. (
  11896. (taicpu(hp1).oper[0]^.typ = top_const) or
  11897. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11898. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11899. ) then
  11900. begin
  11901. { change
  11902. movx %reg2,%reg2
  11903. op const,%reg2
  11904. into
  11905. op const,%reg2 (smaller version)
  11906. movx %reg2,%reg2
  11907. also change
  11908. movx %reg1,%reg2
  11909. and/test (oper),%reg2
  11910. dealloc %reg2
  11911. into
  11912. and/test (oper),%reg1
  11913. }
  11914. case taicpu(p).opsize of
  11915. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11916. begin
  11917. NewSize := S_B;
  11918. NewRegSize := R_SUBL;
  11919. Limit := $FF;
  11920. end;
  11921. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11922. begin
  11923. NewSize := S_W;
  11924. NewRegSize := R_SUBW;
  11925. Limit := $FFFF;
  11926. end;
  11927. {$ifdef x86_64}
  11928. S_LQ:
  11929. begin
  11930. NewSize := S_L;
  11931. NewRegSize := R_SUBD;
  11932. Limit := $FFFFFFFF;
  11933. end;
  11934. {$endif x86_64}
  11935. else
  11936. Internalerror(2021120302);
  11937. end;
  11938. TransferUsedRegs(TmpUsedRegs);
  11939. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11940. if AndTest then
  11941. begin
  11942. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11943. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11944. end
  11945. else
  11946. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11947. if
  11948. (
  11949. (taicpu(p).opcode = A_MOVZX) and
  11950. (
  11951. (taicpu(hp1).opcode=A_AND) or
  11952. (taicpu(hp1).opcode=A_TEST)
  11953. ) and
  11954. not (
  11955. { If both are references, then the final instruction will have
  11956. both operands as references, which is not allowed }
  11957. (taicpu(p).oper[0]^.typ = top_ref) and
  11958. (taicpu(hp1).oper[0]^.typ = top_ref)
  11959. ) and
  11960. not RegUsed
  11961. ) or
  11962. (
  11963. (
  11964. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11965. not RegUsed
  11966. ) and
  11967. (taicpu(p).oper[0]^.typ = top_reg) and
  11968. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11969. (taicpu(hp1).oper[0]^.typ = top_const) and
  11970. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11971. ) then
  11972. begin
  11973. {$if defined(i386) or defined(i8086)}
  11974. { If the target size is 8-bit, make sure we can actually encode it }
  11975. 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
  11976. Exit;
  11977. {$endif i386 or i8086}
  11978. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11979. taicpu(hp1).opsize := NewSize;
  11980. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11981. if AndTest then
  11982. begin
  11983. RemoveInstruction(hp2);
  11984. if not RegUsed then
  11985. begin
  11986. taicpu(hp1).opcode := A_TEST;
  11987. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11988. begin
  11989. { Make sure the reference is the second operand }
  11990. SwapOper := taicpu(hp1).oper[0];
  11991. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11992. taicpu(hp1).oper[1] := SwapOper;
  11993. end;
  11994. end;
  11995. end;
  11996. case taicpu(hp1).oper[0]^.typ of
  11997. top_reg:
  11998. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11999. top_const:
  12000. { For the AND/TEST case }
  12001. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12002. else
  12003. ;
  12004. end;
  12005. if RegUsed then
  12006. begin
  12007. AsmL.Remove(p);
  12008. AsmL.InsertAfter(p, hp1);
  12009. p := hp1;
  12010. end
  12011. else
  12012. RemoveCurrentP(p, hp1);
  12013. result:=true;
  12014. exit;
  12015. end;
  12016. end;
  12017. end;
  12018. if reg_and_hp1_is_instr and
  12019. (taicpu(p).oper[0]^.typ = top_reg) and
  12020. (
  12021. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12022. ) and
  12023. (taicpu(hp1).oper[0]^.typ = top_const) and
  12024. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12025. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12026. { Minimum shift value allowed is the bit difference between the sizes }
  12027. (taicpu(hp1).oper[0]^.val >=
  12028. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12029. 8 * (
  12030. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12031. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12032. )
  12033. ) then
  12034. begin
  12035. { For:
  12036. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12037. shl/sal ##, %reg1
  12038. Remove the movsx/movzx instruction if the shift overwrites the
  12039. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12040. }
  12041. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12042. RemoveCurrentP(p, hp1);
  12043. Result := True;
  12044. Exit;
  12045. end
  12046. else if reg_and_hp1_is_instr and
  12047. (taicpu(p).oper[0]^.typ = top_reg) and
  12048. (
  12049. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12050. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12051. ) and
  12052. (taicpu(hp1).oper[0]^.typ = top_const) and
  12053. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12054. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12055. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12056. (taicpu(hp1).oper[0]^.val <
  12057. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12058. 8 * (
  12059. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12060. )
  12061. ) then
  12062. begin
  12063. { For:
  12064. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12065. sar ##, %reg1 shr ##, %reg1
  12066. Move the shift to before the movx instruction if the shift value
  12067. is not too large.
  12068. }
  12069. asml.Remove(hp1);
  12070. asml.InsertBefore(hp1, p);
  12071. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12072. case taicpu(p).opsize of
  12073. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12074. taicpu(hp1).opsize := S_B;
  12075. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12076. taicpu(hp1).opsize := S_W;
  12077. {$ifdef x86_64}
  12078. S_LQ:
  12079. taicpu(hp1).opsize := S_L;
  12080. {$endif}
  12081. else
  12082. InternalError(2020112401);
  12083. end;
  12084. if (taicpu(hp1).opcode = A_SHR) then
  12085. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12086. else
  12087. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12088. Result := True;
  12089. end;
  12090. if reg_and_hp1_is_instr and
  12091. (taicpu(p).oper[0]^.typ = top_reg) and
  12092. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12093. (
  12094. (taicpu(hp1).opcode = taicpu(p).opcode)
  12095. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12096. {$ifdef x86_64}
  12097. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12098. {$endif x86_64}
  12099. ) then
  12100. begin
  12101. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12102. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12103. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12104. begin
  12105. {
  12106. For example:
  12107. movzbw %al,%ax
  12108. movzwl %ax,%eax
  12109. Compress into:
  12110. movzbl %al,%eax
  12111. }
  12112. RegUsed := False;
  12113. case taicpu(p).opsize of
  12114. S_BW:
  12115. case taicpu(hp1).opsize of
  12116. S_WL:
  12117. begin
  12118. taicpu(p).opsize := S_BL;
  12119. RegUsed := True;
  12120. end;
  12121. {$ifdef x86_64}
  12122. S_WQ:
  12123. begin
  12124. if taicpu(p).opcode = A_MOVZX then
  12125. begin
  12126. taicpu(p).opsize := S_BL;
  12127. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12128. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12129. end
  12130. else
  12131. taicpu(p).opsize := S_BQ;
  12132. RegUsed := True;
  12133. end;
  12134. {$endif x86_64}
  12135. else
  12136. ;
  12137. end;
  12138. {$ifdef x86_64}
  12139. S_BL:
  12140. case taicpu(hp1).opsize of
  12141. S_LQ:
  12142. begin
  12143. if taicpu(p).opcode = A_MOVZX then
  12144. begin
  12145. taicpu(p).opsize := S_BL;
  12146. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12147. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12148. end
  12149. else
  12150. taicpu(p).opsize := S_BQ;
  12151. RegUsed := True;
  12152. end;
  12153. else
  12154. ;
  12155. end;
  12156. S_WL:
  12157. case taicpu(hp1).opsize of
  12158. S_LQ:
  12159. begin
  12160. if taicpu(p).opcode = A_MOVZX then
  12161. begin
  12162. taicpu(p).opsize := S_WL;
  12163. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12164. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12165. end
  12166. else
  12167. taicpu(p).opsize := S_WQ;
  12168. RegUsed := True;
  12169. end;
  12170. else
  12171. ;
  12172. end;
  12173. {$endif x86_64}
  12174. else
  12175. ;
  12176. end;
  12177. if RegUsed then
  12178. begin
  12179. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12180. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12181. RemoveInstruction(hp1);
  12182. Result := True;
  12183. Exit;
  12184. end;
  12185. end;
  12186. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12187. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12188. GetNextInstruction(hp1, hp2) and
  12189. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12190. (
  12191. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12192. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12193. {$ifdef x86_64}
  12194. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12195. {$endif x86_64}
  12196. ) and
  12197. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12198. (
  12199. (
  12200. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12201. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12202. ) or
  12203. (
  12204. { Only allow the operands in reverse order for TEST instructions }
  12205. (taicpu(hp2).opcode = A_TEST) and
  12206. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12207. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12208. )
  12209. ) then
  12210. begin
  12211. {
  12212. For example:
  12213. movzbl %al,%eax
  12214. movzbl (ref),%edx
  12215. andl %edx,%eax
  12216. (%edx deallocated)
  12217. Change to:
  12218. andb (ref),%al
  12219. movzbl %al,%eax
  12220. Rules are:
  12221. - First two instructions have the same opcode and opsize
  12222. - First instruction's operands are the same super-register
  12223. - Second instruction operates on a different register
  12224. - Third instruction is AND, OR, XOR or TEST
  12225. - Third instruction's operands are the destination registers of the first two instructions
  12226. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12227. - Second instruction's destination register is deallocated afterwards
  12228. }
  12229. TransferUsedRegs(TmpUsedRegs);
  12230. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12231. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12232. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12233. begin
  12234. case taicpu(p).opsize of
  12235. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12236. NewSize := S_B;
  12237. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12238. NewSize := S_W;
  12239. {$ifdef x86_64}
  12240. S_LQ:
  12241. NewSize := S_L;
  12242. {$endif x86_64}
  12243. else
  12244. InternalError(2021120301);
  12245. end;
  12246. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12247. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12248. taicpu(hp2).opsize := NewSize;
  12249. RemoveInstruction(hp1);
  12250. { With TEST, it's best to keep the MOVX instruction at the top }
  12251. if (taicpu(hp2).opcode <> A_TEST) then
  12252. begin
  12253. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12254. asml.Remove(p);
  12255. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12256. asml.InsertAfter(p, hp2);
  12257. p := hp2;
  12258. end
  12259. else
  12260. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12261. Result := True;
  12262. Exit;
  12263. end;
  12264. end;
  12265. end;
  12266. if taicpu(p).opcode=A_MOVZX then
  12267. begin
  12268. { removes superfluous And's after movzx's }
  12269. if reg_and_hp1_is_instr and
  12270. (taicpu(hp1).opcode = A_AND) and
  12271. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12272. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12273. {$ifdef x86_64}
  12274. { check for implicit extension to 64 bit }
  12275. or
  12276. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12277. (taicpu(hp1).opsize=S_Q) and
  12278. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12279. )
  12280. {$endif x86_64}
  12281. )
  12282. then
  12283. begin
  12284. case taicpu(p).opsize Of
  12285. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12286. if (taicpu(hp1).oper[0]^.val = $ff) then
  12287. begin
  12288. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12289. RemoveInstruction(hp1);
  12290. Result:=true;
  12291. exit;
  12292. end;
  12293. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12294. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12295. begin
  12296. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12297. RemoveInstruction(hp1);
  12298. Result:=true;
  12299. exit;
  12300. end;
  12301. {$ifdef x86_64}
  12302. S_LQ:
  12303. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12304. begin
  12305. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12306. RemoveInstruction(hp1);
  12307. Result:=true;
  12308. exit;
  12309. end;
  12310. {$endif x86_64}
  12311. else
  12312. ;
  12313. end;
  12314. { we cannot get rid of the and, but can we get rid of the movz ?}
  12315. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12316. begin
  12317. case taicpu(p).opsize Of
  12318. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12319. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12320. begin
  12321. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12322. RemoveCurrentP(p,hp1);
  12323. Result:=true;
  12324. exit;
  12325. end;
  12326. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12327. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12328. begin
  12329. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12330. RemoveCurrentP(p,hp1);
  12331. Result:=true;
  12332. exit;
  12333. end;
  12334. {$ifdef x86_64}
  12335. S_LQ:
  12336. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12337. begin
  12338. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12339. RemoveCurrentP(p,hp1);
  12340. Result:=true;
  12341. exit;
  12342. end;
  12343. {$endif x86_64}
  12344. else
  12345. ;
  12346. end;
  12347. end;
  12348. end;
  12349. { changes some movzx constructs to faster synonyms (all examples
  12350. are given with eax/ax, but are also valid for other registers)}
  12351. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12352. begin
  12353. case taicpu(p).opsize of
  12354. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12355. (the machine code is equivalent to movzbl %al,%eax), but the
  12356. code generator still generates that assembler instruction and
  12357. it is silently converted. This should probably be checked.
  12358. [Kit] }
  12359. S_BW:
  12360. begin
  12361. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12362. (
  12363. not IsMOVZXAcceptable
  12364. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12365. or (
  12366. (cs_opt_size in current_settings.optimizerswitches) and
  12367. (taicpu(p).oper[1]^.reg = NR_AX)
  12368. )
  12369. ) then
  12370. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12371. begin
  12372. DebugMsg(SPeepholeOptimization + 'var7',p);
  12373. taicpu(p).opcode := A_AND;
  12374. taicpu(p).changeopsize(S_W);
  12375. taicpu(p).loadConst(0,$ff);
  12376. Result := True;
  12377. end
  12378. else if not IsMOVZXAcceptable and
  12379. GetNextInstruction(p, hp1) and
  12380. (tai(hp1).typ = ait_instruction) and
  12381. (taicpu(hp1).opcode = A_AND) and
  12382. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12383. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12384. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12385. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12386. begin
  12387. DebugMsg(SPeepholeOptimization + 'var8',p);
  12388. taicpu(p).opcode := A_MOV;
  12389. taicpu(p).changeopsize(S_W);
  12390. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12391. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12392. Result := True;
  12393. end;
  12394. end;
  12395. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12396. S_BL:
  12397. if not IsMOVZXAcceptable then
  12398. begin
  12399. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12400. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12401. begin
  12402. DebugMsg(SPeepholeOptimization + 'var9',p);
  12403. taicpu(p).opcode := A_AND;
  12404. taicpu(p).changeopsize(S_L);
  12405. taicpu(p).loadConst(0,$ff);
  12406. Result := True;
  12407. end
  12408. else if GetNextInstruction(p, hp1) and
  12409. (tai(hp1).typ = ait_instruction) and
  12410. (taicpu(hp1).opcode = A_AND) and
  12411. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12412. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12413. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12414. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12415. begin
  12416. DebugMsg(SPeepholeOptimization + 'var10',p);
  12417. taicpu(p).opcode := A_MOV;
  12418. taicpu(p).changeopsize(S_L);
  12419. { do not use R_SUBWHOLE
  12420. as movl %rdx,%eax
  12421. is invalid in assembler PM }
  12422. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12423. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12424. Result := True;
  12425. end;
  12426. end;
  12427. {$endif i8086}
  12428. S_WL:
  12429. if not IsMOVZXAcceptable then
  12430. begin
  12431. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12432. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12433. begin
  12434. DebugMsg(SPeepholeOptimization + 'var11',p);
  12435. taicpu(p).opcode := A_AND;
  12436. taicpu(p).changeopsize(S_L);
  12437. taicpu(p).loadConst(0,$ffff);
  12438. Result := True;
  12439. end
  12440. else if GetNextInstruction(p, hp1) and
  12441. (tai(hp1).typ = ait_instruction) and
  12442. (taicpu(hp1).opcode = A_AND) and
  12443. (taicpu(hp1).oper[0]^.typ = top_const) and
  12444. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12445. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12446. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12447. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12448. begin
  12449. DebugMsg(SPeepholeOptimization + 'var12',p);
  12450. taicpu(p).opcode := A_MOV;
  12451. taicpu(p).changeopsize(S_L);
  12452. { do not use R_SUBWHOLE
  12453. as movl %rdx,%eax
  12454. is invalid in assembler PM }
  12455. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12456. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12457. Result := True;
  12458. end;
  12459. end;
  12460. else
  12461. InternalError(2017050705);
  12462. end;
  12463. end
  12464. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12465. begin
  12466. if GetNextInstruction(p, hp1) and
  12467. (tai(hp1).typ = ait_instruction) and
  12468. (taicpu(hp1).opcode = A_AND) and
  12469. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12470. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12471. begin
  12472. //taicpu(p).opcode := A_MOV;
  12473. case taicpu(p).opsize Of
  12474. S_BL:
  12475. begin
  12476. DebugMsg(SPeepholeOptimization + 'var13',p);
  12477. taicpu(hp1).changeopsize(S_L);
  12478. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12479. end;
  12480. S_WL:
  12481. begin
  12482. DebugMsg(SPeepholeOptimization + 'var14',p);
  12483. taicpu(hp1).changeopsize(S_L);
  12484. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12485. end;
  12486. S_BW:
  12487. begin
  12488. DebugMsg(SPeepholeOptimization + 'var15',p);
  12489. taicpu(hp1).changeopsize(S_W);
  12490. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12491. end;
  12492. else
  12493. Internalerror(2017050704)
  12494. end;
  12495. Result := True;
  12496. end;
  12497. end;
  12498. end;
  12499. end;
  12500. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12501. var
  12502. hp1, hp2 : tai;
  12503. MaskLength : Cardinal;
  12504. MaskedBits : TCgInt;
  12505. ActiveReg : TRegister;
  12506. begin
  12507. Result:=false;
  12508. { There are no optimisations for reference targets }
  12509. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12510. Exit;
  12511. while GetNextInstruction(p, hp1) and
  12512. (hp1.typ = ait_instruction) do
  12513. begin
  12514. if (taicpu(p).oper[0]^.typ = top_const) then
  12515. begin
  12516. case taicpu(hp1).opcode of
  12517. A_AND:
  12518. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12519. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12520. { the second register must contain the first one, so compare their subreg types }
  12521. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12522. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12523. { change
  12524. and const1, reg
  12525. and const2, reg
  12526. to
  12527. and (const1 and const2), reg
  12528. }
  12529. begin
  12530. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12531. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12532. RemoveCurrentP(p, hp1);
  12533. Result:=true;
  12534. exit;
  12535. end;
  12536. A_CMP:
  12537. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12538. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12539. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12540. { Just check that the condition on the next instruction is compatible }
  12541. GetNextInstruction(hp1, hp2) and
  12542. (hp2.typ = ait_instruction) and
  12543. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12544. then
  12545. { change
  12546. and 2^n, reg
  12547. cmp 2^n, reg
  12548. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12549. to
  12550. and 2^n, reg
  12551. test reg, reg
  12552. j(~c) / set(~c) / cmov(~c)
  12553. }
  12554. begin
  12555. { Keep TEST instruction in, rather than remove it, because
  12556. it may trigger other optimisations such as MovAndTest2Test }
  12557. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12558. taicpu(hp1).opcode := A_TEST;
  12559. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12560. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12561. Result := True;
  12562. Exit;
  12563. end
  12564. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12565. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12566. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12567. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12568. { change
  12569. and $ff/$ff/$ffff, reg
  12570. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12571. dealloc reg
  12572. to
  12573. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12574. }
  12575. begin
  12576. TransferUsedRegs(TmpUsedRegs);
  12577. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12578. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12579. begin
  12580. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12581. case taicpu(p).oper[0]^.val of
  12582. $ff:
  12583. begin
  12584. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12585. taicpu(hp1).opsize:=S_B;
  12586. end;
  12587. $ffff:
  12588. begin
  12589. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12590. taicpu(hp1).opsize:=S_W;
  12591. end;
  12592. $ffffffff:
  12593. begin
  12594. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12595. taicpu(hp1).opsize:=S_L;
  12596. end;
  12597. else
  12598. Internalerror(2023030401);
  12599. end;
  12600. RemoveCurrentP(p);
  12601. Result := True;
  12602. Exit;
  12603. end;
  12604. end;
  12605. A_MOVZX:
  12606. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12607. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12608. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12609. (
  12610. (
  12611. (taicpu(p).opsize=S_W) and
  12612. (taicpu(hp1).opsize=S_BW)
  12613. ) or
  12614. (
  12615. (taicpu(p).opsize=S_L) and
  12616. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12617. )
  12618. {$ifdef x86_64}
  12619. or
  12620. (
  12621. (taicpu(p).opsize=S_Q) and
  12622. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12623. )
  12624. {$endif x86_64}
  12625. ) then
  12626. begin
  12627. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12628. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12629. ) or
  12630. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12631. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12632. then
  12633. begin
  12634. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12635. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12636. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12637. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12638. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12639. }
  12640. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12641. RemoveInstruction(hp1);
  12642. { See if there are other optimisations possible }
  12643. Continue;
  12644. end;
  12645. end;
  12646. A_SHL:
  12647. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12648. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12649. begin
  12650. {$ifopt R+}
  12651. {$define RANGE_WAS_ON}
  12652. {$R-}
  12653. {$endif}
  12654. { get length of potential and mask }
  12655. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12656. { really a mask? }
  12657. {$ifdef RANGE_WAS_ON}
  12658. {$R+}
  12659. {$endif}
  12660. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12661. { unmasked part shifted out? }
  12662. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12663. begin
  12664. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12665. RemoveCurrentP(p, hp1);
  12666. Result:=true;
  12667. exit;
  12668. end;
  12669. end;
  12670. A_SHR:
  12671. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12672. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12673. (taicpu(hp1).oper[0]^.val <= 63) then
  12674. begin
  12675. { Does SHR combined with the AND cover all the bits?
  12676. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12677. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12678. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12679. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12680. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12681. begin
  12682. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12683. RemoveCurrentP(p, hp1);
  12684. Result := True;
  12685. Exit;
  12686. end;
  12687. end;
  12688. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12689. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12690. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12691. begin
  12692. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12693. (
  12694. (
  12695. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12696. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12697. ) or (
  12698. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12699. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12700. {$ifdef x86_64}
  12701. ) or (
  12702. (taicpu(hp1).opsize = S_LQ) and
  12703. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12704. {$endif x86_64}
  12705. )
  12706. ) then
  12707. begin
  12708. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12709. begin
  12710. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12711. RemoveInstruction(hp1);
  12712. { See if there are other optimisations possible }
  12713. Continue;
  12714. end;
  12715. { The super-registers are the same though.
  12716. Note that this change by itself doesn't improve
  12717. code speed, but it opens up other optimisations. }
  12718. {$ifdef x86_64}
  12719. { Convert 64-bit register to 32-bit }
  12720. case taicpu(hp1).opsize of
  12721. S_BQ:
  12722. begin
  12723. taicpu(hp1).opsize := S_BL;
  12724. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12725. end;
  12726. S_WQ:
  12727. begin
  12728. taicpu(hp1).opsize := S_WL;
  12729. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12730. end
  12731. else
  12732. ;
  12733. end;
  12734. {$endif x86_64}
  12735. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12736. taicpu(hp1).opcode := A_MOVZX;
  12737. { See if there are other optimisations possible }
  12738. Continue;
  12739. end;
  12740. end;
  12741. else
  12742. ;
  12743. end;
  12744. end
  12745. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12746. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12747. begin
  12748. {$ifdef x86_64}
  12749. if (taicpu(p).opsize = S_Q) then
  12750. begin
  12751. { Never necessary }
  12752. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12753. RemoveCurrentP(p, hp1);
  12754. Result := True;
  12755. Exit;
  12756. end;
  12757. {$endif x86_64}
  12758. { Forward check to determine necessity of and %reg,%reg }
  12759. TransferUsedRegs(TmpUsedRegs);
  12760. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12761. { Saves on a bunch of dereferences }
  12762. ActiveReg := taicpu(p).oper[1]^.reg;
  12763. case taicpu(hp1).opcode of
  12764. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12765. if (
  12766. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12767. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12768. ) and
  12769. (
  12770. (taicpu(hp1).opcode <> A_MOV) or
  12771. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12772. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12773. ) and
  12774. not (
  12775. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12776. (taicpu(hp1).opcode = A_MOV) and
  12777. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12778. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12779. ) and
  12780. (
  12781. (
  12782. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12783. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12784. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12785. ) or
  12786. (
  12787. {$ifdef x86_64}
  12788. (
  12789. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12790. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12791. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12792. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12793. ) and
  12794. {$endif x86_64}
  12795. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12796. )
  12797. ) then
  12798. begin
  12799. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12800. RemoveCurrentP(p, hp1);
  12801. Result := True;
  12802. Exit;
  12803. end;
  12804. A_ADD,
  12805. A_AND,
  12806. A_BSF,
  12807. A_BSR,
  12808. A_BTC,
  12809. A_BTR,
  12810. A_BTS,
  12811. A_OR,
  12812. A_SUB,
  12813. A_XOR:
  12814. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12815. if (
  12816. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12817. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12818. ) and
  12819. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12820. begin
  12821. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12822. RemoveCurrentP(p, hp1);
  12823. Result := True;
  12824. Exit;
  12825. end;
  12826. A_CMP,
  12827. A_TEST:
  12828. if (
  12829. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12830. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12831. ) and
  12832. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12833. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12834. begin
  12835. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12836. RemoveCurrentP(p, hp1);
  12837. Result := True;
  12838. Exit;
  12839. end;
  12840. A_BSWAP,
  12841. A_NEG,
  12842. A_NOT:
  12843. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12844. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12845. begin
  12846. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12847. RemoveCurrentP(p, hp1);
  12848. Result := True;
  12849. Exit;
  12850. end;
  12851. else
  12852. ;
  12853. end;
  12854. end;
  12855. if (taicpu(hp1).is_jmp) and
  12856. (taicpu(hp1).opcode<>A_JMP) and
  12857. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12858. begin
  12859. { change
  12860. and x, reg
  12861. jxx
  12862. to
  12863. test x, reg
  12864. jxx
  12865. if reg is deallocated before the
  12866. jump, but only if it's a conditional jump (PFV)
  12867. }
  12868. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12869. taicpu(p).opcode := A_TEST;
  12870. Exit;
  12871. end;
  12872. Break;
  12873. end;
  12874. { Lone AND tests }
  12875. if (taicpu(p).oper[0]^.typ = top_const) then
  12876. begin
  12877. {
  12878. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12879. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12880. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12881. }
  12882. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12883. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12884. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12885. begin
  12886. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12887. if taicpu(p).opsize = S_L then
  12888. begin
  12889. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12890. Result := True;
  12891. end;
  12892. end;
  12893. end;
  12894. { Backward check to determine necessity of and %reg,%reg }
  12895. if (taicpu(p).oper[0]^.typ = top_reg) and
  12896. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12897. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12898. GetLastInstruction(p, hp2) and
  12899. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12900. { Check size of adjacent instruction to determine if the AND is
  12901. effectively a null operation }
  12902. (
  12903. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12904. { Note: Don't include S_Q }
  12905. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12906. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12907. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12908. ) then
  12909. begin
  12910. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12911. { If GetNextInstruction returned False, hp1 will be nil }
  12912. RemoveCurrentP(p, hp1);
  12913. Result := True;
  12914. Exit;
  12915. end;
  12916. end;
  12917. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12918. var
  12919. hp1, hp2: tai;
  12920. NewRef: TReference;
  12921. Distance: Cardinal;
  12922. TempTracking: TAllUsedRegs;
  12923. { This entire nested function is used in an if-statement below, but we
  12924. want to avoid all the used reg transfers and GetNextInstruction calls
  12925. until we really have to check }
  12926. function MemRegisterNotUsedLater: Boolean; inline;
  12927. var
  12928. hp2: tai;
  12929. begin
  12930. TransferUsedRegs(TmpUsedRegs);
  12931. hp2 := p;
  12932. repeat
  12933. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12934. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12935. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12936. end;
  12937. begin
  12938. Result := False;
  12939. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12940. (taicpu(p).oper[1]^.typ = top_reg) then
  12941. begin
  12942. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12943. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12944. (hp1.typ <> ait_instruction) or
  12945. not
  12946. (
  12947. (cs_opt_level3 in current_settings.optimizerswitches) or
  12948. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12949. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12950. ) then
  12951. Exit;
  12952. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12953. addq $x, %rax
  12954. movq %rax, %rdx
  12955. sarq $63, %rdx
  12956. (%rax still in use)
  12957. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12958. leaq $x(%rax),%rdx
  12959. addq $x, %rax
  12960. sarq $63, %rdx
  12961. ...which is okay since it breaks the dependency chain between
  12962. addq and movq, but if OptPass2MOV is called first:
  12963. addq $x, %rax
  12964. cqto
  12965. ...which is better in all ways, taking only 2 cycles to execute
  12966. and much smaller in code size.
  12967. }
  12968. { The extra register tracking is quite strenuous }
  12969. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12970. MatchInstruction(hp1, A_MOV, []) then
  12971. begin
  12972. { Update the register tracking to the MOV instruction }
  12973. CopyUsedRegs(TempTracking);
  12974. hp2 := p;
  12975. repeat
  12976. UpdateUsedRegs(tai(hp2.Next));
  12977. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12978. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12979. OptPass2ADD get called again }
  12980. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12981. begin
  12982. { Reset the tracking to the current instruction }
  12983. RestoreUsedRegs(TempTracking);
  12984. ReleaseUsedRegs(TempTracking);
  12985. Result := True;
  12986. Exit;
  12987. end;
  12988. { Reset the tracking to the current instruction }
  12989. RestoreUsedRegs(TempTracking);
  12990. ReleaseUsedRegs(TempTracking);
  12991. { If OptPass2MOV returned True, we don't need to set Result to
  12992. True if hp1 didn't change because the ADD instruction didn't
  12993. get modified and we'll be evaluating hp1 again when the
  12994. peephole optimizer reaches it }
  12995. end;
  12996. { Change:
  12997. add %reg2,%reg1
  12998. (%reg2 not modified in between)
  12999. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13000. To:
  13001. mov/s/z #(%reg1,%reg2),%reg1
  13002. }
  13003. if (taicpu(p).oper[0]^.typ = top_reg) and
  13004. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13005. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13006. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13007. (
  13008. (
  13009. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13010. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13011. { r/esp cannot be an index }
  13012. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13013. ) or (
  13014. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13015. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13016. )
  13017. ) and (
  13018. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13019. (
  13020. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13021. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13022. MemRegisterNotUsedLater
  13023. )
  13024. ) then
  13025. begin
  13026. if (
  13027. { Instructions are guaranteed to be adjacent on -O2 and under }
  13028. (cs_opt_level3 in current_settings.optimizerswitches) and
  13029. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13030. ) then
  13031. begin
  13032. { If the other register is used in between, move the MOV
  13033. instruction to right after the ADD instruction so a
  13034. saving can still be made }
  13035. Asml.Remove(hp1);
  13036. Asml.InsertAfter(hp1, p);
  13037. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13038. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13039. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13040. RemoveCurrentp(p, hp1);
  13041. end
  13042. else
  13043. begin
  13044. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13045. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13046. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13047. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13048. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13049. { hp1 may not be the immediate next instruction under -O3 }
  13050. RemoveCurrentp(p)
  13051. else
  13052. RemoveCurrentp(p, hp1);
  13053. end;
  13054. Result := True;
  13055. Exit;
  13056. end;
  13057. { Change:
  13058. addl/q $x,%reg1
  13059. movl/q %reg1,%reg2
  13060. To:
  13061. leal/q $x(%reg1),%reg2
  13062. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13063. Breaks the dependency chain.
  13064. }
  13065. if (taicpu(p).oper[0]^.typ = top_const) and
  13066. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13067. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13068. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13069. (
  13070. { Instructions are guaranteed to be adjacent on -O2 and under }
  13071. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13072. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13073. ) then
  13074. begin
  13075. TransferUsedRegs(TmpUsedRegs);
  13076. hp2 := p;
  13077. repeat
  13078. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13079. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13080. if (
  13081. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13082. not (cs_opt_size in current_settings.optimizerswitches) or
  13083. (
  13084. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13085. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13086. )
  13087. ) then
  13088. begin
  13089. { Change the MOV instruction to a LEA instruction, and update the
  13090. first operand }
  13091. reference_reset(NewRef, 1, []);
  13092. NewRef.base := taicpu(p).oper[1]^.reg;
  13093. NewRef.scalefactor := 1;
  13094. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13095. taicpu(hp1).opcode := A_LEA;
  13096. taicpu(hp1).loadref(0, NewRef);
  13097. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13098. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13099. begin
  13100. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13101. { Move what is now the LEA instruction to before the ADD instruction }
  13102. Asml.Remove(hp1);
  13103. Asml.InsertBefore(hp1, p);
  13104. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13105. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13106. p := hp1;
  13107. end
  13108. else
  13109. begin
  13110. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13111. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13112. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13113. { hp1 may not be the immediate next instruction under -O3 }
  13114. RemoveCurrentp(p)
  13115. else
  13116. RemoveCurrentp(p, hp1);
  13117. end;
  13118. Result := True;
  13119. end;
  13120. end;
  13121. end;
  13122. end;
  13123. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13124. var
  13125. SubReg: TSubRegister;
  13126. begin
  13127. Result:=false;
  13128. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13129. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13130. with taicpu(p).oper[0]^.ref^ do
  13131. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13132. begin
  13133. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13134. begin
  13135. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13136. taicpu(p).opcode := A_ADD;
  13137. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13138. Result := True;
  13139. end
  13140. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13141. begin
  13142. if (base <> NR_NO) then
  13143. begin
  13144. if (scalefactor <= 1) then
  13145. begin
  13146. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13147. taicpu(p).opcode := A_ADD;
  13148. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13149. Result := True;
  13150. end;
  13151. end
  13152. else
  13153. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13154. if (scalefactor in [2, 4, 8]) then
  13155. begin
  13156. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13157. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13158. taicpu(p).opcode := A_SHL;
  13159. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13160. Result := True;
  13161. end;
  13162. end;
  13163. end;
  13164. end;
  13165. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13166. var
  13167. hp1, hp2: tai;
  13168. NewRef: TReference;
  13169. Distance: Cardinal;
  13170. TempTracking: TAllUsedRegs;
  13171. begin
  13172. Result := False;
  13173. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13174. MatchOpType(taicpu(p),top_const,top_reg) then
  13175. begin
  13176. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13177. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13178. (hp1.typ <> ait_instruction) or
  13179. not
  13180. (
  13181. (cs_opt_level3 in current_settings.optimizerswitches) or
  13182. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13183. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13184. ) then
  13185. Exit;
  13186. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13187. subq $x, %rax
  13188. movq %rax, %rdx
  13189. sarq $63, %rdx
  13190. (%rax still in use)
  13191. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13192. leaq $-x(%rax),%rdx
  13193. movq $x, %rax
  13194. sarq $63, %rdx
  13195. ...which is okay since it breaks the dependency chain between
  13196. subq and movq, but if OptPass2MOV is called first:
  13197. subq $x, %rax
  13198. cqto
  13199. ...which is better in all ways, taking only 2 cycles to execute
  13200. and much smaller in code size.
  13201. }
  13202. { The extra register tracking is quite strenuous }
  13203. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13204. MatchInstruction(hp1, A_MOV, []) then
  13205. begin
  13206. { Update the register tracking to the MOV instruction }
  13207. CopyUsedRegs(TempTracking);
  13208. hp2 := p;
  13209. repeat
  13210. UpdateUsedRegs(tai(hp2.Next));
  13211. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13212. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13213. OptPass2SUB get called again }
  13214. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13215. begin
  13216. { Reset the tracking to the current instruction }
  13217. RestoreUsedRegs(TempTracking);
  13218. ReleaseUsedRegs(TempTracking);
  13219. Result := True;
  13220. Exit;
  13221. end;
  13222. { Reset the tracking to the current instruction }
  13223. RestoreUsedRegs(TempTracking);
  13224. ReleaseUsedRegs(TempTracking);
  13225. { If OptPass2MOV returned True, we don't need to set Result to
  13226. True if hp1 didn't change because the SUB instruction didn't
  13227. get modified and we'll be evaluating hp1 again when the
  13228. peephole optimizer reaches it }
  13229. end;
  13230. { Change:
  13231. subl/q $x,%reg1
  13232. movl/q %reg1,%reg2
  13233. To:
  13234. leal/q $-x(%reg1),%reg2
  13235. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13236. Breaks the dependency chain and potentially permits the removal of
  13237. a CMP instruction if one follows.
  13238. }
  13239. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13240. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13241. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13242. (
  13243. { Instructions are guaranteed to be adjacent on -O2 and under }
  13244. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13245. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13246. ) then
  13247. begin
  13248. TransferUsedRegs(TmpUsedRegs);
  13249. hp2 := p;
  13250. repeat
  13251. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13252. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13253. if (
  13254. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13255. not (cs_opt_size in current_settings.optimizerswitches) or
  13256. (
  13257. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13258. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13259. )
  13260. ) then
  13261. begin
  13262. { Change the MOV instruction to a LEA instruction, and update the
  13263. first operand }
  13264. reference_reset(NewRef, 1, []);
  13265. NewRef.base := taicpu(p).oper[1]^.reg;
  13266. NewRef.scalefactor := 1;
  13267. NewRef.offset := -taicpu(p).oper[0]^.val;
  13268. taicpu(hp1).opcode := A_LEA;
  13269. taicpu(hp1).loadref(0, NewRef);
  13270. TransferUsedRegs(TmpUsedRegs);
  13271. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13272. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13273. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13274. begin
  13275. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13276. { Move what is now the LEA instruction to before the SUB instruction }
  13277. Asml.Remove(hp1);
  13278. Asml.InsertBefore(hp1, p);
  13279. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13280. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13281. p := hp1;
  13282. end
  13283. else
  13284. begin
  13285. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13286. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13287. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13288. { hp1 may not be the immediate next instruction under -O3 }
  13289. RemoveCurrentp(p)
  13290. else
  13291. RemoveCurrentp(p, hp1);
  13292. end;
  13293. Result := True;
  13294. end;
  13295. end;
  13296. end;
  13297. end;
  13298. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13299. begin
  13300. { we can skip all instructions not messing with the stack pointer }
  13301. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13302. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13303. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13304. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13305. ({(taicpu(hp1).ops=0) or }
  13306. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13307. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13308. ) and }
  13309. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13310. )
  13311. ) do
  13312. GetNextInstruction(hp1,hp1);
  13313. Result:=assigned(hp1);
  13314. end;
  13315. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13316. var
  13317. hp1, hp2, hp3, hp4, hp5: tai;
  13318. begin
  13319. Result:=false;
  13320. hp5:=nil;
  13321. { replace
  13322. leal(q) x(<stackpointer>),<stackpointer>
  13323. call procname
  13324. leal(q) -x(<stackpointer>),<stackpointer>
  13325. ret
  13326. by
  13327. jmp procname
  13328. but do it only on level 4 because it destroys stack back traces
  13329. }
  13330. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13331. MatchOpType(taicpu(p),top_ref,top_reg) and
  13332. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13333. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13334. { the -8 or -24 are not required, but bail out early if possible,
  13335. higher values are unlikely }
  13336. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13337. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13338. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13339. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13340. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13341. GetNextInstruction(p, hp1) and
  13342. { Take a copy of hp1 }
  13343. SetAndTest(hp1, hp4) and
  13344. { trick to skip label }
  13345. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13346. SkipSimpleInstructions(hp1) and
  13347. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13348. GetNextInstruction(hp1, hp2) and
  13349. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13350. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13351. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13352. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13353. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13354. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13355. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13356. { Segment register will be NR_NO }
  13357. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13358. GetNextInstruction(hp2, hp3) and
  13359. { trick to skip label }
  13360. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13361. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13362. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13363. SetAndTest(hp3,hp5) and
  13364. GetNextInstruction(hp3,hp3) and
  13365. MatchInstruction(hp3,A_RET,[S_NO])
  13366. )
  13367. ) and
  13368. (taicpu(hp3).ops=0) then
  13369. begin
  13370. taicpu(hp1).opcode := A_JMP;
  13371. taicpu(hp1).is_jmp := true;
  13372. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13373. RemoveCurrentP(p, hp4);
  13374. RemoveInstruction(hp2);
  13375. RemoveInstruction(hp3);
  13376. if Assigned(hp5) then
  13377. begin
  13378. AsmL.Remove(hp5);
  13379. ASmL.InsertBefore(hp5,hp1)
  13380. end;
  13381. Result:=true;
  13382. end;
  13383. end;
  13384. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13385. {$ifdef x86_64}
  13386. var
  13387. hp1, hp2, hp3, hp4, hp5: tai;
  13388. {$endif x86_64}
  13389. begin
  13390. Result:=false;
  13391. {$ifdef x86_64}
  13392. hp5:=nil;
  13393. { replace
  13394. push %rax
  13395. call procname
  13396. pop %rcx
  13397. ret
  13398. by
  13399. jmp procname
  13400. but do it only on level 4 because it destroys stack back traces
  13401. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13402. for all supported calling conventions
  13403. }
  13404. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13405. MatchOpType(taicpu(p),top_reg) and
  13406. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13407. GetNextInstruction(p, hp1) and
  13408. { Take a copy of hp1 }
  13409. SetAndTest(hp1, hp4) and
  13410. { trick to skip label }
  13411. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13412. SkipSimpleInstructions(hp1) and
  13413. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13414. GetNextInstruction(hp1, hp2) and
  13415. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13416. MatchOpType(taicpu(hp2),top_reg) and
  13417. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13418. GetNextInstruction(hp2, hp3) and
  13419. { trick to skip label }
  13420. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13421. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13422. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13423. SetAndTest(hp3,hp5) and
  13424. GetNextInstruction(hp3,hp3) and
  13425. MatchInstruction(hp3,A_RET,[S_NO])
  13426. )
  13427. ) and
  13428. (taicpu(hp3).ops=0) then
  13429. begin
  13430. taicpu(hp1).opcode := A_JMP;
  13431. taicpu(hp1).is_jmp := true;
  13432. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13433. RemoveCurrentP(p, hp4);
  13434. RemoveInstruction(hp2);
  13435. RemoveInstruction(hp3);
  13436. if Assigned(hp5) then
  13437. begin
  13438. AsmL.Remove(hp5);
  13439. ASmL.InsertBefore(hp5,hp1)
  13440. end;
  13441. Result:=true;
  13442. end;
  13443. {$endif x86_64}
  13444. end;
  13445. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13446. var
  13447. Value, RegName: string;
  13448. begin
  13449. Result:=false;
  13450. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13451. begin
  13452. case taicpu(p).oper[0]^.val of
  13453. 0:
  13454. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13455. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13456. begin
  13457. { change "mov $0,%reg" into "xor %reg,%reg" }
  13458. taicpu(p).opcode := A_XOR;
  13459. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13460. Result := True;
  13461. {$ifdef x86_64}
  13462. end
  13463. else if (taicpu(p).opsize = S_Q) then
  13464. begin
  13465. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13466. { The actual optimization }
  13467. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13468. taicpu(p).changeopsize(S_L);
  13469. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13470. Result := True;
  13471. end;
  13472. $1..$FFFFFFFF:
  13473. begin
  13474. { Code size reduction by J. Gareth "Kit" Moreton }
  13475. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13476. case taicpu(p).opsize of
  13477. S_Q:
  13478. begin
  13479. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13480. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13481. { The actual optimization }
  13482. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13483. taicpu(p).changeopsize(S_L);
  13484. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13485. Result := True;
  13486. end;
  13487. else
  13488. { Do nothing };
  13489. end;
  13490. {$endif x86_64}
  13491. end;
  13492. -1:
  13493. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13494. if (cs_opt_size in current_settings.optimizerswitches) and
  13495. (taicpu(p).opsize <> S_B) and
  13496. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13497. begin
  13498. { change "mov $-1,%reg" into "or $-1,%reg" }
  13499. { NOTES:
  13500. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13501. - This operation creates a false dependency on the register, so only do it when optimising for size
  13502. - 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
  13503. }
  13504. taicpu(p).opcode := A_OR;
  13505. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13506. Result := True;
  13507. end;
  13508. else
  13509. { Do nothing };
  13510. end;
  13511. end;
  13512. end;
  13513. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13514. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13515. begin
  13516. Result := False;
  13517. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13518. Exit;
  13519. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13520. so don't bother optimising }
  13521. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13522. Exit;
  13523. if (taicpu(p).oper[0]^.typ <> top_const) or
  13524. { If the value can fit into an 8-bit signed integer, a smaller
  13525. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13526. falls within this range }
  13527. (
  13528. (taicpu(p).oper[0]^.val > -128) and
  13529. (taicpu(p).oper[0]^.val <= 127)
  13530. ) then
  13531. Exit;
  13532. { If we're optimising for size, this is acceptable }
  13533. if (cs_opt_size in current_settings.optimizerswitches) then
  13534. Exit(True);
  13535. if (taicpu(p).oper[1]^.typ = top_reg) and
  13536. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13537. Exit(True);
  13538. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13539. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13540. Exit(True);
  13541. end;
  13542. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13543. var
  13544. hp1: tai;
  13545. Value: TCGInt;
  13546. begin
  13547. Result := False;
  13548. if MatchOpType(taicpu(p), top_const, top_reg) then
  13549. begin
  13550. { Detect:
  13551. andw x, %ax (0 <= x < $8000)
  13552. ...
  13553. movzwl %ax,%eax
  13554. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13555. }
  13556. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13557. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13558. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13559. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13560. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13561. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13562. begin
  13563. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13564. taicpu(hp1).opcode := A_CWDE;
  13565. taicpu(hp1).clearop(0);
  13566. taicpu(hp1).clearop(1);
  13567. taicpu(hp1).ops := 0;
  13568. { A change was made, but not with p, so don't set Result, but
  13569. notify the compiler that a change was made }
  13570. Include(OptsToCheck, aoc_ForceNewIteration);
  13571. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13572. end;
  13573. end;
  13574. { If "not x" is a power of 2 (popcnt = 1), change:
  13575. and $x, %reg/ref
  13576. To:
  13577. btr lb(x), %reg/ref
  13578. }
  13579. if IsBTXAcceptable(p) and
  13580. (
  13581. { Make sure a TEST doesn't follow that plays with the register }
  13582. not GetNextInstruction(p, hp1) or
  13583. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13584. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13585. ) then
  13586. begin
  13587. {$push}{$R-}{$Q-}
  13588. { Value is a sign-extended 32-bit integer - just correct it
  13589. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13590. checks to see if this operand is an immediate. }
  13591. Value := not taicpu(p).oper[0]^.val;
  13592. {$pop}
  13593. {$ifdef x86_64}
  13594. if taicpu(p).opsize = S_L then
  13595. {$endif x86_64}
  13596. Value := Value and $FFFFFFFF;
  13597. if (PopCnt(QWord(Value)) = 1) then
  13598. begin
  13599. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13600. taicpu(p).opcode := A_BTR;
  13601. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13602. Result := True;
  13603. Exit;
  13604. end;
  13605. end;
  13606. end;
  13607. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13608. begin
  13609. Result := False;
  13610. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13611. Exit;
  13612. { Convert:
  13613. movswl %ax,%eax -> cwtl
  13614. movslq %eax,%rax -> cdqe
  13615. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13616. refer to the same opcode and depends only on the assembler's
  13617. current operand-size attribute. [Kit]
  13618. }
  13619. with taicpu(p) do
  13620. case opsize of
  13621. S_WL:
  13622. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13623. begin
  13624. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13625. opcode := A_CWDE;
  13626. clearop(0);
  13627. clearop(1);
  13628. ops := 0;
  13629. Result := True;
  13630. end;
  13631. {$ifdef x86_64}
  13632. S_LQ:
  13633. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13634. begin
  13635. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13636. opcode := A_CDQE;
  13637. clearop(0);
  13638. clearop(1);
  13639. ops := 0;
  13640. Result := True;
  13641. end;
  13642. {$endif x86_64}
  13643. else
  13644. ;
  13645. end;
  13646. end;
  13647. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13648. var
  13649. hp1, hp2: tai;
  13650. IdentityMask, Shift: TCGInt;
  13651. LimitSize: Topsize;
  13652. DoNotMerge: Boolean;
  13653. begin
  13654. Result := False;
  13655. { All these optimisations work on "shr const,%reg" }
  13656. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13657. Exit;
  13658. DoNotMerge := False;
  13659. Shift := taicpu(p).oper[0]^.val;
  13660. LimitSize := taicpu(p).opsize;
  13661. hp1 := p;
  13662. repeat
  13663. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13664. Break;
  13665. { Detect:
  13666. shr x, %reg
  13667. and y, %reg
  13668. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13669. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13670. }
  13671. case taicpu(hp1).opcode of
  13672. A_AND:
  13673. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13674. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13675. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13676. begin
  13677. { Make sure the FLAGS register isn't in use }
  13678. TransferUsedRegs(TmpUsedRegs);
  13679. hp2 := p;
  13680. repeat
  13681. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13682. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13683. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13684. begin
  13685. { Generate the identity mask }
  13686. case taicpu(p).opsize of
  13687. S_B:
  13688. IdentityMask := $FF shr Shift;
  13689. S_W:
  13690. IdentityMask := $FFFF shr Shift;
  13691. S_L:
  13692. IdentityMask := $FFFFFFFF shr Shift;
  13693. {$ifdef x86_64}
  13694. S_Q:
  13695. { We need to force the operands to be unsigned 64-bit
  13696. integers otherwise the wrong value is generated }
  13697. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13698. {$endif x86_64}
  13699. else
  13700. InternalError(2022081501);
  13701. end;
  13702. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13703. begin
  13704. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13705. { All the possible 1 bits are covered, so we can remove the AND }
  13706. hp2 := tai(hp1.Previous);
  13707. RemoveInstruction(hp1);
  13708. { p wasn't actually changed, so don't set Result to True,
  13709. but a change was nonetheless made elsewhere }
  13710. Include(OptsToCheck, aoc_ForceNewIteration);
  13711. { Do another pass in case other AND or MOVZX instructions
  13712. follow }
  13713. hp1 := hp2;
  13714. Continue;
  13715. end;
  13716. end;
  13717. end;
  13718. A_TEST, A_CMP, A_Jcc:
  13719. { Skip over conditional jumps and relevant comparisons }
  13720. Continue;
  13721. A_MOVZX:
  13722. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13723. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13724. begin
  13725. { Since the original register is being read as is, subsequent
  13726. SHRs must not be merged at this point }
  13727. DoNotMerge := True;
  13728. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13729. begin
  13730. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13731. begin
  13732. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13733. { All the possible 1 bits are covered, so we can remove the AND }
  13734. hp2 := tai(hp1.Previous);
  13735. RemoveInstruction(hp1);
  13736. hp1 := hp2;
  13737. end
  13738. else { Different register target }
  13739. begin
  13740. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13741. taicpu(hp1).opcode := A_MOV;
  13742. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13743. case taicpu(hp1).opsize of
  13744. S_BW:
  13745. taicpu(hp1).opsize := S_W;
  13746. S_BL, S_WL:
  13747. taicpu(hp1).opsize := S_L;
  13748. else
  13749. InternalError(2022081503);
  13750. end;
  13751. end;
  13752. end
  13753. else if (Shift > 0) and
  13754. (taicpu(p).opsize = S_W) and
  13755. (taicpu(hp1).opsize = S_WL) and
  13756. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13757. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13758. begin
  13759. { Detect:
  13760. shr x, %ax (x > 0)
  13761. ...
  13762. movzwl %ax,%eax
  13763. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13764. }
  13765. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13766. taicpu(hp1).opcode := A_CWDE;
  13767. taicpu(hp1).clearop(0);
  13768. taicpu(hp1).clearop(1);
  13769. taicpu(hp1).ops := 0;
  13770. end;
  13771. { Move onto the next instruction }
  13772. Continue;
  13773. end;
  13774. A_SHL, A_SAL, A_SHR:
  13775. if (taicpu(hp1).opsize <= LimitSize) and
  13776. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13777. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13778. begin
  13779. { Make sure the sizes don't exceed the register size limit
  13780. (measured by the shift value falling below the limit) }
  13781. if taicpu(hp1).opsize < LimitSize then
  13782. LimitSize := taicpu(hp1).opsize;
  13783. if taicpu(hp1).opcode = A_SHR then
  13784. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13785. else
  13786. begin
  13787. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13788. DoNotMerge := True;
  13789. end;
  13790. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13791. Break;
  13792. { Since we've established that the combined shift is within
  13793. limits, we can actually combine the adjacent SHR
  13794. instructions even if they're different sizes }
  13795. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13796. begin
  13797. hp2 := tai(hp1.Previous);
  13798. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13799. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13800. RemoveInstruction(hp1);
  13801. hp1 := hp2;
  13802. end;
  13803. { Move onto the next instruction }
  13804. Continue;
  13805. end;
  13806. else
  13807. ;
  13808. end;
  13809. Break;
  13810. until False;
  13811. { Detect the following (looking backwards):
  13812. shr %cl,%reg
  13813. shr x, %reg
  13814. Swap the two SHR instructions to minimise a pipeline stall.
  13815. }
  13816. if GetLastInstruction(p, hp1) and
  13817. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13818. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13819. { First operand will be %cl }
  13820. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13821. { Just to be sure }
  13822. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13823. begin
  13824. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13825. { Moving the entries this way ensures the register tracking remains correct }
  13826. Asml.Remove(p);
  13827. Asml.InsertBefore(p, hp1);
  13828. p := hp1;
  13829. { Don't set Result to True because the current instruction is now
  13830. "shr %cl,%reg" and there's nothing more we can do with it }
  13831. end;
  13832. end;
  13833. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13834. var
  13835. hp1, hp2: tai;
  13836. Opposite, SecondOpposite: TAsmOp;
  13837. NewCond: TAsmCond;
  13838. begin
  13839. Result := False;
  13840. { Change:
  13841. add/sub 128,(dest)
  13842. To:
  13843. sub/add -128,(dest)
  13844. This generaally takes fewer bytes to encode because -128 can be stored
  13845. in a signed byte, whereas +128 cannot.
  13846. }
  13847. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13848. begin
  13849. if taicpu(p).opcode = A_ADD then
  13850. Opposite := A_SUB
  13851. else
  13852. Opposite := A_ADD;
  13853. { Be careful if the flags are in use, because the CF flag inverts
  13854. when changing from ADD to SUB and vice versa }
  13855. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13856. GetNextInstruction(p, hp1) then
  13857. begin
  13858. TransferUsedRegs(TmpUsedRegs);
  13859. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13860. hp2 := hp1;
  13861. { Scan ahead to check if everything's safe }
  13862. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13863. begin
  13864. if (hp1.typ <> ait_instruction) then
  13865. { Probably unsafe since the flags are still in use }
  13866. Exit;
  13867. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13868. { Stop searching at an unconditional jump }
  13869. Break;
  13870. if not
  13871. (
  13872. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13873. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13874. ) and
  13875. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13876. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13877. Exit;
  13878. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13879. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13880. { Move to the next instruction }
  13881. GetNextInstruction(hp1, hp1);
  13882. end;
  13883. while Assigned(hp2) and (hp2 <> hp1) do
  13884. begin
  13885. NewCond := C_None;
  13886. case taicpu(hp2).condition of
  13887. C_A, C_NBE:
  13888. NewCond := C_BE;
  13889. C_B, C_C, C_NAE:
  13890. NewCond := C_AE;
  13891. C_AE, C_NB, C_NC:
  13892. NewCond := C_B;
  13893. C_BE, C_NA:
  13894. NewCond := C_A;
  13895. else
  13896. { No change needed };
  13897. end;
  13898. if NewCond <> C_None then
  13899. begin
  13900. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13901. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13902. taicpu(hp2).condition := NewCond;
  13903. end
  13904. else
  13905. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13906. begin
  13907. { Because of the flipping of the carry bit, to ensure
  13908. the operation remains equivalent, ADC becomes SBB
  13909. and vice versa, and the constant is not-inverted.
  13910. If multiple ADCs or SBBs appear in a row, each one
  13911. changed causes the carry bit to invert, so they all
  13912. need to be flipped }
  13913. if taicpu(hp2).opcode = A_ADC then
  13914. SecondOpposite := A_SBB
  13915. else
  13916. SecondOpposite := A_ADC;
  13917. if taicpu(hp2).oper[0]^.typ <> top_const then
  13918. { Should have broken out of this optimisation already }
  13919. InternalError(2021112901);
  13920. 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]^) + ' -> ' +
  13921. 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);
  13922. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13923. taicpu(hp2).opcode := SecondOpposite;
  13924. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13925. end;
  13926. { Move to the next instruction }
  13927. GetNextInstruction(hp2, hp2);
  13928. end;
  13929. if (hp2 <> hp1) then
  13930. InternalError(2021111501);
  13931. end;
  13932. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13933. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13934. taicpu(p).opcode := Opposite;
  13935. taicpu(p).oper[0]^.val := -128;
  13936. { No further optimisations can be made on this instruction, so move
  13937. onto the next one to save time }
  13938. p := tai(p.Next);
  13939. UpdateUsedRegs(p);
  13940. Result := True;
  13941. Exit;
  13942. end;
  13943. { Detect:
  13944. add/sub %reg2,(dest)
  13945. add/sub x, (dest)
  13946. (dest can be a register or a reference)
  13947. Swap the instructions to minimise a pipeline stall. This reverses the
  13948. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13949. optimisations could be made.
  13950. }
  13951. if (taicpu(p).oper[0]^.typ = top_reg) and
  13952. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13953. (
  13954. (
  13955. (taicpu(p).oper[1]^.typ = top_reg) and
  13956. { We can try searching further ahead if we're writing to a register }
  13957. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13958. ) or
  13959. (
  13960. (taicpu(p).oper[1]^.typ = top_ref) and
  13961. GetNextInstruction(p, hp1)
  13962. )
  13963. ) and
  13964. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13965. (taicpu(hp1).oper[0]^.typ = top_const) and
  13966. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13967. begin
  13968. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13969. TransferUsedRegs(TmpUsedRegs);
  13970. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13971. hp2 := p;
  13972. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13973. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13974. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13975. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13976. begin
  13977. asml.remove(hp1);
  13978. asml.InsertBefore(hp1, p);
  13979. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13980. Result := True;
  13981. end;
  13982. end;
  13983. end;
  13984. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13985. var
  13986. hp1: tai;
  13987. begin
  13988. Result:=false;
  13989. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13990. while GetNextInstruction(p, hp1) and
  13991. TrySwapMovCmp(p, hp1) do
  13992. begin
  13993. if MatchInstruction(hp1, A_MOV, []) then
  13994. begin
  13995. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13996. begin
  13997. { A little hacky, but since CMP doesn't read the flags, only
  13998. modify them, it's safe if they get scrambled by MOV -> XOR }
  13999. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14000. Result := PostPeepholeOptMov(hp1);
  14001. {$ifdef x86_64}
  14002. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14003. { Used to shrink instruction size }
  14004. PostPeepholeOptXor(hp1);
  14005. {$endif x86_64}
  14006. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14007. end
  14008. else
  14009. begin
  14010. Result := PostPeepholeOptMov(hp1);
  14011. {$ifdef x86_64}
  14012. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14013. { Used to shrink instruction size }
  14014. PostPeepholeOptXor(hp1);
  14015. {$endif x86_64}
  14016. end;
  14017. end;
  14018. { Enabling this flag is actually a null operation, but it marks
  14019. the code as 'modified' during this pass }
  14020. Include(OptsToCheck, aoc_ForceNewIteration);
  14021. end;
  14022. { change "cmp $0, %reg" to "test %reg, %reg" }
  14023. if MatchOpType(taicpu(p),top_const,top_reg) and
  14024. (taicpu(p).oper[0]^.val = 0) then
  14025. begin
  14026. taicpu(p).opcode := A_TEST;
  14027. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14028. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14029. Result:=true;
  14030. end;
  14031. end;
  14032. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14033. var
  14034. IsTestConstX, IsValid : Boolean;
  14035. hp1,hp2 : tai;
  14036. begin
  14037. Result:=false;
  14038. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14039. if (taicpu(p).opcode = A_TEST) then
  14040. while GetNextInstruction(p, hp1) and
  14041. TrySwapMovCmp(p, hp1) do
  14042. begin
  14043. if MatchInstruction(hp1, A_MOV, []) then
  14044. begin
  14045. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14046. begin
  14047. { A little hacky, but since TEST doesn't read the flags, only
  14048. modify them, it's safe if they get scrambled by MOV -> XOR }
  14049. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14050. Result := PostPeepholeOptMov(hp1);
  14051. {$ifdef x86_64}
  14052. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14053. { Used to shrink instruction size }
  14054. PostPeepholeOptXor(hp1);
  14055. {$endif x86_64}
  14056. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14057. end
  14058. else
  14059. begin
  14060. Result := PostPeepholeOptMov(hp1);
  14061. {$ifdef x86_64}
  14062. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14063. { Used to shrink instruction size }
  14064. PostPeepholeOptXor(hp1);
  14065. {$endif x86_64}
  14066. end;
  14067. end;
  14068. { Enabling this flag is actually a null operation, but it marks
  14069. the code as 'modified' during this pass }
  14070. Include(OptsToCheck, aoc_ForceNewIteration);
  14071. end;
  14072. { If x is a power of 2 (popcnt = 1), change:
  14073. or $x, %reg/ref
  14074. To:
  14075. bts lb(x), %reg/ref
  14076. }
  14077. if (taicpu(p).opcode = A_OR) and
  14078. IsBTXAcceptable(p) and
  14079. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14080. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14081. (
  14082. { Don't optimise if a test instruction follows }
  14083. not GetNextInstruction(p, hp1) or
  14084. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14085. ) then
  14086. begin
  14087. 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);
  14088. taicpu(p).opcode := A_BTS;
  14089. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14090. Result := True;
  14091. Exit;
  14092. end;
  14093. { If x is a power of 2 (popcnt = 1), change:
  14094. test $x, %reg/ref
  14095. je / sete / cmove (or jne / setne)
  14096. To:
  14097. bt lb(x), %reg/ref
  14098. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14099. }
  14100. if (taicpu(p).opcode = A_TEST) and
  14101. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14102. (taicpu(p).oper[0]^.typ = top_const) and
  14103. (
  14104. (cs_opt_size in current_settings.optimizerswitches) or
  14105. (
  14106. (taicpu(p).oper[1]^.typ = top_reg) and
  14107. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14108. ) or
  14109. (
  14110. (taicpu(p).oper[1]^.typ <> top_reg) and
  14111. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14112. )
  14113. ) and
  14114. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14115. { For sizes less than S_L, the byte size is equal or larger with BT,
  14116. so don't bother optimising }
  14117. (taicpu(p).opsize >= S_L) then
  14118. begin
  14119. IsValid := True;
  14120. { Check the next set of instructions, watching the FLAGS register
  14121. and the conditions used }
  14122. TransferUsedRegs(TmpUsedRegs);
  14123. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14124. hp1 := p;
  14125. hp2 := nil;
  14126. while GetNextInstruction(hp1, hp1) do
  14127. begin
  14128. if not Assigned(hp2) then
  14129. { The first instruction after TEST }
  14130. hp2 := hp1;
  14131. if (hp1.typ <> ait_instruction) then
  14132. begin
  14133. { If the flags are no longer in use, everything is fine }
  14134. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14135. IsValid := False;
  14136. Break;
  14137. end;
  14138. case taicpu(hp1).condition of
  14139. C_None:
  14140. begin
  14141. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14142. { Something is not quite normal, so play safe and don't change }
  14143. IsValid := False;
  14144. Break;
  14145. end;
  14146. C_E, C_Z, C_NE, C_NZ:
  14147. { This is fine };
  14148. else
  14149. begin
  14150. { Unsupported condition }
  14151. IsValid := False;
  14152. Break;
  14153. end;
  14154. end;
  14155. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14156. end;
  14157. if IsValid then
  14158. begin
  14159. while hp2 <> hp1 do
  14160. begin
  14161. case taicpu(hp2).condition of
  14162. C_Z, C_E:
  14163. taicpu(hp2).condition := C_NC;
  14164. C_NZ, C_NE:
  14165. taicpu(hp2).condition := C_C;
  14166. else
  14167. { Should not get this by this point }
  14168. InternalError(2022110701);
  14169. end;
  14170. GetNextInstruction(hp2, hp2);
  14171. end;
  14172. 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);
  14173. taicpu(p).opcode := A_BT;
  14174. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14175. Result := True;
  14176. Exit;
  14177. end;
  14178. end;
  14179. { removes the line marked with (x) from the sequence
  14180. and/or/xor/add/sub/... $x, %y
  14181. test/or %y, %y | test $-1, %y (x)
  14182. j(n)z _Label
  14183. as the first instruction already adjusts the ZF
  14184. %y operand may also be a reference }
  14185. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14186. MatchOperand(taicpu(p).oper[0]^,-1);
  14187. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14188. GetLastInstruction(p, hp1) and
  14189. (tai(hp1).typ = ait_instruction) and
  14190. GetNextInstruction(p,hp2) and
  14191. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14192. case taicpu(hp1).opcode Of
  14193. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14194. { These two instructions set the zero flag if the result is zero }
  14195. A_POPCNT, A_LZCNT:
  14196. begin
  14197. if (
  14198. { With POPCNT, an input of zero will set the zero flag
  14199. because the population count of zero is zero }
  14200. (taicpu(hp1).opcode = A_POPCNT) and
  14201. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14202. (
  14203. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14204. { Faster than going through the second half of the 'or'
  14205. condition below }
  14206. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14207. )
  14208. ) or (
  14209. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14210. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14211. { and in case of carry for A(E)/B(E)/C/NC }
  14212. (
  14213. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14214. (
  14215. (taicpu(hp1).opcode <> A_ADD) and
  14216. (taicpu(hp1).opcode <> A_SUB) and
  14217. (taicpu(hp1).opcode <> A_LZCNT)
  14218. )
  14219. )
  14220. ) then
  14221. begin
  14222. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14223. RemoveCurrentP(p, hp2);
  14224. Result:=true;
  14225. Exit;
  14226. end;
  14227. end;
  14228. A_SHL, A_SAL, A_SHR, A_SAR:
  14229. begin
  14230. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14231. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14232. { therefore, it's only safe to do this optimization for }
  14233. { shifts by a (nonzero) constant }
  14234. (taicpu(hp1).oper[0]^.typ = top_const) and
  14235. (taicpu(hp1).oper[0]^.val <> 0) and
  14236. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14237. { and in case of carry for A(E)/B(E)/C/NC }
  14238. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14239. begin
  14240. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14241. RemoveCurrentP(p, hp2);
  14242. Result:=true;
  14243. Exit;
  14244. end;
  14245. end;
  14246. A_DEC, A_INC, A_NEG:
  14247. begin
  14248. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14249. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14250. { and in case of carry for A(E)/B(E)/C/NC }
  14251. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14252. begin
  14253. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14254. RemoveCurrentP(p, hp2);
  14255. Result:=true;
  14256. Exit;
  14257. end;
  14258. end;
  14259. A_ANDN, A_BZHI:
  14260. begin
  14261. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14262. { Only the zero and sign flags are consistent with what the result is }
  14263. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14264. begin
  14265. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14266. RemoveCurrentP(p, hp2);
  14267. Result:=true;
  14268. Exit;
  14269. end;
  14270. end;
  14271. A_BEXTR:
  14272. begin
  14273. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14274. { Only the zero flag is set }
  14275. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14276. begin
  14277. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14278. RemoveCurrentP(p, hp2);
  14279. Result:=true;
  14280. Exit;
  14281. end;
  14282. end;
  14283. else
  14284. ;
  14285. end; { case }
  14286. { change "test $-1,%reg" into "test %reg,%reg" }
  14287. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14288. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14289. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14290. if MatchInstruction(p, A_OR, []) and
  14291. { Can only match if they're both registers }
  14292. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14293. begin
  14294. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14295. taicpu(p).opcode := A_TEST;
  14296. { No need to set Result to True, as we've done all the optimisations we can }
  14297. end;
  14298. end;
  14299. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14300. var
  14301. hp1,hp3 : tai;
  14302. {$ifndef x86_64}
  14303. hp2 : taicpu;
  14304. {$endif x86_64}
  14305. begin
  14306. Result:=false;
  14307. hp3:=nil;
  14308. {$ifndef x86_64}
  14309. { don't do this on modern CPUs, this really hurts them due to
  14310. broken call/ret pairing }
  14311. if (current_settings.optimizecputype < cpu_Pentium2) and
  14312. not(cs_create_pic in current_settings.moduleswitches) and
  14313. GetNextInstruction(p, hp1) and
  14314. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14315. MatchOpType(taicpu(hp1),top_ref) and
  14316. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14317. begin
  14318. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14319. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14320. InsertLLItem(p.previous, p, hp2);
  14321. taicpu(p).opcode := A_JMP;
  14322. taicpu(p).is_jmp := true;
  14323. RemoveInstruction(hp1);
  14324. Result:=true;
  14325. end
  14326. else
  14327. {$endif x86_64}
  14328. { replace
  14329. call procname
  14330. ret
  14331. by
  14332. jmp procname
  14333. but do it only on level 4 because it destroys stack back traces
  14334. else if the subroutine is marked as no return, remove the ret
  14335. }
  14336. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14337. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14338. GetNextInstruction(p, hp1) and
  14339. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14340. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14341. SetAndTest(hp1,hp3) and
  14342. GetNextInstruction(hp1,hp1) and
  14343. MatchInstruction(hp1,A_RET,[S_NO])
  14344. )
  14345. ) and
  14346. (taicpu(hp1).ops=0) then
  14347. begin
  14348. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14349. { we might destroy stack alignment here if we do not do a call }
  14350. (target_info.stackalign<=sizeof(SizeUInt)) then
  14351. begin
  14352. taicpu(p).opcode := A_JMP;
  14353. taicpu(p).is_jmp := true;
  14354. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14355. end
  14356. else
  14357. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14358. RemoveInstruction(hp1);
  14359. if Assigned(hp3) then
  14360. begin
  14361. AsmL.Remove(hp3);
  14362. AsmL.InsertBefore(hp3,p)
  14363. end;
  14364. Result:=true;
  14365. end;
  14366. end;
  14367. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14368. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14369. begin
  14370. case OpSize of
  14371. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14372. Result := (Val <= $FF) and (Val >= -128);
  14373. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14374. Result := (Val <= $FFFF) and (Val >= -32768);
  14375. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14376. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14377. else
  14378. Result := True;
  14379. end;
  14380. end;
  14381. var
  14382. hp1, hp2 : tai;
  14383. SizeChange: Boolean;
  14384. PreMessage: string;
  14385. begin
  14386. Result := False;
  14387. if (taicpu(p).oper[0]^.typ = top_reg) and
  14388. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14389. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14390. begin
  14391. { Change (using movzbl %al,%eax as an example):
  14392. movzbl %al, %eax movzbl %al, %eax
  14393. cmpl x, %eax testl %eax,%eax
  14394. To:
  14395. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14396. movzbl %al, %eax movzbl %al, %eax
  14397. Smaller instruction and minimises pipeline stall as the CPU
  14398. doesn't have to wait for the register to get zero-extended. [Kit]
  14399. Also allow if the smaller of the two registers is being checked,
  14400. as this still removes the false dependency.
  14401. }
  14402. if
  14403. (
  14404. (
  14405. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14406. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14407. ) or (
  14408. { If MatchOperand returns True, they must both be registers }
  14409. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14410. )
  14411. ) and
  14412. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14413. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14414. begin
  14415. 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);
  14416. asml.Remove(hp1);
  14417. asml.InsertBefore(hp1, p);
  14418. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14419. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14420. begin
  14421. taicpu(hp1).opcode := A_TEST;
  14422. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14423. end;
  14424. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14425. case taicpu(p).opsize of
  14426. S_BW, S_BL:
  14427. begin
  14428. SizeChange := taicpu(hp1).opsize <> S_B;
  14429. taicpu(hp1).changeopsize(S_B);
  14430. end;
  14431. S_WL:
  14432. begin
  14433. SizeChange := taicpu(hp1).opsize <> S_W;
  14434. taicpu(hp1).changeopsize(S_W);
  14435. end
  14436. else
  14437. InternalError(2020112701);
  14438. end;
  14439. UpdateUsedRegs(tai(p.Next));
  14440. { Check if the register is used aferwards - if not, we can
  14441. remove the movzx instruction completely }
  14442. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14443. begin
  14444. { Hp1 is a better position than p for debugging purposes }
  14445. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14446. RemoveCurrentp(p, hp1);
  14447. Result := True;
  14448. end;
  14449. if SizeChange then
  14450. DebugMsg(SPeepholeOptimization + PreMessage +
  14451. 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)
  14452. else
  14453. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14454. Exit;
  14455. end;
  14456. { Change (using movzwl %ax,%eax as an example):
  14457. movzwl %ax, %eax
  14458. movb %al, (dest) (Register is smaller than read register in movz)
  14459. To:
  14460. movb %al, (dest) (Move one back to avoid a false dependency)
  14461. movzwl %ax, %eax
  14462. }
  14463. if (taicpu(hp1).opcode = A_MOV) and
  14464. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14465. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14466. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14467. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14468. begin
  14469. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14470. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14471. asml.Remove(hp1);
  14472. asml.InsertBefore(hp1, p);
  14473. if taicpu(hp1).oper[1]^.typ = top_reg then
  14474. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14475. { Check if the register is used aferwards - if not, we can
  14476. remove the movzx instruction completely }
  14477. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14478. begin
  14479. { Hp1 is a better position than p for debugging purposes }
  14480. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14481. RemoveCurrentp(p, hp1);
  14482. Result := True;
  14483. end;
  14484. Exit;
  14485. end;
  14486. end;
  14487. end;
  14488. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14489. var
  14490. hp1: tai;
  14491. {$ifdef x86_64}
  14492. PreMessage, RegName: string;
  14493. {$endif x86_64}
  14494. begin
  14495. Result := False;
  14496. { If x is a power of 2 (popcnt = 1), change:
  14497. xor $x, %reg/ref
  14498. To:
  14499. btc lb(x), %reg/ref
  14500. }
  14501. if IsBTXAcceptable(p) and
  14502. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14503. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14504. (
  14505. { Don't optimise if a test instruction follows }
  14506. not GetNextInstruction(p, hp1) or
  14507. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14508. ) then
  14509. begin
  14510. 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);
  14511. taicpu(p).opcode := A_BTC;
  14512. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14513. Result := True;
  14514. Exit;
  14515. end;
  14516. {$ifdef x86_64}
  14517. { Code size reduction by J. Gareth "Kit" Moreton }
  14518. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14519. as this removes the REX prefix }
  14520. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14521. Exit;
  14522. if taicpu(p).oper[0]^.typ <> top_reg then
  14523. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14524. InternalError(2018011500);
  14525. case taicpu(p).opsize of
  14526. S_Q:
  14527. begin
  14528. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14529. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14530. { The actual optimization }
  14531. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14532. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14533. taicpu(p).changeopsize(S_L);
  14534. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14535. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14536. end;
  14537. else
  14538. ;
  14539. end;
  14540. {$endif x86_64}
  14541. end;
  14542. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14543. var
  14544. XReg: TRegister;
  14545. begin
  14546. Result := False;
  14547. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14548. Smaller encoding and slightly faster on some platforms (also works for
  14549. ZMM-sized registers) }
  14550. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14551. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14552. begin
  14553. XReg := taicpu(p).oper[0]^.reg;
  14554. if (taicpu(p).oper[1]^.reg = XReg) then
  14555. begin
  14556. taicpu(p).changeopsize(S_XMM);
  14557. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14558. if (cs_opt_size in current_settings.optimizerswitches) then
  14559. begin
  14560. { Change input registers to %xmm0 to reduce size. Note that
  14561. there's a risk of a false dependency doing this, so only
  14562. optimise for size here }
  14563. XReg := NR_XMM0;
  14564. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14565. end
  14566. else
  14567. begin
  14568. setsubreg(XReg, R_SUBMMX);
  14569. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14570. end;
  14571. taicpu(p).oper[0]^.reg := XReg;
  14572. taicpu(p).oper[1]^.reg := XReg;
  14573. Result := True;
  14574. end;
  14575. end;
  14576. end;
  14577. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14578. var
  14579. OperIdx: Integer;
  14580. begin
  14581. for OperIdx := 0 to p.ops - 1 do
  14582. if p.oper[OperIdx]^.typ = top_ref then
  14583. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14584. end;
  14585. end.