aoptx86.pas 697 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110
  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) then
  2037. begin
  2038. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2039. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2040. begin
  2041. { vmova* reg1,reg2
  2042. vmova* reg2,reg3
  2043. dealloc reg2
  2044. =>
  2045. vmova* reg1,reg3 }
  2046. TransferUsedRegs(TmpUsedRegs);
  2047. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2048. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2049. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2050. begin
  2051. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2052. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2053. RemoveInstruction(hp1);
  2054. result:=true;
  2055. exit;
  2056. end;
  2057. { special case:
  2058. vmova* reg1,<op>
  2059. vmova* <op>,reg1
  2060. =>
  2061. vmova* reg1,<op> }
  2062. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2063. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2064. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2065. ) then
  2066. begin
  2067. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2068. RemoveInstruction(hp1);
  2069. result:=true;
  2070. exit;
  2071. end
  2072. end
  2073. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2074. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2075. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2076. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2077. ) and
  2078. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2079. begin
  2080. { vmova* reg1,reg2
  2081. vmovs* reg2,<op>
  2082. dealloc reg2
  2083. =>
  2084. vmovs* reg1,reg3 }
  2085. TransferUsedRegs(TmpUsedRegs);
  2086. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2087. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2088. begin
  2089. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2090. taicpu(p).opcode:=taicpu(hp1).opcode;
  2091. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2092. RemoveInstruction(hp1);
  2093. result:=true;
  2094. exit;
  2095. end
  2096. end;
  2097. end;
  2098. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2099. begin
  2100. if MatchInstruction(hp1,[A_VFMADDPD,
  2101. A_VFMADD132PD,
  2102. A_VFMADD132PS,
  2103. A_VFMADD132SD,
  2104. A_VFMADD132SS,
  2105. A_VFMADD213PD,
  2106. A_VFMADD213PS,
  2107. A_VFMADD213SD,
  2108. A_VFMADD213SS,
  2109. A_VFMADD231PD,
  2110. A_VFMADD231PS,
  2111. A_VFMADD231SD,
  2112. A_VFMADD231SS,
  2113. A_VFMADDSUB132PD,
  2114. A_VFMADDSUB132PS,
  2115. A_VFMADDSUB213PD,
  2116. A_VFMADDSUB213PS,
  2117. A_VFMADDSUB231PD,
  2118. A_VFMADDSUB231PS,
  2119. A_VFMSUB132PD,
  2120. A_VFMSUB132PS,
  2121. A_VFMSUB132SD,
  2122. A_VFMSUB132SS,
  2123. A_VFMSUB213PD,
  2124. A_VFMSUB213PS,
  2125. A_VFMSUB213SD,
  2126. A_VFMSUB213SS,
  2127. A_VFMSUB231PD,
  2128. A_VFMSUB231PS,
  2129. A_VFMSUB231SD,
  2130. A_VFMSUB231SS,
  2131. A_VFMSUBADD132PD,
  2132. A_VFMSUBADD132PS,
  2133. A_VFMSUBADD213PD,
  2134. A_VFMSUBADD213PS,
  2135. A_VFMSUBADD231PD,
  2136. A_VFMSUBADD231PS,
  2137. A_VFNMADD132PD,
  2138. A_VFNMADD132PS,
  2139. A_VFNMADD132SD,
  2140. A_VFNMADD132SS,
  2141. A_VFNMADD213PD,
  2142. A_VFNMADD213PS,
  2143. A_VFNMADD213SD,
  2144. A_VFNMADD213SS,
  2145. A_VFNMADD231PD,
  2146. A_VFNMADD231PS,
  2147. A_VFNMADD231SD,
  2148. A_VFNMADD231SS,
  2149. A_VFNMSUB132PD,
  2150. A_VFNMSUB132PS,
  2151. A_VFNMSUB132SD,
  2152. A_VFNMSUB132SS,
  2153. A_VFNMSUB213PD,
  2154. A_VFNMSUB213PS,
  2155. A_VFNMSUB213SD,
  2156. A_VFNMSUB213SS,
  2157. A_VFNMSUB231PD,
  2158. A_VFNMSUB231PS,
  2159. A_VFNMSUB231SD,
  2160. A_VFNMSUB231SS],[S_NO]) and
  2161. { we mix single and double opperations here because we assume that the compiler
  2162. generates vmovapd only after double operations and vmovaps only after single operations }
  2163. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2164. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2165. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2166. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2167. begin
  2168. TransferUsedRegs(TmpUsedRegs);
  2169. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2170. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2171. begin
  2172. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2173. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2174. RemoveCurrentP(p)
  2175. else
  2176. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2177. RemoveInstruction(hp2);
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_MOVAPS) and
  2182. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2183. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2184. ((taicpu(p).opcode=A_MOVAPD) and
  2185. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2186. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2187. ) and
  2188. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2189. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2190. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2191. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2192. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2193. { change
  2194. movapX reg,reg2
  2195. addsX/subsX/... reg3, reg2
  2196. movapX reg2,reg
  2197. to
  2198. addsX/subsX/... reg3,reg
  2199. }
  2200. begin
  2201. TransferUsedRegs(TmpUsedRegs);
  2202. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2203. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2204. begin
  2205. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2206. debug_op2str(taicpu(p).opcode)+' '+
  2207. debug_op2str(taicpu(hp1).opcode)+' '+
  2208. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2209. { we cannot eliminate the first move if
  2210. the operations uses the same register for source and dest }
  2211. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2212. { Remember that hp1 is not necessarily the immediate
  2213. next instruction }
  2214. RemoveCurrentP(p);
  2215. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2216. RemoveInstruction(hp2);
  2217. result:=true;
  2218. end;
  2219. end
  2220. else if (hp1.typ = ait_instruction) and
  2221. (((taicpu(p).opcode=A_VMOVAPD) and
  2222. (taicpu(hp1).opcode=A_VCOMISD)) or
  2223. ((taicpu(p).opcode=A_VMOVAPS) and
  2224. ((taicpu(hp1).opcode=A_VCOMISS))
  2225. )
  2226. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2227. { change
  2228. movapX reg,reg1
  2229. vcomisX reg1,reg1
  2230. to
  2231. vcomisX reg,reg
  2232. }
  2233. begin
  2234. TransferUsedRegs(TmpUsedRegs);
  2235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2236. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2237. begin
  2238. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2239. debug_op2str(taicpu(p).opcode)+' '+
  2240. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2241. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2242. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2243. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2244. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2245. RemoveCurrentP(p);
  2246. result:=true;
  2247. exit;
  2248. end;
  2249. end
  2250. end;
  2251. end;
  2252. end;
  2253. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2254. var
  2255. hp1 : tai;
  2256. begin
  2257. result:=false;
  2258. { replace
  2259. V<Op>X %mreg1,%mreg2,%mreg3
  2260. VMovX %mreg3,%mreg4
  2261. dealloc %mreg3
  2262. by
  2263. V<Op>X %mreg1,%mreg2,%mreg4
  2264. ?
  2265. }
  2266. if GetNextInstruction(p,hp1) and
  2267. { we mix single and double operations here because we assume that the compiler
  2268. generates vmovapd only after double operations and vmovaps only after single operations }
  2269. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2270. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2271. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2272. begin
  2273. TransferUsedRegs(TmpUsedRegs);
  2274. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2275. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2276. begin
  2277. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2278. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2279. RemoveInstruction(hp1);
  2280. result:=true;
  2281. end;
  2282. end;
  2283. end;
  2284. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2285. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2286. begin
  2287. Result := False;
  2288. { For safety reasons, only check for exact register matches }
  2289. { Check base register }
  2290. if (ref.base = AOldReg) then
  2291. begin
  2292. ref.base := ANewReg;
  2293. Result := True;
  2294. end;
  2295. { Check index register }
  2296. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2297. begin
  2298. ref.index := ANewReg;
  2299. Result := True;
  2300. end;
  2301. end;
  2302. { Replaces all references to AOldReg in an operand to ANewReg }
  2303. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2304. var
  2305. OldSupReg, NewSupReg: TSuperRegister;
  2306. OldSubReg, NewSubReg: TSubRegister;
  2307. OldRegType: TRegisterType;
  2308. ThisOper: POper;
  2309. begin
  2310. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2311. Result := False;
  2312. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2313. InternalError(2020011801);
  2314. OldSupReg := getsupreg(AOldReg);
  2315. OldSubReg := getsubreg(AOldReg);
  2316. OldRegType := getregtype(AOldReg);
  2317. NewSupReg := getsupreg(ANewReg);
  2318. NewSubReg := getsubreg(ANewReg);
  2319. if OldRegType <> getregtype(ANewReg) then
  2320. InternalError(2020011802);
  2321. if OldSubReg <> NewSubReg then
  2322. InternalError(2020011803);
  2323. case ThisOper^.typ of
  2324. top_reg:
  2325. if (
  2326. (ThisOper^.reg = AOldReg) or
  2327. (
  2328. (OldRegType = R_INTREGISTER) and
  2329. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2330. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2331. (
  2332. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2333. {$ifndef x86_64}
  2334. and (
  2335. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2336. don't have an 8-bit representation }
  2337. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2338. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2339. )
  2340. {$endif x86_64}
  2341. )
  2342. )
  2343. ) then
  2344. begin
  2345. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2346. Result := True;
  2347. end;
  2348. top_ref:
  2349. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2350. Result := True;
  2351. else
  2352. ;
  2353. end;
  2354. end;
  2355. { Replaces all references to AOldReg in an instruction to ANewReg }
  2356. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2357. const
  2358. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2359. var
  2360. OperIdx: Integer;
  2361. begin
  2362. Result := False;
  2363. for OperIdx := 0 to p.ops - 1 do
  2364. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2365. begin
  2366. { The shift and rotate instructions can only use CL }
  2367. if not (
  2368. (OperIdx = 0) and
  2369. { This second condition just helps to avoid unnecessarily
  2370. calling MatchInstruction for 10 different opcodes }
  2371. (p.oper[0]^.reg = NR_CL) and
  2372. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2373. ) then
  2374. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2375. end
  2376. else if p.oper[OperIdx]^.typ = top_ref then
  2377. { It's okay to replace registers in references that get written to }
  2378. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2379. end;
  2380. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2381. begin
  2382. Result :=
  2383. (ref^.index = NR_NO) and
  2384. (
  2385. {$ifdef x86_64}
  2386. (
  2387. (ref^.base = NR_RIP) and
  2388. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2389. ) or
  2390. {$endif x86_64}
  2391. (ref^.refaddr = addr_full) or
  2392. (ref^.base = NR_STACK_POINTER_REG) or
  2393. (ref^.base = current_procinfo.framepointer)
  2394. );
  2395. end;
  2396. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2397. var
  2398. l: asizeint;
  2399. begin
  2400. Result := False;
  2401. { Should have been checked previously }
  2402. if p.opcode <> A_LEA then
  2403. InternalError(2020072501);
  2404. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2405. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2406. not(cs_opt_size in current_settings.optimizerswitches) then
  2407. exit;
  2408. with p.oper[0]^.ref^ do
  2409. begin
  2410. if (base <> p.oper[1]^.reg) or
  2411. (index <> NR_NO) or
  2412. assigned(symbol) then
  2413. exit;
  2414. l:=offset;
  2415. if (l=1) and UseIncDec then
  2416. begin
  2417. p.opcode:=A_INC;
  2418. p.loadreg(0,p.oper[1]^.reg);
  2419. p.ops:=1;
  2420. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2421. end
  2422. else if (l=-1) and UseIncDec then
  2423. begin
  2424. p.opcode:=A_DEC;
  2425. p.loadreg(0,p.oper[1]^.reg);
  2426. p.ops:=1;
  2427. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2428. end
  2429. else
  2430. begin
  2431. if (l<0) and (l<>-2147483648) then
  2432. begin
  2433. p.opcode:=A_SUB;
  2434. p.loadConst(0,-l);
  2435. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2436. end
  2437. else
  2438. begin
  2439. p.opcode:=A_ADD;
  2440. p.loadConst(0,l);
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2442. end;
  2443. end;
  2444. end;
  2445. Result := True;
  2446. end;
  2447. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2448. var
  2449. CurrentReg, ReplaceReg: TRegister;
  2450. begin
  2451. Result := False;
  2452. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2453. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2454. case hp.opcode of
  2455. A_FSTSW, A_FNSTSW,
  2456. A_IN, A_INS, A_OUT, A_OUTS,
  2457. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2458. { These routines have explicit operands, but they are restricted in
  2459. what they can be (e.g. IN and OUT can only read from AL, AX or
  2460. EAX. }
  2461. Exit;
  2462. A_IMUL:
  2463. begin
  2464. { The 1-operand version writes to implicit registers
  2465. The 2-operand version reads from the first operator, and reads
  2466. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2467. the 3-operand version reads from a register that it doesn't write to
  2468. }
  2469. case hp.ops of
  2470. 1:
  2471. if (
  2472. (
  2473. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2474. ) or
  2475. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2476. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2477. begin
  2478. Result := True;
  2479. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2480. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2481. end;
  2482. 2:
  2483. { Only modify the first parameter }
  2484. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2485. begin
  2486. Result := True;
  2487. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2488. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2489. end;
  2490. 3:
  2491. { Only modify the second parameter }
  2492. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2493. begin
  2494. Result := True;
  2495. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2496. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2497. end;
  2498. else
  2499. InternalError(2020012901);
  2500. end;
  2501. end;
  2502. else
  2503. if (hp.ops > 0) and
  2504. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2505. begin
  2506. Result := True;
  2507. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2508. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2509. end;
  2510. end;
  2511. end;
  2512. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2513. var
  2514. hp2: tai;
  2515. p_SourceReg, p_TargetReg: TRegister;
  2516. begin
  2517. Result := False;
  2518. { Backward optimisation. If we have:
  2519. func. %reg1,%reg2
  2520. mov %reg2,%reg3
  2521. (dealloc %reg2)
  2522. Change to:
  2523. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2524. Perform similar optimisations with 1, 3 and 4-operand instructions
  2525. that only have one output.
  2526. }
  2527. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2528. begin
  2529. p_SourceReg := taicpu(p).oper[0]^.reg;
  2530. p_TargetReg := taicpu(p).oper[1]^.reg;
  2531. TransferUsedRegs(TmpUsedRegs);
  2532. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2533. GetLastInstruction(p, hp2) and
  2534. (hp2.typ = ait_instruction) and
  2535. { Have to make sure it's an instruction that only reads from
  2536. the first operands and only writes (not reads or modifies) to
  2537. the last one; in essence, a pure function such as BSR, POPCNT
  2538. or ANDN }
  2539. (
  2540. (
  2541. (taicpu(hp2).ops = 1) and
  2542. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2543. ) or
  2544. (
  2545. (taicpu(hp2).ops = 2) and
  2546. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2547. ) or
  2548. (
  2549. (taicpu(hp2).ops = 3) and
  2550. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2551. ) or
  2552. (
  2553. (taicpu(hp2).ops = 4) and
  2554. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2555. )
  2556. ) and
  2557. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2558. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2559. begin
  2560. case taicpu(hp2).opcode of
  2561. A_FSTSW, A_FNSTSW,
  2562. A_IN, A_INS, A_OUT, A_OUTS,
  2563. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2564. { These routines have explicit operands, but they are restricted in
  2565. what they can be (e.g. IN and OUT can only read from AL, AX or
  2566. EAX. }
  2567. ;
  2568. else
  2569. begin
  2570. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2571. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2572. if not RegInInstruction(p_TargetReg, hp2) then
  2573. begin
  2574. { Since we're allocating from an earlier point, we
  2575. need to remove the register from the tracking }
  2576. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2577. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2578. end;
  2579. RemoveCurrentp(p, hp1);
  2580. { If the Func was another MOV instruction, we might get
  2581. "mov %reg,%reg" that doesn't get removed in Pass 2
  2582. otherwise, so deal with it here (also do something
  2583. similar with lea (%reg),%reg}
  2584. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2585. begin
  2586. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2587. if p = hp2 then
  2588. RemoveCurrentp(p)
  2589. else
  2590. RemoveInstruction(hp2);
  2591. end;
  2592. Result := True;
  2593. Exit;
  2594. end;
  2595. end;
  2596. end;
  2597. end;
  2598. end;
  2599. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2600. var
  2601. hp1, hp2, hp3: tai;
  2602. DoOptimisation, TempBool: Boolean;
  2603. {$ifdef x86_64}
  2604. NewConst: TCGInt;
  2605. {$endif x86_64}
  2606. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2607. begin
  2608. if taicpu(hp1).opcode = signed_movop then
  2609. begin
  2610. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2611. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2612. end
  2613. else
  2614. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2615. end;
  2616. function TryConstMerge(var p1, p2: tai): Boolean;
  2617. var
  2618. ThisRef: TReference;
  2619. begin
  2620. Result := False;
  2621. ThisRef := taicpu(p2).oper[1]^.ref^;
  2622. { Only permit writes to the stack, since we can guarantee alignment with that }
  2623. if (ThisRef.index = NR_NO) and
  2624. (
  2625. (ThisRef.base = NR_STACK_POINTER_REG) or
  2626. (ThisRef.base = current_procinfo.framepointer)
  2627. ) then
  2628. begin
  2629. case taicpu(p).opsize of
  2630. S_B:
  2631. begin
  2632. { Word writes must be on a 2-byte boundary }
  2633. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2634. begin
  2635. { Reduce offset of second reference to see if it is sequential with the first }
  2636. Dec(ThisRef.offset, 1);
  2637. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2638. begin
  2639. { Make sure the constants aren't represented as a
  2640. negative number, as these won't merge properly }
  2641. taicpu(p1).opsize := S_W;
  2642. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2643. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2644. RemoveInstruction(p2);
  2645. Result := True;
  2646. end;
  2647. end;
  2648. end;
  2649. S_W:
  2650. begin
  2651. { Longword writes must be on a 4-byte boundary }
  2652. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2653. begin
  2654. { Reduce offset of second reference to see if it is sequential with the first }
  2655. Dec(ThisRef.offset, 2);
  2656. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2657. begin
  2658. { Make sure the constants aren't represented as a
  2659. negative number, as these won't merge properly }
  2660. taicpu(p1).opsize := S_L;
  2661. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2662. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2663. RemoveInstruction(p2);
  2664. Result := True;
  2665. end;
  2666. end;
  2667. end;
  2668. {$ifdef x86_64}
  2669. S_L:
  2670. begin
  2671. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2672. see if the constants can be encoded this way. }
  2673. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2674. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2675. { Quadword writes must be on an 8-byte boundary }
  2676. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2677. begin
  2678. { Reduce offset of second reference to see if it is sequential with the first }
  2679. Dec(ThisRef.offset, 4);
  2680. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2681. begin
  2682. { Make sure the constants aren't represented as a
  2683. negative number, as these won't merge properly }
  2684. taicpu(p1).opsize := S_Q;
  2685. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2686. taicpu(p1).oper[0]^.val := NewConst;
  2687. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2688. RemoveInstruction(p2);
  2689. Result := True;
  2690. end;
  2691. end;
  2692. end;
  2693. {$endif x86_64}
  2694. else
  2695. ;
  2696. end;
  2697. end;
  2698. end;
  2699. var
  2700. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2701. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2702. NewSize: topsize; NewOffset: asizeint;
  2703. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2704. SourceRef, TargetRef: TReference;
  2705. MovAligned, MovUnaligned: TAsmOp;
  2706. ThisRef: TReference;
  2707. JumpTracking: TLinkedList;
  2708. begin
  2709. Result:=false;
  2710. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2711. { remove mov reg1,reg1? }
  2712. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2713. then
  2714. begin
  2715. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2716. { take care of the register (de)allocs following p }
  2717. RemoveCurrentP(p, hp1);
  2718. Result:=true;
  2719. exit;
  2720. end;
  2721. { All the next optimisations require a next instruction }
  2722. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2723. Exit;
  2724. { Prevent compiler warnings }
  2725. p_TargetReg := NR_NO;
  2726. if taicpu(p).oper[1]^.typ = top_reg then
  2727. begin
  2728. { Saves on a large number of dereferences }
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. { Look for:
  2731. mov %reg1,%reg2
  2732. ??? %reg2,r/m
  2733. Change to:
  2734. mov %reg1,%reg2
  2735. ??? %reg1,r/m
  2736. }
  2737. if taicpu(p).oper[0]^.typ = top_reg then
  2738. begin
  2739. if RegReadByInstruction(p_TargetReg, hp1) and
  2740. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2741. begin
  2742. { A change has occurred, just not in p }
  2743. Result := True;
  2744. TransferUsedRegs(TmpUsedRegs);
  2745. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2746. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2747. { Just in case something didn't get modified (e.g. an
  2748. implicit register) }
  2749. not RegReadByInstruction(p_TargetReg, hp1) then
  2750. begin
  2751. { We can remove the original MOV }
  2752. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2753. RemoveCurrentp(p, hp1);
  2754. { UsedRegs got updated by RemoveCurrentp }
  2755. Result := True;
  2756. Exit;
  2757. end;
  2758. { If we know a MOV instruction has become a null operation, we might as well
  2759. get rid of it now to save time. }
  2760. if (taicpu(hp1).opcode = A_MOV) and
  2761. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2762. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2763. { Just being a register is enough to confirm it's a null operation }
  2764. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2765. begin
  2766. Result := True;
  2767. { Speed-up to reduce a pipeline stall... if we had something like...
  2768. movl %eax,%edx
  2769. movw %dx,%ax
  2770. ... the second instruction would change to movw %ax,%ax, but
  2771. given that it is now %ax that's active rather than %eax,
  2772. penalties might occur due to a partial register write, so instead,
  2773. change it to a MOVZX instruction when optimising for speed.
  2774. }
  2775. if not (cs_opt_size in current_settings.optimizerswitches) and
  2776. IsMOVZXAcceptable and
  2777. (taicpu(hp1).opsize < taicpu(p).opsize)
  2778. {$ifdef x86_64}
  2779. { operations already implicitly set the upper 64 bits to zero }
  2780. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2781. {$endif x86_64}
  2782. then
  2783. begin
  2784. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2785. case taicpu(p).opsize of
  2786. S_W:
  2787. if taicpu(hp1).opsize = S_B then
  2788. taicpu(hp1).opsize := S_BL
  2789. else
  2790. InternalError(2020012911);
  2791. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2792. case taicpu(hp1).opsize of
  2793. S_B:
  2794. taicpu(hp1).opsize := S_BL;
  2795. S_W:
  2796. taicpu(hp1).opsize := S_WL;
  2797. else
  2798. InternalError(2020012912);
  2799. end;
  2800. else
  2801. InternalError(2020012910);
  2802. end;
  2803. taicpu(hp1).opcode := A_MOVZX;
  2804. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2805. end
  2806. else
  2807. begin
  2808. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2809. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2810. RemoveInstruction(hp1);
  2811. { The instruction after what was hp1 is now the immediate next instruction,
  2812. so we can continue to make optimisations if it's present }
  2813. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2814. Exit;
  2815. hp1 := hp2;
  2816. end;
  2817. end;
  2818. end;
  2819. end;
  2820. end;
  2821. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2822. overwrites the original destination register. e.g.
  2823. movl ###,%reg2d
  2824. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2825. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2826. }
  2827. if (taicpu(p).oper[1]^.typ = top_reg) and
  2828. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2829. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2830. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2831. begin
  2832. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2833. begin
  2834. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2835. case taicpu(p).oper[0]^.typ of
  2836. top_const:
  2837. { We have something like:
  2838. movb $x, %regb
  2839. movzbl %regb,%regd
  2840. Change to:
  2841. movl $x, %regd
  2842. }
  2843. begin
  2844. case taicpu(hp1).opsize of
  2845. S_BW:
  2846. begin
  2847. convert_mov_value(A_MOVSX, $FF);
  2848. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2849. taicpu(p).opsize := S_W;
  2850. end;
  2851. S_BL:
  2852. begin
  2853. convert_mov_value(A_MOVSX, $FF);
  2854. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2855. taicpu(p).opsize := S_L;
  2856. end;
  2857. S_WL:
  2858. begin
  2859. convert_mov_value(A_MOVSX, $FFFF);
  2860. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2861. taicpu(p).opsize := S_L;
  2862. end;
  2863. {$ifdef x86_64}
  2864. S_BQ:
  2865. begin
  2866. convert_mov_value(A_MOVSX, $FF);
  2867. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2868. taicpu(p).opsize := S_Q;
  2869. end;
  2870. S_WQ:
  2871. begin
  2872. convert_mov_value(A_MOVSX, $FFFF);
  2873. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2874. taicpu(p).opsize := S_Q;
  2875. end;
  2876. S_LQ:
  2877. begin
  2878. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2879. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2880. taicpu(p).opsize := S_Q;
  2881. end;
  2882. {$endif x86_64}
  2883. else
  2884. { If hp1 was a MOV instruction, it should have been
  2885. optimised already }
  2886. InternalError(2020021001);
  2887. end;
  2888. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2889. RemoveInstruction(hp1);
  2890. Result := True;
  2891. Exit;
  2892. end;
  2893. top_ref:
  2894. begin
  2895. { We have something like:
  2896. movb mem, %regb
  2897. movzbl %regb,%regd
  2898. Change to:
  2899. movzbl mem, %regd
  2900. }
  2901. ThisRef := taicpu(p).oper[0]^.ref^;
  2902. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2903. begin
  2904. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2905. taicpu(hp1).loadref(0, ThisRef);
  2906. { Make sure any registers in the references are properly tracked }
  2907. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2908. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2909. if (ThisRef.index <> NR_NO) then
  2910. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2911. RemoveCurrentP(p, hp1);
  2912. Result := True;
  2913. Exit;
  2914. end;
  2915. end;
  2916. else
  2917. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2918. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2919. Exit;
  2920. end;
  2921. end
  2922. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2923. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2924. optimised }
  2925. else
  2926. begin
  2927. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2928. RemoveCurrentP(p, hp1);
  2929. Result := True;
  2930. Exit;
  2931. end;
  2932. end;
  2933. if (taicpu(hp1).opcode = A_AND) and
  2934. (taicpu(p).oper[1]^.typ = top_reg) and
  2935. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2936. begin
  2937. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2938. begin
  2939. case taicpu(p).opsize of
  2940. S_L:
  2941. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2942. begin
  2943. { Optimize out:
  2944. mov x, %reg
  2945. and ffffffffh, %reg
  2946. }
  2947. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2948. RemoveInstruction(hp1);
  2949. Result:=true;
  2950. exit;
  2951. end;
  2952. S_Q: { TODO: Confirm if this is even possible }
  2953. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2954. begin
  2955. { Optimize out:
  2956. mov x, %reg
  2957. and ffffffffffffffffh, %reg
  2958. }
  2959. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2960. RemoveInstruction(hp1);
  2961. Result:=true;
  2962. exit;
  2963. end;
  2964. else
  2965. ;
  2966. end;
  2967. if (
  2968. (taicpu(p).oper[0]^.typ=top_reg) or
  2969. (
  2970. (taicpu(p).oper[0]^.typ=top_ref) and
  2971. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2972. )
  2973. ) and
  2974. GetNextInstruction(hp1,hp2) and
  2975. MatchInstruction(hp2,A_TEST,[]) and
  2976. (
  2977. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2978. (
  2979. { If the register being tested is smaller than the one
  2980. that received a bitwise AND, permit it if the constant
  2981. fits into the smaller size }
  2982. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2983. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2984. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2985. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2986. (
  2987. (
  2988. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2989. (taicpu(hp1).oper[0]^.val <= $FF)
  2990. ) or
  2991. (
  2992. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2993. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2994. {$ifdef x86_64}
  2995. ) or
  2996. (
  2997. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2998. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2999. {$endif x86_64}
  3000. )
  3001. )
  3002. )
  3003. ) and
  3004. (
  3005. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3006. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3007. ) and
  3008. GetNextInstruction(hp2,hp3) and
  3009. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3010. (taicpu(hp3).condition in [C_E,C_NE]) then
  3011. begin
  3012. TransferUsedRegs(TmpUsedRegs);
  3013. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3014. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3015. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3016. begin
  3017. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3018. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3019. taicpu(hp1).opcode:=A_TEST;
  3020. { Shrink the TEST instruction down to the smallest possible size }
  3021. case taicpu(hp1).oper[0]^.val of
  3022. 0..255:
  3023. if (taicpu(hp1).opsize <> S_B)
  3024. {$ifndef x86_64}
  3025. and (
  3026. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3027. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3028. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3029. )
  3030. {$endif x86_64}
  3031. then
  3032. begin
  3033. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3034. { Only print debug message if the TEST instruction
  3035. is a different size before and after }
  3036. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3037. taicpu(hp1).opsize := S_B;
  3038. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3039. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3040. end;
  3041. 256..65535:
  3042. if (taicpu(hp1).opsize <> S_W) then
  3043. begin
  3044. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3045. { Only print debug message if the TEST instruction
  3046. is a different size before and after }
  3047. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3048. taicpu(hp1).opsize := S_W;
  3049. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3050. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3051. end;
  3052. {$ifdef x86_64}
  3053. 65536..$7FFFFFFF:
  3054. if (taicpu(hp1).opsize <> S_L) then
  3055. begin
  3056. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3057. { Only print debug message if the TEST instruction
  3058. is a different size before and after }
  3059. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3060. taicpu(hp1).opsize := S_L;
  3061. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3062. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3063. end;
  3064. {$endif x86_64}
  3065. else
  3066. ;
  3067. end;
  3068. RemoveInstruction(hp2);
  3069. RemoveCurrentP(p, hp1);
  3070. Result:=true;
  3071. exit;
  3072. end;
  3073. end;
  3074. end
  3075. else if IsMOVZXAcceptable and
  3076. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3077. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3078. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3079. then
  3080. begin
  3081. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3082. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3083. case taicpu(p).opsize of
  3084. S_B:
  3085. if (taicpu(hp1).oper[0]^.val = $ff) then
  3086. begin
  3087. { Convert:
  3088. movb x, %regl movb x, %regl
  3089. andw ffh, %regw andl ffh, %regd
  3090. To:
  3091. movzbw x, %regd movzbl x, %regd
  3092. (Identical registers, just different sizes)
  3093. }
  3094. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3095. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3096. case taicpu(hp1).opsize of
  3097. S_W: NewSize := S_BW;
  3098. S_L: NewSize := S_BL;
  3099. {$ifdef x86_64}
  3100. S_Q: NewSize := S_BQ;
  3101. {$endif x86_64}
  3102. else
  3103. InternalError(2018011510);
  3104. end;
  3105. end
  3106. else
  3107. NewSize := S_NO;
  3108. S_W:
  3109. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3110. begin
  3111. { Convert:
  3112. movw x, %regw
  3113. andl ffffh, %regd
  3114. To:
  3115. movzwl x, %regd
  3116. (Identical registers, just different sizes)
  3117. }
  3118. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3119. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3120. case taicpu(hp1).opsize of
  3121. S_L: NewSize := S_WL;
  3122. {$ifdef x86_64}
  3123. S_Q: NewSize := S_WQ;
  3124. {$endif x86_64}
  3125. else
  3126. InternalError(2018011511);
  3127. end;
  3128. end
  3129. else
  3130. NewSize := S_NO;
  3131. else
  3132. NewSize := S_NO;
  3133. end;
  3134. if NewSize <> S_NO then
  3135. begin
  3136. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3137. { The actual optimization }
  3138. taicpu(p).opcode := A_MOVZX;
  3139. taicpu(p).changeopsize(NewSize);
  3140. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3141. { Safeguard if "and" is followed by a conditional command }
  3142. TransferUsedRegs(TmpUsedRegs);
  3143. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3144. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3145. begin
  3146. { At this point, the "and" command is effectively equivalent to
  3147. "test %reg,%reg". This will be handled separately by the
  3148. Peephole Optimizer. [Kit] }
  3149. DebugMsg(SPeepholeOptimization + PreMessage +
  3150. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3151. end
  3152. else
  3153. begin
  3154. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3155. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3156. RemoveInstruction(hp1);
  3157. end;
  3158. Result := True;
  3159. Exit;
  3160. end;
  3161. end;
  3162. end;
  3163. if (taicpu(hp1).opcode = A_OR) and
  3164. (taicpu(p).oper[1]^.typ = top_reg) and
  3165. MatchOperand(taicpu(p).oper[0]^, 0) and
  3166. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3167. begin
  3168. { mov 0, %reg
  3169. or ###,%reg
  3170. Change to (only if the flags are not used):
  3171. mov ###,%reg
  3172. }
  3173. TransferUsedRegs(TmpUsedRegs);
  3174. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3175. DoOptimisation := True;
  3176. { Even if the flags are used, we might be able to do the optimisation
  3177. if the conditions are predictable }
  3178. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3179. begin
  3180. { Only perform if ### = %reg (the same register) or equal to 0,
  3181. so %reg is guaranteed to still have a value of zero }
  3182. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3183. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3184. begin
  3185. hp2 := hp1;
  3186. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3187. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3188. GetNextInstruction(hp2, hp3) do
  3189. begin
  3190. { Don't continue modifying if the flags state is getting changed }
  3191. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3192. Break;
  3193. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3194. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3195. begin
  3196. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3197. begin
  3198. { Condition is always true }
  3199. case taicpu(hp3).opcode of
  3200. A_Jcc:
  3201. begin
  3202. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3203. { Check for jump shortcuts before we destroy the condition }
  3204. DoJumpOptimizations(hp3, TempBool);
  3205. MakeUnconditional(taicpu(hp3));
  3206. Result := True;
  3207. end;
  3208. A_CMOVcc:
  3209. begin
  3210. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3211. taicpu(hp3).opcode := A_MOV;
  3212. taicpu(hp3).condition := C_None;
  3213. Result := True;
  3214. end;
  3215. A_SETcc:
  3216. begin
  3217. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3218. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3219. taicpu(hp3).opcode := A_MOV;
  3220. taicpu(hp3).ops := 2;
  3221. taicpu(hp3).condition := C_None;
  3222. taicpu(hp3).opsize := S_B;
  3223. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3224. taicpu(hp3).loadconst(0, 1);
  3225. Result := True;
  3226. end;
  3227. else
  3228. InternalError(2021090701);
  3229. end;
  3230. end
  3231. 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
  3232. begin
  3233. { Condition is always false }
  3234. case taicpu(hp3).opcode of
  3235. A_Jcc:
  3236. begin
  3237. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3238. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3239. RemoveInstruction(hp3);
  3240. Result := True;
  3241. { Since hp3 was deleted, hp2 must not be updated }
  3242. Continue;
  3243. end;
  3244. A_CMOVcc:
  3245. begin
  3246. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3247. RemoveInstruction(hp3);
  3248. Result := True;
  3249. { Since hp3 was deleted, hp2 must not be updated }
  3250. Continue;
  3251. end;
  3252. A_SETcc:
  3253. begin
  3254. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3255. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3256. taicpu(hp3).opcode := A_MOV;
  3257. taicpu(hp3).ops := 2;
  3258. taicpu(hp3).condition := C_None;
  3259. taicpu(hp3).opsize := S_B;
  3260. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3261. taicpu(hp3).loadconst(0, 0);
  3262. Result := True;
  3263. end;
  3264. else
  3265. InternalError(2021090702);
  3266. end;
  3267. end
  3268. else
  3269. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3270. DoOptimisation := False;
  3271. end;
  3272. hp2 := hp3;
  3273. end;
  3274. { Flags are still in use - don't optimise }
  3275. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3276. DoOptimisation := False;
  3277. end
  3278. else
  3279. DoOptimisation := False;
  3280. end;
  3281. if DoOptimisation then
  3282. begin
  3283. {$ifdef x86_64}
  3284. { OR only supports 32-bit sign-extended constants for 64-bit
  3285. instructions, so compensate for this if the constant is
  3286. encoded as a value greater than or equal to 2^31 }
  3287. if (taicpu(hp1).opsize = S_Q) and
  3288. (taicpu(hp1).oper[0]^.typ = top_const) and
  3289. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3290. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3291. {$endif x86_64}
  3292. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3293. taicpu(hp1).opcode := A_MOV;
  3294. RemoveCurrentP(p, hp1);
  3295. Result := True;
  3296. Exit;
  3297. end;
  3298. end;
  3299. { Next instruction is also a MOV ? }
  3300. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3301. begin
  3302. if MatchOpType(taicpu(p), top_const, top_ref) and
  3303. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3304. TryConstMerge(p, hp1) then
  3305. begin
  3306. Result := True;
  3307. { In case we have four byte writes in a row, check for 2 more
  3308. right now so we don't have to wait for another iteration of
  3309. pass 1
  3310. }
  3311. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3312. case taicpu(p).opsize of
  3313. S_W:
  3314. begin
  3315. if GetNextInstruction(p, hp1) and
  3316. MatchInstruction(hp1, A_MOV, [S_B]) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. GetNextInstruction(hp1, hp2) and
  3319. MatchInstruction(hp2, A_MOV, [S_B]) and
  3320. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3321. { Try to merge the two bytes }
  3322. TryConstMerge(hp1, hp2) then
  3323. { Now try to merge the two words (hp2 will get deleted) }
  3324. TryConstMerge(p, hp1);
  3325. end;
  3326. S_L:
  3327. begin
  3328. { Though this only really benefits x86_64 and not i386, it
  3329. gets a potential optimisation done faster and hence
  3330. reduces the number of times OptPass1MOV is entered }
  3331. if GetNextInstruction(p, hp1) and
  3332. MatchInstruction(hp1, A_MOV, [S_W]) and
  3333. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3334. GetNextInstruction(hp1, hp2) and
  3335. MatchInstruction(hp2, A_MOV, [S_W]) and
  3336. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3337. { Try to merge the two words }
  3338. TryConstMerge(hp1, hp2) then
  3339. { This will always fail on i386, so don't bother
  3340. calling it unless we're doing x86_64 }
  3341. {$ifdef x86_64}
  3342. { Now try to merge the two longwords (hp2 will get deleted) }
  3343. TryConstMerge(p, hp1)
  3344. {$endif x86_64}
  3345. ;
  3346. end;
  3347. else
  3348. ;
  3349. end;
  3350. Exit;
  3351. end;
  3352. if (taicpu(p).oper[1]^.typ = top_reg) and
  3353. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3354. begin
  3355. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3356. TransferUsedRegs(TmpUsedRegs);
  3357. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3358. { we have
  3359. mov x, %treg
  3360. mov %treg, y
  3361. }
  3362. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3363. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3364. { we've got
  3365. mov x, %treg
  3366. mov %treg, y
  3367. with %treg is not used after }
  3368. case taicpu(p).oper[0]^.typ Of
  3369. { top_reg is covered by DeepMOVOpt }
  3370. top_const:
  3371. begin
  3372. { change
  3373. mov const, %treg
  3374. mov %treg, y
  3375. to
  3376. mov const, y
  3377. }
  3378. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3379. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3380. begin
  3381. if taicpu(hp1).oper[1]^.typ=top_reg then
  3382. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3383. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3385. RemoveInstruction(hp1);
  3386. Result:=true;
  3387. Exit;
  3388. end;
  3389. end;
  3390. top_ref:
  3391. case taicpu(hp1).oper[1]^.typ of
  3392. top_reg:
  3393. begin
  3394. { change
  3395. mov mem, %treg
  3396. mov %treg, %reg
  3397. to
  3398. mov mem, %reg"
  3399. }
  3400. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3401. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3402. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3403. RemoveInstruction(hp1);
  3404. Result:=true;
  3405. Exit;
  3406. end;
  3407. top_ref:
  3408. begin
  3409. {$ifdef x86_64}
  3410. { Look for the following to simplify:
  3411. mov x(mem1), %reg
  3412. mov %reg, y(mem2)
  3413. mov x+8(mem1), %reg
  3414. mov %reg, y+8(mem2)
  3415. Change to:
  3416. movdqu x(mem1), %xmmreg
  3417. movdqu %xmmreg, y(mem2)
  3418. ...but only as long as the memory blocks don't overlap
  3419. }
  3420. SourceRef := taicpu(p).oper[0]^.ref^;
  3421. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3422. if (taicpu(p).opsize = S_Q) and
  3423. GetNextInstruction(hp1, hp2) and
  3424. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3425. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3426. begin
  3427. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3428. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3429. Inc(SourceRef.offset, 8);
  3430. if UseAVX then
  3431. begin
  3432. MovAligned := A_VMOVDQA;
  3433. MovUnaligned := A_VMOVDQU;
  3434. end
  3435. else
  3436. begin
  3437. MovAligned := A_MOVDQA;
  3438. MovUnaligned := A_MOVDQU;
  3439. end;
  3440. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3441. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3442. begin
  3443. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3444. Inc(TargetRef.offset, 8);
  3445. if GetNextInstruction(hp2, hp3) and
  3446. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3447. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3448. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3449. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3450. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3451. begin
  3452. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3453. if NewMMReg <> NR_NO then
  3454. begin
  3455. { Remember that the offsets are 8 ahead }
  3456. if ((SourceRef.offset mod 16) = 8) and
  3457. (
  3458. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3459. (SourceRef.base = current_procinfo.framepointer) or
  3460. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3461. ) then
  3462. taicpu(p).opcode := MovAligned
  3463. else
  3464. taicpu(p).opcode := MovUnaligned;
  3465. taicpu(p).opsize := S_XMM;
  3466. taicpu(p).oper[1]^.reg := NewMMReg;
  3467. if ((TargetRef.offset mod 16) = 8) and
  3468. (
  3469. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3470. (TargetRef.base = current_procinfo.framepointer) or
  3471. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3472. ) then
  3473. taicpu(hp1).opcode := MovAligned
  3474. else
  3475. taicpu(hp1).opcode := MovUnaligned;
  3476. taicpu(hp1).opsize := S_XMM;
  3477. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3478. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3479. RemoveInstruction(hp2);
  3480. RemoveInstruction(hp3);
  3481. Result := True;
  3482. Exit;
  3483. end;
  3484. end;
  3485. end
  3486. else
  3487. begin
  3488. { See if the next references are 8 less rather than 8 greater }
  3489. Dec(SourceRef.offset, 16); { -8 the other way }
  3490. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3491. begin
  3492. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3493. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3494. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3495. GetNextInstruction(hp2, hp3) and
  3496. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3497. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3498. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3499. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3500. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3501. begin
  3502. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3503. if NewMMReg <> NR_NO then
  3504. begin
  3505. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3506. if ((SourceRef.offset mod 16) = 0) and
  3507. (
  3508. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3509. (SourceRef.base = current_procinfo.framepointer) or
  3510. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3511. ) then
  3512. taicpu(hp2).opcode := MovAligned
  3513. else
  3514. taicpu(hp2).opcode := MovUnaligned;
  3515. taicpu(hp2).opsize := S_XMM;
  3516. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3517. if ((TargetRef.offset mod 16) = 0) and
  3518. (
  3519. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3520. (TargetRef.base = current_procinfo.framepointer) or
  3521. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3522. ) then
  3523. taicpu(hp3).opcode := MovAligned
  3524. else
  3525. taicpu(hp3).opcode := MovUnaligned;
  3526. taicpu(hp3).opsize := S_XMM;
  3527. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3528. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3529. RemoveInstruction(hp1);
  3530. RemoveCurrentP(p, hp2);
  3531. Result := True;
  3532. Exit;
  3533. end;
  3534. end;
  3535. end;
  3536. end;
  3537. end;
  3538. {$endif x86_64}
  3539. end;
  3540. else
  3541. { The write target should be a reg or a ref }
  3542. InternalError(2021091601);
  3543. end;
  3544. else
  3545. ;
  3546. end
  3547. else
  3548. { %treg is used afterwards, but all eventualities
  3549. other than the first MOV instruction being a constant
  3550. are covered by DeepMOVOpt, so only check for that }
  3551. if (taicpu(p).oper[0]^.typ = top_const) and
  3552. (
  3553. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3554. not (cs_opt_size in current_settings.optimizerswitches) or
  3555. (taicpu(hp1).opsize = S_B)
  3556. ) and
  3557. (
  3558. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3559. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3560. ) then
  3561. begin
  3562. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3563. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3564. end;
  3565. end;
  3566. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3567. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3568. { mov reg1, mem1 or mov mem1, reg1
  3569. mov mem2, reg2 mov reg2, mem2}
  3570. begin
  3571. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3572. { mov reg1, mem1 or mov mem1, reg1
  3573. mov mem2, reg1 mov reg2, mem1}
  3574. begin
  3575. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3576. { Removes the second statement from
  3577. mov reg1, mem1/reg2
  3578. mov mem1/reg2, reg1 }
  3579. begin
  3580. if taicpu(p).oper[0]^.typ=top_reg then
  3581. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3582. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3583. RemoveInstruction(hp1);
  3584. Result:=true;
  3585. exit;
  3586. end
  3587. else
  3588. begin
  3589. TransferUsedRegs(TmpUsedRegs);
  3590. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3591. if (taicpu(p).oper[1]^.typ = top_ref) and
  3592. { mov reg1, mem1
  3593. mov mem2, reg1 }
  3594. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3595. GetNextInstruction(hp1, hp2) and
  3596. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3597. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3598. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3599. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3600. { change to
  3601. mov reg1, mem1 mov reg1, mem1
  3602. mov mem2, reg1 cmp reg1, mem2
  3603. cmp mem1, reg1
  3604. }
  3605. begin
  3606. RemoveInstruction(hp2);
  3607. taicpu(hp1).opcode := A_CMP;
  3608. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3609. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3610. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3611. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3612. end;
  3613. end;
  3614. end
  3615. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3616. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3617. begin
  3618. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3619. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3620. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3621. end
  3622. else
  3623. begin
  3624. TransferUsedRegs(TmpUsedRegs);
  3625. if GetNextInstruction(hp1, hp2) and
  3626. MatchOpType(taicpu(p),top_ref,top_reg) and
  3627. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3628. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3629. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3630. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3631. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3632. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3633. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3634. { mov mem1, %reg1
  3635. mov %reg1, mem2
  3636. mov mem2, reg2
  3637. to:
  3638. mov mem1, reg2
  3639. mov reg2, mem2}
  3640. begin
  3641. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3642. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3643. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3644. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3645. RemoveInstruction(hp2);
  3646. Result := True;
  3647. end
  3648. {$ifdef i386}
  3649. { this is enabled for i386 only, as the rules to create the reg sets below
  3650. are too complicated for x86-64, so this makes this code too error prone
  3651. on x86-64
  3652. }
  3653. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3654. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3655. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3656. { mov mem1, reg1 mov mem1, reg1
  3657. mov reg1, mem2 mov reg1, mem2
  3658. mov mem2, reg2 mov mem2, reg1
  3659. to: to:
  3660. mov mem1, reg1 mov mem1, reg1
  3661. mov mem1, reg2 mov reg1, mem2
  3662. mov reg1, mem2
  3663. or (if mem1 depends on reg1
  3664. and/or if mem2 depends on reg2)
  3665. to:
  3666. mov mem1, reg1
  3667. mov reg1, mem2
  3668. mov reg1, reg2
  3669. }
  3670. begin
  3671. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3672. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3673. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3674. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3675. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3676. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3677. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3678. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3679. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3680. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3681. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3682. end
  3683. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3684. begin
  3685. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3686. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3687. end
  3688. else
  3689. begin
  3690. RemoveInstruction(hp2);
  3691. end
  3692. {$endif i386}
  3693. ;
  3694. end;
  3695. end
  3696. { movl [mem1],reg1
  3697. movl [mem1],reg2
  3698. to
  3699. movl [mem1],reg1
  3700. movl reg1,reg2
  3701. }
  3702. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3703. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3704. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3705. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3706. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3707. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3708. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3709. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3710. begin
  3711. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3712. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3713. end;
  3714. { movl const1,[mem1]
  3715. movl [mem1],reg1
  3716. to
  3717. movl const1,reg1
  3718. movl reg1,[mem1]
  3719. }
  3720. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3721. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3722. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3723. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3724. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3725. begin
  3726. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3727. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3728. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3729. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3730. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3731. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3732. Result:=true;
  3733. exit;
  3734. end;
  3735. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3736. { Change:
  3737. movl %reg1,%reg2
  3738. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3739. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3740. To:
  3741. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3742. movl x(%reg1),%reg1
  3743. movl %reg1,%regX
  3744. }
  3745. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3746. begin
  3747. p_SourceReg := taicpu(p).oper[0]^.reg;
  3748. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3749. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3750. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3751. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3752. GetNextInstruction(hp1, hp2) and
  3753. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3754. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3755. begin
  3756. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3757. if RegInRef(p_TargetReg, SourceRef) and
  3758. { If %reg1 also appears in the second reference, then it will
  3759. not refer to the same memory block as the first reference }
  3760. not RegInRef(p_SourceReg, SourceRef) then
  3761. begin
  3762. { Check to see if the references match if %reg2 is changed to %reg1 }
  3763. if SourceRef.base = p_TargetReg then
  3764. SourceRef.base := p_SourceReg;
  3765. if SourceRef.index = p_TargetReg then
  3766. SourceRef.index := p_SourceReg;
  3767. { RefsEqual also checks to ensure both references are non-volatile }
  3768. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3769. begin
  3770. taicpu(hp2).loadreg(0, p_SourceReg);
  3771. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3772. Result := True;
  3773. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3774. begin
  3775. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3776. RemoveCurrentP(p, hp1);
  3777. Exit;
  3778. end
  3779. else
  3780. begin
  3781. { Check to see if %reg2 is no longer in use }
  3782. TransferUsedRegs(TmpUsedRegs);
  3783. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3784. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3785. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3786. begin
  3787. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3788. RemoveCurrentP(p, hp1);
  3789. Exit;
  3790. end;
  3791. end;
  3792. { If we reach this point, p and hp1 weren't actually modified,
  3793. so we can do a bit more work on this pass }
  3794. end;
  3795. end;
  3796. end;
  3797. end;
  3798. end;
  3799. {$ifdef x86_64}
  3800. { Change:
  3801. movl %reg1l,%reg2l
  3802. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3803. To:
  3804. movl %reg1l,%reg2l
  3805. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3806. If %reg1 = %reg3, convert to:
  3807. movl %reg1l,%reg2l
  3808. andl %reg1l,%reg1l
  3809. }
  3810. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3811. MatchOpType(taicpu(p), top_reg, top_reg) and
  3812. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3813. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3814. begin
  3815. TransferUsedRegs(TmpUsedRegs);
  3816. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3817. taicpu(hp1).opsize := S_L;
  3818. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3819. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3820. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3821. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3822. begin
  3823. { %reg1 = %reg3 }
  3824. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3825. taicpu(hp1).opcode := A_AND;
  3826. end
  3827. else
  3828. begin
  3829. { %reg1 <> %reg3 }
  3830. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3831. end;
  3832. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3833. begin
  3834. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3835. RemoveCurrentP(p, hp1);
  3836. Result := True;
  3837. Exit;
  3838. end
  3839. else
  3840. begin
  3841. { Initial instruction wasn't actually changed }
  3842. Include(OptsToCheck, aoc_ForceNewIteration);
  3843. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3844. appears below since %reg1 has technically changed }
  3845. if taicpu(hp1).opcode = A_AND then
  3846. Exit;
  3847. end;
  3848. end;
  3849. {$endif x86_64}
  3850. { search further than the next instruction for a mov (as long as it's not a jump) }
  3851. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3852. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3853. (taicpu(p).oper[1]^.typ = top_reg) and
  3854. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3855. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3856. begin
  3857. { we work with hp2 here, so hp1 can be still used later on when
  3858. checking for GetNextInstruction_p }
  3859. hp3 := hp1;
  3860. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3861. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3862. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3863. TransferUsedRegs(TmpUsedRegs);
  3864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3865. if NotFirstIteration then
  3866. JumpTracking := TLinkedList.Create
  3867. else
  3868. JumpTracking := nil;
  3869. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3870. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3871. (hp2.typ=ait_instruction) do
  3872. begin
  3873. case taicpu(hp2).opcode of
  3874. A_POP:
  3875. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3876. begin
  3877. if not CrossJump and
  3878. not RegUsedBetween(p_TargetReg, p, hp2) then
  3879. begin
  3880. { We can remove the original MOV since the register
  3881. wasn't used between it and its popping from the stack }
  3882. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3883. RemoveCurrentp(p, hp1);
  3884. Result := True;
  3885. JumpTracking.Free;
  3886. Exit;
  3887. end;
  3888. { Can't go any further }
  3889. Break;
  3890. end;
  3891. A_MOV:
  3892. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3893. ((taicpu(p).oper[0]^.typ=top_const) or
  3894. ((taicpu(p).oper[0]^.typ=top_reg) and
  3895. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3896. )
  3897. ) then
  3898. begin
  3899. { we have
  3900. mov x, %treg
  3901. mov %treg, y
  3902. }
  3903. { We don't need to call UpdateUsedRegs for every instruction between
  3904. p and hp2 because the register we're concerned about will not
  3905. become deallocated (otherwise GetNextInstructionUsingReg would
  3906. have stopped at an earlier instruction). [Kit] }
  3907. TempRegUsed :=
  3908. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3909. RegReadByInstruction(p_TargetReg, hp3) or
  3910. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3911. case taicpu(p).oper[0]^.typ Of
  3912. top_reg:
  3913. begin
  3914. { change
  3915. mov %reg, %treg
  3916. mov %treg, y
  3917. to
  3918. mov %reg, y
  3919. }
  3920. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3921. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3922. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3923. begin
  3924. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3925. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3926. if TempRegUsed then
  3927. begin
  3928. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3929. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3930. { Set the start of the next GetNextInstructionUsingRegCond search
  3931. to start at the entry right before hp2 (which is about to be removed) }
  3932. hp3 := tai(hp2.Previous);
  3933. RemoveInstruction(hp2);
  3934. Include(OptsToCheck, aoc_ForceNewIteration);
  3935. { See if there's more we can optimise }
  3936. Continue;
  3937. end
  3938. else
  3939. begin
  3940. RemoveInstruction(hp2);
  3941. { We can remove the original MOV too }
  3942. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3943. RemoveCurrentP(p, hp1);
  3944. Result:=true;
  3945. JumpTracking.Free;
  3946. Exit;
  3947. end;
  3948. end
  3949. else
  3950. begin
  3951. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3952. taicpu(hp2).loadReg(0, p_SourceReg);
  3953. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3954. { Check to see if the register also appears in the reference }
  3955. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3956. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3957. { Don't remove the first instruction if the temporary register is in use }
  3958. if not TempRegUsed and
  3959. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3960. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3961. begin
  3962. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3963. RemoveCurrentP(p, hp1);
  3964. Result:=true;
  3965. JumpTracking.Free;
  3966. Exit;
  3967. end;
  3968. { No need to set Result to True here. If there's another instruction later
  3969. on that can be optimised, it will be detected when the main Pass 1 loop
  3970. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3971. end;
  3972. end;
  3973. top_const:
  3974. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3975. begin
  3976. { change
  3977. mov const, %treg
  3978. mov %treg, y
  3979. to
  3980. mov const, y
  3981. }
  3982. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3983. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3984. begin
  3985. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3986. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3987. if TempRegUsed then
  3988. begin
  3989. { Don't remove the first instruction if the temporary register is in use }
  3990. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3991. { No need to set Result to True. If there's another instruction later on
  3992. that can be optimised, it will be detected when the main Pass 1 loop
  3993. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3994. end
  3995. else
  3996. begin
  3997. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3998. RemoveCurrentP(p, hp1);
  3999. Result:=true;
  4000. Exit;
  4001. end;
  4002. end;
  4003. end;
  4004. else
  4005. Internalerror(2019103001);
  4006. end;
  4007. end
  4008. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4009. begin
  4010. if not CrossJump and
  4011. not RegUsedBetween(p_TargetReg, p, hp2) and
  4012. not RegReadByInstruction(p_TargetReg, hp2) then
  4013. begin
  4014. { Register is not used before it is overwritten }
  4015. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4016. RemoveCurrentp(p, hp1);
  4017. Result := True;
  4018. Exit;
  4019. end;
  4020. if (taicpu(p).oper[0]^.typ = top_const) and
  4021. (taicpu(hp2).oper[0]^.typ = top_const) then
  4022. begin
  4023. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4024. begin
  4025. { Same value - register hasn't changed }
  4026. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4027. RemoveInstruction(hp2);
  4028. Include(OptsToCheck, aoc_ForceNewIteration);
  4029. { See if there's more we can optimise }
  4030. Continue;
  4031. end;
  4032. end;
  4033. {$ifdef x86_64}
  4034. end
  4035. { Change:
  4036. movl %reg1l,%reg2l
  4037. ...
  4038. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4039. To:
  4040. movl %reg1l,%reg2l
  4041. ...
  4042. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4043. If %reg1 = %reg3, convert to:
  4044. movl %reg1l,%reg2l
  4045. ...
  4046. andl %reg1l,%reg1l
  4047. }
  4048. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4049. (taicpu(p).oper[0]^.typ = top_reg) and
  4050. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4051. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4052. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4053. begin
  4054. TempRegUsed :=
  4055. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4056. RegReadByInstruction(p_TargetReg, hp3) or
  4057. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4058. taicpu(hp2).opsize := S_L;
  4059. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4060. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4062. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4063. begin
  4064. { %reg1 = %reg3 }
  4065. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4066. taicpu(hp2).opcode := A_AND;
  4067. end
  4068. else
  4069. begin
  4070. { %reg1 <> %reg3 }
  4071. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4072. end;
  4073. if not TempRegUsed then
  4074. begin
  4075. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4076. RemoveCurrentP(p, hp1);
  4077. Result := True;
  4078. Exit;
  4079. end
  4080. else
  4081. begin
  4082. { Initial instruction wasn't actually changed }
  4083. Include(OptsToCheck, aoc_ForceNewIteration);
  4084. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4085. appears below since %reg1 has technically changed }
  4086. if taicpu(hp2).opcode = A_AND then
  4087. Break;
  4088. end;
  4089. {$endif x86_64}
  4090. end;
  4091. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4092. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4093. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4094. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4095. begin
  4096. {
  4097. Change from:
  4098. mov ###, %reg
  4099. ...
  4100. movs/z %reg,%reg (Same register, just different sizes)
  4101. To:
  4102. movs/z ###, %reg (Longer version)
  4103. ...
  4104. (remove)
  4105. }
  4106. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4107. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4108. { Keep the first instruction as mov if ### is a constant }
  4109. if taicpu(p).oper[0]^.typ = top_const then
  4110. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4111. else
  4112. begin
  4113. taicpu(p).opcode := taicpu(hp2).opcode;
  4114. taicpu(p).opsize := taicpu(hp2).opsize;
  4115. end;
  4116. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4117. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4118. RemoveInstruction(hp2);
  4119. Result := True;
  4120. JumpTracking.Free;
  4121. Exit;
  4122. end;
  4123. else
  4124. { Move down to the if-block below };
  4125. end;
  4126. { Also catches MOV/S/Z instructions that aren't modified }
  4127. if taicpu(p).oper[0]^.typ = top_reg then
  4128. begin
  4129. p_SourceReg := taicpu(p).oper[0]^.reg;
  4130. if
  4131. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4132. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4133. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4134. begin
  4135. Result := True;
  4136. { Just in case something didn't get modified (e.g. an
  4137. implicit register). Also, if it does read from this
  4138. register, then there's no longer an advantage to
  4139. changing the register on subsequent instructions.}
  4140. if not RegReadByInstruction(p_TargetReg, hp2) then
  4141. begin
  4142. { If a conditional jump was crossed, do not delete
  4143. the original MOV no matter what }
  4144. if not CrossJump and
  4145. { RegEndOfLife returns True if the register is
  4146. deallocated before the next instruction or has
  4147. been loaded with a new value }
  4148. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4149. begin
  4150. { We can remove the original MOV }
  4151. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4152. RemoveCurrentp(p, hp1);
  4153. JumpTracking.Free;
  4154. Result := True;
  4155. Exit;
  4156. end;
  4157. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4158. begin
  4159. { See if there's more we can optimise }
  4160. hp3 := hp2;
  4161. Continue;
  4162. end;
  4163. end;
  4164. end;
  4165. end;
  4166. { Break out of the while loop under normal circumstances }
  4167. Break;
  4168. end;
  4169. JumpTracking.Free;
  4170. end;
  4171. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4172. (taicpu(p).oper[1]^.typ = top_reg) and
  4173. (taicpu(p).opsize = S_L) and
  4174. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4175. (hp2.typ = ait_instruction) and
  4176. (taicpu(hp2).opcode = A_AND) and
  4177. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4178. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4179. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4180. ) then
  4181. begin
  4182. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4183. begin
  4184. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4185. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4186. begin
  4187. { Optimize out:
  4188. mov x, %reg
  4189. and ffffffffh, %reg
  4190. }
  4191. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4192. RemoveInstruction(hp2);
  4193. Result:=true;
  4194. exit;
  4195. end;
  4196. end;
  4197. end;
  4198. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4199. x >= RetOffset) as it doesn't do anything (it writes either to a
  4200. parameter or to the temporary storage room for the function
  4201. result)
  4202. }
  4203. if IsExitCode(hp1) and
  4204. (taicpu(p).oper[1]^.typ = top_ref) and
  4205. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4206. (
  4207. (
  4208. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4209. not (
  4210. assigned(current_procinfo.procdef.funcretsym) and
  4211. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4212. )
  4213. ) or
  4214. { Also discard writes to the stack that are below the base pointer,
  4215. as this is temporary storage rather than a function result on the
  4216. stack, say. }
  4217. (
  4218. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4219. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4220. )
  4221. ) then
  4222. begin
  4223. RemoveCurrentp(p, hp1);
  4224. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4225. RemoveLastDeallocForFuncRes(p);
  4226. Result:=true;
  4227. exit;
  4228. end;
  4229. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4230. begin
  4231. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4232. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4233. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4234. begin
  4235. { change
  4236. mov reg1, mem1
  4237. test/cmp x, mem1
  4238. to
  4239. mov reg1, mem1
  4240. test/cmp x, reg1
  4241. }
  4242. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4243. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4244. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4245. Result := True;
  4246. Exit;
  4247. end;
  4248. if DoMovCmpMemOpt(p, hp1) then
  4249. begin
  4250. Result := True;
  4251. Exit;
  4252. end;
  4253. end;
  4254. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4255. { If the flags register is in use, don't change the instruction to an
  4256. ADD otherwise this will scramble the flags. [Kit] }
  4257. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4258. begin
  4259. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4260. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4261. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4262. ) or
  4263. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4264. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4265. )
  4266. ) then
  4267. { mov reg1,ref
  4268. lea reg2,[reg1,reg2]
  4269. to
  4270. add reg2,ref}
  4271. begin
  4272. TransferUsedRegs(TmpUsedRegs);
  4273. { reg1 may not be used afterwards }
  4274. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4275. begin
  4276. Taicpu(hp1).opcode:=A_ADD;
  4277. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4278. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4279. RemoveCurrentp(p, hp1);
  4280. result:=true;
  4281. exit;
  4282. end;
  4283. end;
  4284. { If the LEA instruction can be converted into an arithmetic instruction,
  4285. it may be possible to then fold it in the next optimisation, otherwise
  4286. there's nothing more that can be optimised here. }
  4287. if not ConvertLEA(taicpu(hp1)) then
  4288. Exit;
  4289. end;
  4290. if (taicpu(p).oper[1]^.typ = top_reg) and
  4291. (hp1.typ = ait_instruction) and
  4292. GetNextInstruction(hp1, hp2) and
  4293. MatchInstruction(hp2,A_MOV,[]) and
  4294. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4295. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4296. (
  4297. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4298. {$ifdef x86_64}
  4299. or
  4300. (
  4301. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4302. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4303. )
  4304. {$endif x86_64}
  4305. ) then
  4306. begin
  4307. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4308. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4309. { change movsX/movzX reg/ref, reg2
  4310. add/sub/or/... reg3/$const, reg2
  4311. mov reg2 reg/ref
  4312. dealloc reg2
  4313. to
  4314. add/sub/or/... reg3/$const, reg/ref }
  4315. begin
  4316. TransferUsedRegs(TmpUsedRegs);
  4317. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4318. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4319. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4320. begin
  4321. { by example:
  4322. movswl %si,%eax movswl %si,%eax p
  4323. decl %eax addl %edx,%eax hp1
  4324. movw %ax,%si movw %ax,%si hp2
  4325. ->
  4326. movswl %si,%eax movswl %si,%eax p
  4327. decw %eax addw %edx,%eax hp1
  4328. movw %ax,%si movw %ax,%si hp2
  4329. }
  4330. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4331. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4332. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4333. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4334. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4335. {
  4336. ->
  4337. movswl %si,%eax movswl %si,%eax p
  4338. decw %si addw %dx,%si hp1
  4339. movw %ax,%si movw %ax,%si hp2
  4340. }
  4341. case taicpu(hp1).ops of
  4342. 1:
  4343. begin
  4344. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4345. if taicpu(hp1).oper[0]^.typ=top_reg then
  4346. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4347. end;
  4348. 2:
  4349. begin
  4350. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4351. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4352. (taicpu(hp1).opcode<>A_SHL) and
  4353. (taicpu(hp1).opcode<>A_SHR) and
  4354. (taicpu(hp1).opcode<>A_SAR) then
  4355. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4356. end;
  4357. else
  4358. internalerror(2008042701);
  4359. end;
  4360. {
  4361. ->
  4362. decw %si addw %dx,%si p
  4363. }
  4364. RemoveInstruction(hp2);
  4365. RemoveCurrentP(p, hp1);
  4366. Result:=True;
  4367. Exit;
  4368. end;
  4369. end;
  4370. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4371. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4372. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4373. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4374. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4375. )
  4376. {$ifdef i386}
  4377. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4378. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4379. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4380. {$endif i386}
  4381. then
  4382. { change movsX/movzX reg/ref, reg2
  4383. add/sub/or/... regX/$const, reg2
  4384. mov reg2, reg3
  4385. dealloc reg2
  4386. to
  4387. movsX/movzX reg/ref, reg3
  4388. add/sub/or/... reg3/$const, reg3
  4389. }
  4390. begin
  4391. TransferUsedRegs(TmpUsedRegs);
  4392. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4393. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4394. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4395. begin
  4396. { by example:
  4397. movswl %si,%eax movswl %si,%eax p
  4398. decl %eax addl %edx,%eax hp1
  4399. movw %ax,%si movw %ax,%si hp2
  4400. ->
  4401. movswl %si,%eax movswl %si,%eax p
  4402. decw %eax addw %edx,%eax hp1
  4403. movw %ax,%si movw %ax,%si hp2
  4404. }
  4405. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4406. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4407. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4408. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4409. { limit size of constants as well to avoid assembler errors, but
  4410. check opsize to avoid overflow when left shifting the 1 }
  4411. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4412. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4413. {$ifdef x86_64}
  4414. { Be careful of, for example:
  4415. movl %reg1,%reg2
  4416. addl %reg3,%reg2
  4417. movq %reg2,%reg4
  4418. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4419. }
  4420. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4421. begin
  4422. taicpu(hp2).changeopsize(S_L);
  4423. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4424. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4425. end;
  4426. {$endif x86_64}
  4427. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4428. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4429. if taicpu(p).oper[0]^.typ=top_reg then
  4430. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4431. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4432. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4433. {
  4434. ->
  4435. movswl %si,%eax movswl %si,%eax p
  4436. decw %si addw %dx,%si hp1
  4437. movw %ax,%si movw %ax,%si hp2
  4438. }
  4439. case taicpu(hp1).ops of
  4440. 1:
  4441. begin
  4442. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4443. if taicpu(hp1).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. end;
  4446. 2:
  4447. begin
  4448. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4449. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4450. (taicpu(hp1).opcode<>A_SHL) and
  4451. (taicpu(hp1).opcode<>A_SHR) and
  4452. (taicpu(hp1).opcode<>A_SAR) then
  4453. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4454. end;
  4455. else
  4456. internalerror(2018111801);
  4457. end;
  4458. {
  4459. ->
  4460. decw %si addw %dx,%si p
  4461. }
  4462. RemoveInstruction(hp2);
  4463. end;
  4464. end;
  4465. end;
  4466. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4467. GetNextInstruction(hp1, hp2) and
  4468. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4469. MatchOperand(Taicpu(p).oper[0]^,0) and
  4470. (Taicpu(p).oper[1]^.typ = top_reg) and
  4471. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4472. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4473. { mov reg1,0
  4474. bts reg1,operand1 --> mov reg1,operand2
  4475. or reg1,operand2 bts reg1,operand1}
  4476. begin
  4477. Taicpu(hp2).opcode:=A_MOV;
  4478. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4479. asml.remove(hp1);
  4480. insertllitem(hp2,hp2.next,hp1);
  4481. RemoveCurrentp(p, hp1);
  4482. Result:=true;
  4483. exit;
  4484. end;
  4485. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4487. GetNextInstruction(hp1, hp2) and
  4488. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4489. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4490. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4491. { change
  4492. mov reg1,reg2
  4493. sub reg3,reg2
  4494. cmp reg3,reg1
  4495. into
  4496. mov reg1,reg2
  4497. sub reg3,reg2
  4498. }
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4501. RemoveInstruction(hp2);
  4502. Result:=true;
  4503. exit;
  4504. end;
  4505. {
  4506. mov ref,reg0
  4507. <op> reg0,reg1
  4508. dealloc reg0
  4509. to
  4510. <op> ref,reg1
  4511. }
  4512. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4513. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4514. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4515. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4516. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4517. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4518. begin
  4519. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4520. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4521. RemoveCurrentp(p, hp1);
  4522. Result:=true;
  4523. exit;
  4524. end;
  4525. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4526. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4527. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4528. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4529. begin
  4530. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4531. {$ifdef x86_64}
  4532. { Convert:
  4533. movq x(ref),%reg64
  4534. shrq y,%reg64
  4535. To:
  4536. movl x+4(ref),%reg32
  4537. shrl y-32,%reg32 (Remove if y = 32)
  4538. }
  4539. if (taicpu(p).opsize = S_Q) and
  4540. (taicpu(hp1).opcode = A_SHR) and
  4541. (taicpu(hp1).oper[0]^.val >= 32) then
  4542. begin
  4543. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4544. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4545. { Convert to 32-bit }
  4546. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4547. taicpu(p).opsize := S_L;
  4548. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4549. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4550. if (taicpu(hp1).oper[0]^.val = 32) then
  4551. begin
  4552. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4553. RemoveInstruction(hp1);
  4554. end
  4555. else
  4556. begin
  4557. { This will potentially open up more arithmetic operations since
  4558. the peephole optimizer now has a big hint that only the lower
  4559. 32 bits are currently in use (and opcodes are smaller in size) }
  4560. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4561. taicpu(hp1).opsize := S_L;
  4562. Dec(taicpu(hp1).oper[0]^.val, 32);
  4563. DebugMsg(SPeepholeOptimization + PreMessage +
  4564. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4565. end;
  4566. Result := True;
  4567. Exit;
  4568. end;
  4569. {$endif x86_64}
  4570. { Convert:
  4571. movl x(ref),%reg
  4572. shrl $24,%reg
  4573. To:
  4574. movzbl x+3(ref),%reg
  4575. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4576. Also accept sar instead of shr, but convert to movsx instead of movzx
  4577. }
  4578. if taicpu(hp1).opcode = A_SHR then
  4579. MovUnaligned := A_MOVZX
  4580. else
  4581. MovUnaligned := A_MOVSX;
  4582. NewSize := S_NO;
  4583. NewOffset := 0;
  4584. case taicpu(p).opsize of
  4585. S_B:
  4586. { No valid combinations };
  4587. S_W:
  4588. if (taicpu(hp1).oper[0]^.val = 8) then
  4589. begin
  4590. NewSize := S_BW;
  4591. NewOffset := 1;
  4592. end;
  4593. S_L:
  4594. case taicpu(hp1).oper[0]^.val of
  4595. 16:
  4596. begin
  4597. NewSize := S_WL;
  4598. NewOffset := 2;
  4599. end;
  4600. 24:
  4601. begin
  4602. NewSize := S_BL;
  4603. NewOffset := 3;
  4604. end;
  4605. else
  4606. ;
  4607. end;
  4608. {$ifdef x86_64}
  4609. S_Q:
  4610. case taicpu(hp1).oper[0]^.val of
  4611. 32:
  4612. begin
  4613. if taicpu(hp1).opcode = A_SAR then
  4614. begin
  4615. { 32-bit to 64-bit is a distinct instruction }
  4616. MovUnaligned := A_MOVSXD;
  4617. NewSize := S_LQ;
  4618. NewOffset := 4;
  4619. end
  4620. else
  4621. { Should have been handled by MovShr2Mov above }
  4622. InternalError(2022081811);
  4623. end;
  4624. 48:
  4625. begin
  4626. NewSize := S_WQ;
  4627. NewOffset := 6;
  4628. end;
  4629. 56:
  4630. begin
  4631. NewSize := S_BQ;
  4632. NewOffset := 7;
  4633. end;
  4634. else
  4635. ;
  4636. end;
  4637. {$endif x86_64}
  4638. else
  4639. InternalError(2022081810);
  4640. end;
  4641. if (NewSize <> S_NO) and
  4642. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4643. begin
  4644. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4645. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4646. debug_op2str(MovUnaligned);
  4647. {$ifdef x86_64}
  4648. if MovUnaligned <> A_MOVSXD then
  4649. { Don't add size suffix for MOVSXD }
  4650. {$endif x86_64}
  4651. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4652. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4653. taicpu(p).opcode := MovUnaligned;
  4654. taicpu(p).opsize := NewSize;
  4655. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4656. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4657. RemoveInstruction(hp1);
  4658. Result := True;
  4659. Exit;
  4660. end;
  4661. end;
  4662. { Backward optimisation shared with OptPass2MOV }
  4663. if FuncMov2Func(p, hp1) then
  4664. begin
  4665. Result := True;
  4666. Exit;
  4667. end;
  4668. end;
  4669. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4670. var
  4671. hp1 : tai;
  4672. begin
  4673. Result:=false;
  4674. if taicpu(p).ops <> 2 then
  4675. exit;
  4676. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4677. GetNextInstruction(p,hp1) then
  4678. begin
  4679. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4680. (taicpu(hp1).ops = 2) then
  4681. begin
  4682. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4683. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4684. { movXX reg1, mem1 or movXX mem1, reg1
  4685. movXX mem2, reg2 movXX reg2, mem2}
  4686. begin
  4687. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4688. { movXX reg1, mem1 or movXX mem1, reg1
  4689. movXX mem2, reg1 movXX reg2, mem1}
  4690. begin
  4691. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4692. begin
  4693. { Removes the second statement from
  4694. movXX reg1, mem1/reg2
  4695. movXX mem1/reg2, reg1
  4696. }
  4697. if taicpu(p).oper[0]^.typ=top_reg then
  4698. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4699. { Removes the second statement from
  4700. movXX mem1/reg1, reg2
  4701. movXX reg2, mem1/reg1
  4702. }
  4703. if (taicpu(p).oper[1]^.typ=top_reg) and
  4704. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4705. begin
  4706. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4707. RemoveInstruction(hp1);
  4708. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4709. Result:=true;
  4710. exit;
  4711. end
  4712. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4713. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4714. begin
  4715. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4716. RemoveInstruction(hp1);
  4717. Result:=true;
  4718. exit;
  4719. end;
  4720. end
  4721. end;
  4722. end;
  4723. end;
  4724. end;
  4725. end;
  4726. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4727. var
  4728. hp1 : tai;
  4729. begin
  4730. result:=false;
  4731. { replace
  4732. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4733. MovX %mreg2,%mreg1
  4734. dealloc %mreg2
  4735. by
  4736. <Op>X %mreg2,%mreg1
  4737. ?
  4738. }
  4739. if GetNextInstruction(p,hp1) and
  4740. { we mix single and double opperations here because we assume that the compiler
  4741. generates vmovapd only after double operations and vmovaps only after single operations }
  4742. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4743. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4744. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4745. (taicpu(p).oper[0]^.typ=top_reg) then
  4746. begin
  4747. TransferUsedRegs(TmpUsedRegs);
  4748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4749. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4750. begin
  4751. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4752. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4753. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4754. RemoveInstruction(hp1);
  4755. result:=true;
  4756. end;
  4757. end;
  4758. end;
  4759. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4760. var
  4761. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4762. JumpLabel, JumpLabel_dist: TAsmLabel;
  4763. FirstValue, SecondValue: TCGInt;
  4764. TempBool: Boolean;
  4765. begin
  4766. Result := False;
  4767. if (taicpu(p).oper[0]^.typ = top_const) and
  4768. (taicpu(p).oper[0]^.val <> -1) then
  4769. begin
  4770. { Convert unsigned maximum constants to -1 to aid optimisation }
  4771. case taicpu(p).opsize of
  4772. S_B:
  4773. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4774. begin
  4775. taicpu(p).oper[0]^.val := -1;
  4776. Result := True;
  4777. Exit;
  4778. end;
  4779. S_W:
  4780. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4781. begin
  4782. taicpu(p).oper[0]^.val := -1;
  4783. Result := True;
  4784. Exit;
  4785. end;
  4786. S_L:
  4787. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. {$ifdef x86_64}
  4794. S_Q:
  4795. { Storing anything greater than $7FFFFFFF is not possible so do
  4796. nothing };
  4797. {$endif x86_64}
  4798. else
  4799. InternalError(2021121001);
  4800. end;
  4801. end;
  4802. if GetNextInstruction(p, hp1) and
  4803. TrySwapMovCmp(p, hp1) then
  4804. begin
  4805. Result := True;
  4806. Exit;
  4807. end;
  4808. if MatchInstruction(hp1, A_Jcc, []) then
  4809. begin
  4810. TempBool := True;
  4811. if DoJumpOptimizations(hp1, TempBool) or
  4812. not TempBool then
  4813. begin
  4814. Result := True;
  4815. if Assigned(hp1) then
  4816. begin
  4817. if (hp1.typ in [ait_align]) then
  4818. SkipAligns(hp1, hp1);
  4819. { CollapseZeroDistJump will be set to the label after the
  4820. jump if it optimises, whether or not it's live or dead }
  4821. if (hp1.typ in [ait_label]) and
  4822. not (tai_label(hp1).labsym.is_used) then
  4823. GetNextInstruction(hp1, hp1);
  4824. end;
  4825. TransferUsedRegs(TmpUsedRegs);
  4826. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4827. if not Assigned(hp1) or
  4828. (
  4829. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4830. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4831. ) then
  4832. begin
  4833. { No more conditional jumps; conditional statement is no longer required }
  4834. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4835. RemoveCurrentP(p);
  4836. end;
  4837. Exit;
  4838. end;
  4839. end;
  4840. { Search for:
  4841. test $x,(reg/ref)
  4842. jne @lbl1
  4843. test $y,(reg/ref) (same register or reference)
  4844. jne @lbl1
  4845. Change to:
  4846. test $(x or y),(reg/ref)
  4847. jne @lbl1
  4848. (Note, this doesn't work with je instead of jne)
  4849. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4850. Also search for:
  4851. test $x,(reg/ref)
  4852. je @lbl1
  4853. ...
  4854. test $y,(reg/ref)
  4855. je/jne @lbl2
  4856. If (x or y) = x, then the second jump is deterministic
  4857. }
  4858. if (
  4859. (
  4860. (taicpu(p).oper[0]^.typ = top_const) or
  4861. (
  4862. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4863. (taicpu(p).oper[0]^.typ = top_reg) and
  4864. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4865. )
  4866. ) and
  4867. MatchInstruction(hp1, A_JCC, [])
  4868. ) then
  4869. begin
  4870. if (taicpu(p).oper[0]^.typ = top_reg) and
  4871. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4872. FirstValue := -1
  4873. else
  4874. FirstValue := taicpu(p).oper[0]^.val;
  4875. { If we have several test/jne's in a row, it might be the case that
  4876. the second label doesn't go to the same location, but the one
  4877. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4878. so accommodate for this with a while loop.
  4879. }
  4880. hp1_last := hp1;
  4881. while (
  4882. (
  4883. (taicpu(p).oper[1]^.typ = top_reg) and
  4884. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4885. ) or GetNextInstruction(hp1_last, p_dist)
  4886. ) and (p_dist.typ = ait_instruction) do
  4887. begin
  4888. if (
  4889. (
  4890. (taicpu(p_dist).opcode = A_TEST) and
  4891. (
  4892. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4893. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4894. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4895. )
  4896. ) or
  4897. (
  4898. { cmp 0,%reg = test %reg,%reg }
  4899. (taicpu(p_dist).opcode = A_CMP) and
  4900. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4901. )
  4902. ) and
  4903. { Make sure the destination operands are actually the same }
  4904. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4905. GetNextInstruction(p_dist, hp1_dist) and
  4906. MatchInstruction(hp1_dist, A_JCC, []) then
  4907. begin
  4908. if
  4909. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4910. (
  4911. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4912. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4913. ) then
  4914. SecondValue := -1
  4915. else
  4916. SecondValue := taicpu(p_dist).oper[0]^.val;
  4917. { If both of the TEST constants are identical, delete the
  4918. second TEST that is unnecessary (be careful though, just
  4919. in case the flags are modified in between) }
  4920. if (FirstValue = SecondValue) then
  4921. begin
  4922. { We have to check the entire range }
  4923. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4924. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4925. begin
  4926. { Since the second jump's condition is a subset of the first, we
  4927. know it will never branch because the first jump dominates it.
  4928. Get it out of the way now rather than wait for the jump
  4929. optimisations for a speed boost. }
  4930. if IsJumpToLabel(taicpu(hp1_dist)) then
  4931. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4932. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4933. RemoveInstruction(hp1_dist);
  4934. Result := True;
  4935. end
  4936. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4937. begin
  4938. { If the inverse of the first condition is a subset of the second,
  4939. the second one will definitely branch if the first one doesn't }
  4940. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4941. { We can remove the TEST instruction too }
  4942. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4943. RemoveInstruction(p_dist);
  4944. MakeUnconditional(taicpu(hp1_dist));
  4945. RemoveDeadCodeAfterJump(hp1_dist);
  4946. { Since the jump is now unconditional, we can't
  4947. continue any further with this particular
  4948. optimisation. The original TEST is still intact
  4949. though, so there might be something else we can
  4950. do }
  4951. Include(OptsToCheck, aoc_ForceNewIteration);
  4952. Break;
  4953. end;
  4954. if Result or
  4955. { If a jump wasn't removed or made unconditional, only
  4956. remove the identical TEST instruction if the flags
  4957. weren't modified }
  4958. TempBool then
  4959. begin
  4960. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4961. RemoveInstruction(p_dist);
  4962. { If the jump was removed or made unconditional, we
  4963. don't need to allocate NR_DEFAULTFLAGS over the
  4964. entire range }
  4965. if not Result then
  4966. begin
  4967. { Mark the flags as 'in use' over the entire range }
  4968. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4969. { Speed gain - continue search from the Jcc instruction }
  4970. hp1_last := hp1_dist;
  4971. { Only the TEST instruction was removed, and the
  4972. original was unchanged, so we can safely do
  4973. another iteration of the while loop }
  4974. Include(OptsToCheck, aoc_ForceNewIteration);
  4975. Continue;
  4976. end;
  4977. Exit;
  4978. end;
  4979. end;
  4980. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4981. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4982. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4983. then the second jump will never branch, so it can also be
  4984. removed regardless of where it goes }
  4985. (
  4986. (FirstValue = -1) or
  4987. (SecondValue = -1) or
  4988. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4989. ) and
  4990. (
  4991. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  4992. { Always adjacent under -O2 and under }
  4993. not(cs_opt_level3 in current_settings.optimizerswitches) or
  4994. (
  4995. GetNextInstruction(hp1, hp1_last) and
  4996. (hp1_last = p_dist)
  4997. )
  4998. ) then
  4999. begin
  5000. { Same jump location... can be a register since nothing's changed }
  5001. { If any of the entries are equivalent to test %reg,%reg, then the
  5002. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5003. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5004. if IsJumpToLabel(taicpu(hp1_dist)) then
  5005. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5006. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5007. RemoveInstruction(hp1_dist);
  5008. { Only remove the second test if no jumps or other conditional instructions follow }
  5009. TransferUsedRegs(TmpUsedRegs);
  5010. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5011. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5012. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  5013. RemoveInstruction(p_dist);
  5014. Result := True;
  5015. Exit;
  5016. end;
  5017. end;
  5018. if { If -O2 and under, it may stop on any old instruction }
  5019. (cs_opt_level3 in current_settings.optimizerswitches) and
  5020. (taicpu(p).oper[1]^.typ = top_reg) and
  5021. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5022. begin
  5023. hp1_last := p_dist;
  5024. Continue;
  5025. end;
  5026. Break;
  5027. end;
  5028. end;
  5029. { Search for:
  5030. test %reg,%reg
  5031. j(c1) @lbl1
  5032. ...
  5033. @lbl:
  5034. test %reg,%reg (same register)
  5035. j(c2) @lbl2
  5036. If c2 is a subset of c1, change to:
  5037. test %reg,%reg
  5038. j(c1) @lbl2
  5039. (@lbl1 may become a dead label as a result)
  5040. }
  5041. if (taicpu(p).oper[1]^.typ = top_reg) and
  5042. (taicpu(p).oper[0]^.typ = top_reg) and
  5043. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5044. MatchInstruction(hp1, A_JCC, []) and
  5045. IsJumpToLabel(taicpu(hp1)) then
  5046. begin
  5047. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5048. p_label := nil;
  5049. if Assigned(JumpLabel) then
  5050. p_label := getlabelwithsym(JumpLabel);
  5051. if Assigned(p_label) and
  5052. GetNextInstruction(p_label, p_dist) and
  5053. MatchInstruction(p_dist, A_TEST, []) and
  5054. { It's fine if the second test uses smaller sub-registers }
  5055. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5056. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5057. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5058. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5059. GetNextInstruction(p_dist, hp1_dist) and
  5060. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5061. begin
  5062. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5063. if JumpLabel = JumpLabel_dist then
  5064. { This is an infinite loop }
  5065. Exit;
  5066. { Best optimisation when the first condition is a subset (or equal) of the second }
  5067. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5068. begin
  5069. { Any registers used here will already be allocated }
  5070. if Assigned(JumpLabel) then
  5071. JumpLabel.DecRefs;
  5072. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5073. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5074. Result := True;
  5075. Exit;
  5076. end;
  5077. end;
  5078. end;
  5079. end;
  5080. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5081. var
  5082. hp1, hp2: tai;
  5083. ActiveReg: TRegister;
  5084. OldOffset: asizeint;
  5085. ThisConst: TCGInt;
  5086. function RegDeallocated: Boolean;
  5087. begin
  5088. TransferUsedRegs(TmpUsedRegs);
  5089. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5090. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5091. end;
  5092. begin
  5093. result:=false;
  5094. hp1 := nil;
  5095. { replace
  5096. addX const,%reg1
  5097. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5098. dealloc %reg1
  5099. by
  5100. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5101. }
  5102. if MatchOpType(taicpu(p),top_const,top_reg) then
  5103. begin
  5104. ActiveReg := taicpu(p).oper[1]^.reg;
  5105. { Ensures the entire register was updated }
  5106. if (taicpu(p).opsize >= S_L) and
  5107. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5108. MatchInstruction(hp1,A_LEA,[]) and
  5109. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5110. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5111. (
  5112. { Cover the case where the register in the reference is also the destination register }
  5113. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5114. (
  5115. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5116. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5117. RegDeallocated
  5118. )
  5119. ) then
  5120. begin
  5121. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5122. {$push}
  5123. {$R-}{$Q-}
  5124. { Explicitly disable overflow checking for these offset calculation
  5125. as those do not matter for the final result }
  5126. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5127. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5128. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5129. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5130. {$pop}
  5131. {$ifdef x86_64}
  5132. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5133. begin
  5134. { Overflow; abort }
  5135. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5136. end
  5137. else
  5138. {$endif x86_64}
  5139. begin
  5140. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5141. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5142. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5143. RemoveCurrentP(p, hp1)
  5144. else
  5145. RemoveCurrentP(p);
  5146. result:=true;
  5147. Exit;
  5148. end;
  5149. end;
  5150. if (
  5151. { Save calling GetNextInstructionUsingReg again }
  5152. Assigned(hp1) or
  5153. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5154. ) and
  5155. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5156. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5157. begin
  5158. if taicpu(hp1).oper[0]^.typ = top_const then
  5159. begin
  5160. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5161. if taicpu(hp1).opcode = A_ADD then
  5162. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5163. else
  5164. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5165. Result := True;
  5166. { Handle any overflows }
  5167. case taicpu(p).opsize of
  5168. S_B:
  5169. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5170. S_W:
  5171. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5172. S_L:
  5173. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5174. {$ifdef x86_64}
  5175. S_Q:
  5176. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5177. { Overflow; abort }
  5178. Result := False
  5179. else
  5180. taicpu(p).oper[0]^.val := ThisConst;
  5181. {$endif x86_64}
  5182. else
  5183. InternalError(2021102610);
  5184. end;
  5185. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5186. if Result then
  5187. begin
  5188. if (taicpu(p).oper[0]^.val < 0) and
  5189. (
  5190. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5191. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5192. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5193. ) then
  5194. begin
  5195. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5196. taicpu(p).opcode := A_SUB;
  5197. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5198. end
  5199. else
  5200. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5201. RemoveInstruction(hp1);
  5202. end;
  5203. end
  5204. else
  5205. begin
  5206. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5207. TransferUsedRegs(TmpUsedRegs);
  5208. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5209. hp2 := p;
  5210. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5211. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5212. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5213. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5214. begin
  5215. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5216. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5217. Asml.Remove(p);
  5218. Asml.InsertAfter(p, hp1);
  5219. p := hp1;
  5220. Result := True;
  5221. Exit;
  5222. end;
  5223. end;
  5224. end;
  5225. if DoArithCombineOpt(p) then
  5226. Result:=true;
  5227. end;
  5228. end;
  5229. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5230. var
  5231. hp1, hp2: tai;
  5232. ref: Integer;
  5233. saveref: treference;
  5234. offsetcalc: Int64;
  5235. TempReg: TRegister;
  5236. Multiple: TCGInt;
  5237. Adjacent, IntermediateRegDiscarded: Boolean;
  5238. begin
  5239. Result:=false;
  5240. { play save and throw an error if LEA uses a seg register prefix,
  5241. this is most likely an error somewhere else }
  5242. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5243. internalerror(2022022001);
  5244. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5245. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5246. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5247. (
  5248. { do not mess with leas accessing the stack pointer
  5249. unless it's a null operation }
  5250. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5251. (
  5252. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5253. (taicpu(p).oper[0]^.ref^.offset = 0)
  5254. )
  5255. ) and
  5256. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5257. begin
  5258. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5259. begin
  5260. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5261. begin
  5262. taicpu(p).opcode := A_MOV;
  5263. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5264. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5265. end
  5266. else
  5267. begin
  5268. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5269. RemoveCurrentP(p);
  5270. end;
  5271. Result:=true;
  5272. exit;
  5273. end
  5274. else if (
  5275. { continue to use lea to adjust the stack pointer,
  5276. it is the recommended way, but only if not optimizing for size }
  5277. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5278. (cs_opt_size in current_settings.optimizerswitches)
  5279. ) and
  5280. { If the flags register is in use, don't change the instruction
  5281. to an ADD otherwise this will scramble the flags. [Kit] }
  5282. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5283. ConvertLEA(taicpu(p)) then
  5284. begin
  5285. Result:=true;
  5286. exit;
  5287. end;
  5288. end;
  5289. { Don't optimise if the stack or frame pointer is the destination register }
  5290. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5291. Exit;
  5292. if GetNextInstruction(p,hp1) and
  5293. (hp1.typ=ait_instruction) then
  5294. begin
  5295. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5296. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5297. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5298. begin
  5299. TransferUsedRegs(TmpUsedRegs);
  5300. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5301. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5302. begin
  5303. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5304. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5305. RemoveInstruction(hp1);
  5306. result:=true;
  5307. exit;
  5308. end;
  5309. end;
  5310. { changes
  5311. lea <ref1>, reg1
  5312. <op> ...,<ref. with reg1>,...
  5313. to
  5314. <op> ...,<ref1>,... }
  5315. { find a reference which uses reg1 }
  5316. 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
  5317. ref:=0
  5318. 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
  5319. ref:=1
  5320. else
  5321. ref:=-1;
  5322. if (ref<>-1) and
  5323. { reg1 must be either the base or the index }
  5324. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5325. begin
  5326. { reg1 can be removed from the reference }
  5327. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5328. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5329. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5330. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5331. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5332. else
  5333. Internalerror(2019111201);
  5334. { check if the can insert all data of the lea into the second instruction }
  5335. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5336. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5337. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5338. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5339. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5340. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5341. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5342. {$ifdef x86_64}
  5343. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5344. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5345. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5346. )
  5347. {$endif x86_64}
  5348. then
  5349. begin
  5350. { reg1 might not used by the second instruction after it is remove from the reference }
  5351. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5352. begin
  5353. TransferUsedRegs(TmpUsedRegs);
  5354. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5355. { reg1 is not updated so it might not be used afterwards }
  5356. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5357. begin
  5358. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5359. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5360. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5361. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5362. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5363. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5364. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5365. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5366. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5367. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5368. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5369. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5370. RemoveCurrentP(p, hp1);
  5371. result:=true;
  5372. exit;
  5373. end
  5374. end;
  5375. end;
  5376. { recover }
  5377. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5378. end;
  5379. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5380. if Adjacent or
  5381. { Check further ahead (up to 2 instructions ahead for -O2) }
  5382. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5383. begin
  5384. { Check common LEA/LEA conditions }
  5385. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5386. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5387. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5388. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5389. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5390. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5391. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5392. (
  5393. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5394. calling it (since it calls GetNextInstruction) }
  5395. Adjacent or
  5396. (
  5397. (
  5398. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5399. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5400. ) and (
  5401. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5402. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5403. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5404. )
  5405. )
  5406. ) then
  5407. begin
  5408. TransferUsedRegs(TmpUsedRegs);
  5409. hp2 := p;
  5410. repeat
  5411. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5412. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5413. IntermediateRegDiscarded :=
  5414. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5415. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5416. { changes
  5417. lea offset1(regX,scale), reg1
  5418. lea offset2(reg1,reg1), reg2
  5419. to
  5420. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5421. and
  5422. lea offset1(regX,scale1), reg1
  5423. lea offset2(reg1,scale2), reg2
  5424. to
  5425. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5426. and
  5427. lea offset1(regX,scale1), reg1
  5428. lea offset2(reg3,reg1,scale2), reg2
  5429. to
  5430. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5431. ... so long as the final scale does not exceed 8
  5432. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5433. }
  5434. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5435. (
  5436. { Don't optimise if size is a concern and the intermediate register remains in use }
  5437. IntermediateRegDiscarded or
  5438. not (cs_opt_size in current_settings.optimizerswitches)
  5439. ) and
  5440. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5441. (
  5442. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5443. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5444. ) and (
  5445. (
  5446. { lea (reg1,scale2), reg2 variant }
  5447. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5448. (
  5449. Adjacent or
  5450. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5451. ) and
  5452. (
  5453. (
  5454. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5455. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5456. ) or (
  5457. { lea (regX,regX), reg1 variant }
  5458. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5459. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5460. )
  5461. )
  5462. ) or (
  5463. { lea (reg1,reg1), reg1 variant }
  5464. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5465. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5466. )
  5467. ) then
  5468. begin
  5469. { Make everything homogeneous to make calculations easier }
  5470. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5471. begin
  5472. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5473. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5474. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5475. else
  5476. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5477. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5478. end;
  5479. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5480. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5481. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5482. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5483. begin
  5484. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5485. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5486. begin
  5487. { Put the register to change in the index register }
  5488. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5489. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5490. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5491. end;
  5492. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5493. begin
  5494. { Just to prevent miscalculations }
  5495. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5496. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5497. else
  5498. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5499. end
  5500. else
  5501. begin
  5502. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5503. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5504. end;
  5505. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5506. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5507. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5508. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5509. if IntermediateRegDiscarded then
  5510. begin
  5511. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5512. RemoveCurrentP(p);
  5513. end
  5514. else
  5515. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5516. result:=true;
  5517. exit;
  5518. end;
  5519. end;
  5520. { changes
  5521. lea offset1(regX), reg1
  5522. lea offset2(reg1), reg2
  5523. to
  5524. lea offset1+offset2(regX), reg2 }
  5525. if (
  5526. { Don't optimise if size is a concern and the intermediate register remains in use }
  5527. IntermediateRegDiscarded or
  5528. not (cs_opt_size in current_settings.optimizerswitches)
  5529. ) and
  5530. (
  5531. (
  5532. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5533. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5534. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5535. ) or (
  5536. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5537. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5538. (
  5539. (
  5540. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5541. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5542. ) or (
  5543. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5544. (
  5545. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5546. (
  5547. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5548. (
  5549. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5550. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5551. )
  5552. )
  5553. )
  5554. )
  5555. )
  5556. )
  5557. ) then
  5558. begin
  5559. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5560. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5561. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5562. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5563. begin
  5564. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5565. begin
  5566. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5567. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5568. { if the register is used as index and base, we have to increase for base as well
  5569. and adapt base }
  5570. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5571. begin
  5572. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5573. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5574. end;
  5575. end
  5576. else
  5577. begin
  5578. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5579. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5580. end;
  5581. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5582. begin
  5583. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5584. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5585. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5586. end;
  5587. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5588. if IntermediateRegDiscarded then
  5589. begin
  5590. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5591. RemoveCurrentP(p);
  5592. end
  5593. else
  5594. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5595. result:=true;
  5596. exit;
  5597. end;
  5598. end;
  5599. end;
  5600. { Change:
  5601. leal/q $x(%reg1),%reg2
  5602. ...
  5603. shll/q $y,%reg2
  5604. To:
  5605. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5606. }
  5607. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5608. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5609. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5610. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5611. (taicpu(hp1).oper[0]^.val <= 3) then
  5612. begin
  5613. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5614. TransferUsedRegs(TmpUsedRegs);
  5615. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5616. if
  5617. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5618. (this works even if scalefactor is zero) }
  5619. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5620. { Ensure offset doesn't go out of bounds }
  5621. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5622. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5623. (
  5624. (
  5625. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5626. (
  5627. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5628. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5629. (
  5630. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5631. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5632. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5633. )
  5634. )
  5635. ) or (
  5636. (
  5637. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5638. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5639. ) and
  5640. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5641. )
  5642. ) then
  5643. begin
  5644. repeat
  5645. with taicpu(p).oper[0]^.ref^ do
  5646. begin
  5647. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5648. if index = base then
  5649. begin
  5650. if Multiple > 4 then
  5651. { Optimisation will no longer work because resultant
  5652. scale factor will exceed 8 }
  5653. Break;
  5654. base := NR_NO;
  5655. scalefactor := 2;
  5656. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5657. end
  5658. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5659. begin
  5660. { Scale factor only works on the index register }
  5661. index := base;
  5662. base := NR_NO;
  5663. end;
  5664. { For safety }
  5665. if scalefactor <= 1 then
  5666. begin
  5667. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5668. scalefactor := Multiple;
  5669. end
  5670. else
  5671. begin
  5672. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5673. scalefactor := scalefactor * Multiple;
  5674. end;
  5675. offset := offset * Multiple;
  5676. end;
  5677. RemoveInstruction(hp1);
  5678. Result := True;
  5679. Exit;
  5680. { This repeat..until loop exists for the benefit of Break }
  5681. until True;
  5682. end;
  5683. end;
  5684. end;
  5685. end;
  5686. end;
  5687. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5688. var
  5689. hp1 : tai;
  5690. SubInstr: Boolean;
  5691. ThisConst: TCGInt;
  5692. const
  5693. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5694. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5695. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5696. begin
  5697. Result := False;
  5698. if taicpu(p).oper[0]^.typ <> top_const then
  5699. { Should have been confirmed before calling }
  5700. InternalError(2021102601);
  5701. SubInstr := (taicpu(p).opcode = A_SUB);
  5702. if GetLastInstruction(p, hp1) and
  5703. (hp1.typ = ait_instruction) and
  5704. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5705. begin
  5706. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5707. { Bad size }
  5708. InternalError(2022042001);
  5709. case taicpu(hp1).opcode Of
  5710. A_INC:
  5711. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5712. begin
  5713. if SubInstr then
  5714. ThisConst := taicpu(p).oper[0]^.val - 1
  5715. else
  5716. ThisConst := taicpu(p).oper[0]^.val + 1;
  5717. end
  5718. else
  5719. Exit;
  5720. A_DEC:
  5721. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5722. begin
  5723. if SubInstr then
  5724. ThisConst := taicpu(p).oper[0]^.val + 1
  5725. else
  5726. ThisConst := taicpu(p).oper[0]^.val - 1;
  5727. end
  5728. else
  5729. Exit;
  5730. A_SUB:
  5731. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5732. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5733. begin
  5734. if SubInstr then
  5735. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5736. else
  5737. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5738. end
  5739. else
  5740. Exit;
  5741. A_ADD:
  5742. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5743. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5744. begin
  5745. if SubInstr then
  5746. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5747. else
  5748. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5749. end
  5750. else
  5751. Exit;
  5752. else
  5753. Exit;
  5754. end;
  5755. { Check that the values are in range }
  5756. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5757. { Overflow; abort }
  5758. Exit;
  5759. if (ThisConst = 0) then
  5760. begin
  5761. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5762. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5763. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5764. RemoveInstruction(hp1);
  5765. hp1 := tai(p.next);
  5766. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5767. if not GetLastInstruction(hp1, p) then
  5768. p := hp1;
  5769. end
  5770. else
  5771. begin
  5772. if taicpu(hp1).opercnt=1 then
  5773. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5774. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5775. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5776. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5777. else
  5778. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5779. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5780. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5781. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5782. RemoveInstruction(hp1);
  5783. taicpu(p).loadconst(0, ThisConst);
  5784. end;
  5785. Result := True;
  5786. end;
  5787. end;
  5788. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5789. begin
  5790. Result := False;
  5791. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5792. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5793. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5794. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5795. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5796. (
  5797. (
  5798. (taicpu(hp1).opcode = A_TEST)
  5799. ) or (
  5800. (taicpu(hp1).opcode = A_CMP) and
  5801. { A sanity check more than anything }
  5802. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5803. )
  5804. ) then
  5805. begin
  5806. { change
  5807. mov mem, %reg
  5808. ...
  5809. cmp/test x, %reg / test %reg,%reg
  5810. (reg deallocated)
  5811. to
  5812. cmp/test x, mem / cmp 0, mem
  5813. }
  5814. TransferUsedRegs(TmpUsedRegs);
  5815. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5816. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5817. begin
  5818. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5819. if (taicpu(hp1).opcode = A_TEST) and
  5820. (
  5821. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5822. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5823. ) then
  5824. begin
  5825. taicpu(hp1).opcode := A_CMP;
  5826. taicpu(hp1).loadconst(0, 0);
  5827. end;
  5828. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5829. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5830. RemoveCurrentP(p);
  5831. if (p <> hp1) then
  5832. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5833. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5834. { Make sure the flags are allocated across the CMP instruction }
  5835. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5836. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5837. Result := True;
  5838. Exit;
  5839. end;
  5840. end;
  5841. end;
  5842. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5843. var
  5844. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5845. ThisReg, SecondReg: TRegister;
  5846. JumpLoc: TAsmLabel;
  5847. NewSize: TOpSize;
  5848. begin
  5849. Result := False;
  5850. {
  5851. Convert:
  5852. j<c> .L1
  5853. .L2:
  5854. mov 1,reg
  5855. jmp .L3 (or ret, although it might not be a RET yet)
  5856. .L1:
  5857. mov 0,reg
  5858. jmp .L3 (or ret)
  5859. ( As long as .L3 <> .L1 or .L2)
  5860. To:
  5861. mov 0,reg
  5862. set<not(c)> reg
  5863. jmp .L3 (or ret)
  5864. .L2:
  5865. mov 1,reg
  5866. jmp .L3 (or ret)
  5867. .L1:
  5868. mov 0,reg
  5869. jmp .L3 (or ret)
  5870. }
  5871. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5872. Exit;
  5873. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5874. if GetNextInstruction(hp_label, hp2) and
  5875. MatchInstruction(hp2,A_MOV,[]) and
  5876. (taicpu(hp2).oper[0]^.typ = top_const) and
  5877. (
  5878. (
  5879. (taicpu(hp2).oper[1]^.typ = top_reg)
  5880. {$ifdef i386}
  5881. { Under i386, ESI, EDI, EBP and ESP
  5882. don't have an 8-bit representation }
  5883. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5884. {$endif i386}
  5885. ) or (
  5886. {$ifdef i386}
  5887. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5888. {$endif i386}
  5889. (taicpu(hp2).opsize = S_B)
  5890. )
  5891. ) and
  5892. GetNextInstruction(hp2, hp3) and
  5893. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5894. (
  5895. (taicpu(hp3).opcode=A_RET) or
  5896. (
  5897. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5898. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5899. )
  5900. ) and
  5901. GetNextInstruction(hp3, hp4) and
  5902. SkipAligns(hp4, hp4) and
  5903. (hp4.typ=ait_label) and
  5904. (tai_label(hp4).labsym=JumpLoc) and
  5905. (
  5906. not (cs_opt_size in current_settings.optimizerswitches) or
  5907. { If the initial jump is the label's only reference, then it will
  5908. become a dead label if the other conditions are met and hence
  5909. remove at least 2 instructions, including a jump }
  5910. (JumpLoc.getrefs = 1)
  5911. ) and
  5912. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5913. that will be optimised out }
  5914. GetNextInstruction(hp4, hp5) and
  5915. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5916. (taicpu(hp5).oper[0]^.typ = top_const) and
  5917. (
  5918. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5919. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5920. ) and
  5921. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5922. GetNextInstruction(hp5,hp6) and
  5923. (
  5924. (hp6.typ<>ait_label) or
  5925. SkipLabels(hp6, hp6)
  5926. ) and
  5927. (hp6.typ=ait_instruction) then
  5928. begin
  5929. { First, let's look at the two jumps that are hp3 and hp6 }
  5930. if not
  5931. (
  5932. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5933. (
  5934. (taicpu(hp6).opcode=A_RET) or
  5935. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5936. )
  5937. ) then
  5938. { If condition is False, then the JMP/RET instructions matched conventionally }
  5939. begin
  5940. { See if one of the jumps can be instantly converted into a RET }
  5941. if (taicpu(hp3).opcode=A_JMP) then
  5942. begin
  5943. { Reuse hp5 }
  5944. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5945. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5946. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5947. Exit;
  5948. if MatchInstruction(hp5, A_RET, []) then
  5949. begin
  5950. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5951. ConvertJumpToRET(hp3, hp5);
  5952. Result := True;
  5953. end
  5954. else
  5955. Exit;
  5956. end;
  5957. if (taicpu(hp6).opcode=A_JMP) then
  5958. begin
  5959. { Reuse hp5 }
  5960. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5961. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5962. Exit;
  5963. if MatchInstruction(hp5, A_RET, []) then
  5964. begin
  5965. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5966. ConvertJumpToRET(hp6, hp5);
  5967. Result := True;
  5968. end
  5969. else
  5970. Exit;
  5971. end;
  5972. if not
  5973. (
  5974. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5975. (
  5976. (taicpu(hp6).opcode=A_RET) or
  5977. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5978. )
  5979. ) then
  5980. { Still doesn't match }
  5981. Exit;
  5982. end;
  5983. if (taicpu(hp2).oper[0]^.val = 1) then
  5984. begin
  5985. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5986. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5987. end
  5988. else
  5989. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5990. if taicpu(hp2).opsize=S_B then
  5991. begin
  5992. if taicpu(hp2).oper[1]^.typ = top_reg then
  5993. begin
  5994. SecondReg := taicpu(hp2).oper[1]^.reg;
  5995. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5996. end
  5997. else
  5998. begin
  5999. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6000. SecondReg := NR_NO;
  6001. end;
  6002. hp_pos := p;
  6003. hp_allocstart := hp4;
  6004. end
  6005. else
  6006. begin
  6007. { Will be a register because the size can't be S_B otherwise }
  6008. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6009. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6010. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6011. if (cs_opt_size in current_settings.optimizerswitches) then
  6012. begin
  6013. { Favour using MOVZX when optimising for size }
  6014. case taicpu(hp2).opsize of
  6015. S_W:
  6016. NewSize := S_BW;
  6017. S_L:
  6018. NewSize := S_BL;
  6019. {$ifdef x86_64}
  6020. S_Q:
  6021. begin
  6022. NewSize := S_BL;
  6023. { Will implicitly zero-extend to 64-bit }
  6024. setsubreg(SecondReg, R_SUBD);
  6025. end;
  6026. {$endif x86_64}
  6027. else
  6028. InternalError(2022101301);
  6029. end;
  6030. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6031. { Inserting it right before p will guarantee that the flags are also tracked }
  6032. Asml.InsertBefore(hp5, p);
  6033. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6034. hp_pos := hp5;
  6035. hp_allocstart := hp4;
  6036. end
  6037. else
  6038. begin
  6039. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6040. { Inserting it right before p will guarantee that the flags are also tracked }
  6041. Asml.InsertBefore(hp5, p);
  6042. hp_pos := p;
  6043. hp_allocstart := hp5;
  6044. end;
  6045. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6046. end;
  6047. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6048. taicpu(hp4).condition := taicpu(p).condition;
  6049. asml.InsertBefore(hp4, hp_pos);
  6050. if taicpu(hp3).is_jmp then
  6051. begin
  6052. JumpLoc.decrefs;
  6053. MakeUnconditional(taicpu(p));
  6054. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6055. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6056. end
  6057. else
  6058. ConvertJumpToRET(p, hp3);
  6059. if SecondReg <> NR_NO then
  6060. { Ensure the destination register is allocated over this region }
  6061. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6062. if (JumpLoc.getrefs = 0) then
  6063. RemoveDeadCodeAfterJump(hp3);
  6064. Result:=true;
  6065. exit;
  6066. end;
  6067. end;
  6068. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6069. var
  6070. hp1, hp2: tai;
  6071. ActiveReg: TRegister;
  6072. OldOffset: asizeint;
  6073. ThisConst: TCGInt;
  6074. function RegDeallocated: Boolean;
  6075. begin
  6076. TransferUsedRegs(TmpUsedRegs);
  6077. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6078. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6079. end;
  6080. begin
  6081. Result:=false;
  6082. hp1 := nil;
  6083. { replace
  6084. subX const,%reg1
  6085. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6086. dealloc %reg1
  6087. by
  6088. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6089. }
  6090. if MatchOpType(taicpu(p),top_const,top_reg) then
  6091. begin
  6092. ActiveReg := taicpu(p).oper[1]^.reg;
  6093. { Ensures the entire register was updated }
  6094. if (taicpu(p).opsize >= S_L) and
  6095. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6096. MatchInstruction(hp1,A_LEA,[]) and
  6097. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6098. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6099. (
  6100. { Cover the case where the register in the reference is also the destination register }
  6101. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6102. (
  6103. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6104. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6105. RegDeallocated
  6106. )
  6107. ) then
  6108. begin
  6109. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6110. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6111. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6112. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6113. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6114. {$ifdef x86_64}
  6115. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6116. begin
  6117. { Overflow; abort }
  6118. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6119. end
  6120. else
  6121. {$endif x86_64}
  6122. begin
  6123. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6124. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6125. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6126. RemoveCurrentP(p, hp1)
  6127. else
  6128. RemoveCurrentP(p);
  6129. result:=true;
  6130. Exit;
  6131. end;
  6132. end;
  6133. if (
  6134. { Save calling GetNextInstructionUsingReg again }
  6135. Assigned(hp1) or
  6136. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6137. ) and
  6138. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6139. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6140. begin
  6141. if taicpu(hp1).oper[0]^.typ = top_const then
  6142. begin
  6143. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6144. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6145. Result := True;
  6146. { Handle any overflows }
  6147. case taicpu(p).opsize of
  6148. S_B:
  6149. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6150. S_W:
  6151. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6152. S_L:
  6153. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6154. {$ifdef x86_64}
  6155. S_Q:
  6156. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6157. { Overflow; abort }
  6158. Result := False
  6159. else
  6160. taicpu(p).oper[0]^.val := ThisConst;
  6161. {$endif x86_64}
  6162. else
  6163. InternalError(2021102611);
  6164. end;
  6165. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6166. if Result then
  6167. begin
  6168. if (taicpu(p).oper[0]^.val < 0) and
  6169. (
  6170. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6171. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6172. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6173. ) then
  6174. begin
  6175. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6176. taicpu(p).opcode := A_SUB;
  6177. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6178. end
  6179. else
  6180. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6181. RemoveInstruction(hp1);
  6182. end;
  6183. end
  6184. else
  6185. begin
  6186. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6187. TransferUsedRegs(TmpUsedRegs);
  6188. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6189. hp2 := p;
  6190. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6191. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6192. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6193. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6194. begin
  6195. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6196. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6197. Asml.Remove(p);
  6198. Asml.InsertAfter(p, hp1);
  6199. p := hp1;
  6200. Result := True;
  6201. Exit;
  6202. end;
  6203. end;
  6204. end;
  6205. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6206. { * change "sub/add const1, reg" or "dec reg" followed by
  6207. "sub const2, reg" to one "sub ..., reg" }
  6208. {$ifdef i386}
  6209. if (taicpu(p).oper[0]^.val = 2) and
  6210. (ActiveReg = NR_ESP) and
  6211. { Don't do the sub/push optimization if the sub }
  6212. { comes from setting up the stack frame (JM) }
  6213. (not(GetLastInstruction(p,hp1)) or
  6214. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6215. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6216. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6217. begin
  6218. hp1 := tai(p.next);
  6219. while Assigned(hp1) and
  6220. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6221. not RegReadByInstruction(NR_ESP,hp1) and
  6222. not RegModifiedByInstruction(NR_ESP,hp1) do
  6223. hp1 := tai(hp1.next);
  6224. if Assigned(hp1) and
  6225. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6226. begin
  6227. taicpu(hp1).changeopsize(S_L);
  6228. if taicpu(hp1).oper[0]^.typ=top_reg then
  6229. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6230. hp1 := tai(p.next);
  6231. RemoveCurrentp(p, hp1);
  6232. Result:=true;
  6233. exit;
  6234. end;
  6235. end;
  6236. {$endif i386}
  6237. if DoArithCombineOpt(p) then
  6238. Result:=true;
  6239. end;
  6240. end;
  6241. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6242. var
  6243. TmpBool1,TmpBool2 : Boolean;
  6244. tmpref : treference;
  6245. hp1,hp2: tai;
  6246. mask, shiftval: tcgint;
  6247. begin
  6248. Result:=false;
  6249. { All these optimisations work on "shl/sal const,%reg" }
  6250. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6251. Exit;
  6252. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6253. (taicpu(p).oper[0]^.val <= 3) then
  6254. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6255. begin
  6256. { should we check the next instruction? }
  6257. TmpBool1 := True;
  6258. { have we found an add/sub which could be
  6259. integrated in the lea? }
  6260. TmpBool2 := False;
  6261. reference_reset(tmpref,2,[]);
  6262. TmpRef.index := taicpu(p).oper[1]^.reg;
  6263. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6264. while TmpBool1 and
  6265. GetNextInstruction(p, hp1) and
  6266. (tai(hp1).typ = ait_instruction) and
  6267. ((((taicpu(hp1).opcode = A_ADD) or
  6268. (taicpu(hp1).opcode = A_SUB)) and
  6269. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6270. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6271. (((taicpu(hp1).opcode = A_INC) or
  6272. (taicpu(hp1).opcode = A_DEC)) and
  6273. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6274. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6275. ((taicpu(hp1).opcode = A_LEA) and
  6276. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6277. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6278. (not GetNextInstruction(hp1,hp2) or
  6279. not instrReadsFlags(hp2)) Do
  6280. begin
  6281. TmpBool1 := False;
  6282. if taicpu(hp1).opcode=A_LEA then
  6283. begin
  6284. if (TmpRef.base = NR_NO) and
  6285. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6286. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6287. { Segment register isn't a concern here }
  6288. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6289. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6290. begin
  6291. TmpBool1 := True;
  6292. TmpBool2 := True;
  6293. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6294. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6295. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6296. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6297. RemoveInstruction(hp1);
  6298. end
  6299. end
  6300. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6301. begin
  6302. TmpBool1 := True;
  6303. TmpBool2 := True;
  6304. case taicpu(hp1).opcode of
  6305. A_ADD:
  6306. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6307. A_SUB:
  6308. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6309. else
  6310. internalerror(2019050536);
  6311. end;
  6312. RemoveInstruction(hp1);
  6313. end
  6314. else
  6315. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6316. (((taicpu(hp1).opcode = A_ADD) and
  6317. (TmpRef.base = NR_NO)) or
  6318. (taicpu(hp1).opcode = A_INC) or
  6319. (taicpu(hp1).opcode = A_DEC)) then
  6320. begin
  6321. TmpBool1 := True;
  6322. TmpBool2 := True;
  6323. case taicpu(hp1).opcode of
  6324. A_ADD:
  6325. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6326. A_INC:
  6327. inc(TmpRef.offset);
  6328. A_DEC:
  6329. dec(TmpRef.offset);
  6330. else
  6331. internalerror(2019050535);
  6332. end;
  6333. RemoveInstruction(hp1);
  6334. end;
  6335. end;
  6336. if TmpBool2
  6337. {$ifndef x86_64}
  6338. or
  6339. ((current_settings.optimizecputype < cpu_Pentium2) and
  6340. (taicpu(p).oper[0]^.val <= 3) and
  6341. not(cs_opt_size in current_settings.optimizerswitches))
  6342. {$endif x86_64}
  6343. then
  6344. begin
  6345. if not(TmpBool2) and
  6346. (taicpu(p).oper[0]^.val=1) then
  6347. begin
  6348. taicpu(p).opcode := A_ADD;
  6349. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6350. end
  6351. else
  6352. begin
  6353. taicpu(p).opcode := A_LEA;
  6354. taicpu(p).loadref(0, TmpRef);
  6355. end;
  6356. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6357. Result := True;
  6358. end;
  6359. end
  6360. {$ifndef x86_64}
  6361. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6362. begin
  6363. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6364. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6365. (unlike shl, which is only Tairable in the U pipe) }
  6366. if taicpu(p).oper[0]^.val=1 then
  6367. begin
  6368. taicpu(p).opcode := A_ADD;
  6369. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6370. Result := True;
  6371. end
  6372. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6373. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6374. else if (taicpu(p).opsize = S_L) and
  6375. (taicpu(p).oper[0]^.val<= 3) then
  6376. begin
  6377. reference_reset(tmpref,2,[]);
  6378. TmpRef.index := taicpu(p).oper[1]^.reg;
  6379. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6380. taicpu(p).opcode := A_LEA;
  6381. taicpu(p).loadref(0, TmpRef);
  6382. Result := True;
  6383. end;
  6384. end
  6385. {$endif x86_64}
  6386. else if
  6387. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6388. (
  6389. (
  6390. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6391. SetAndTest(hp1, hp2)
  6392. {$ifdef x86_64}
  6393. ) or
  6394. (
  6395. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6396. GetNextInstruction(hp1, hp2) and
  6397. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6398. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6399. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6400. {$endif x86_64}
  6401. )
  6402. ) and
  6403. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6404. begin
  6405. { Change:
  6406. shl x, %reg1
  6407. mov -(1<<x), %reg2
  6408. and %reg2, %reg1
  6409. Or:
  6410. shl x, %reg1
  6411. and -(1<<x), %reg1
  6412. To just:
  6413. shl x, %reg1
  6414. Since the and operation only zeroes bits that are already zero from the shl operation
  6415. }
  6416. case taicpu(p).oper[0]^.val of
  6417. 8:
  6418. mask:=$FFFFFFFFFFFFFF00;
  6419. 16:
  6420. mask:=$FFFFFFFFFFFF0000;
  6421. 32:
  6422. mask:=$FFFFFFFF00000000;
  6423. 63:
  6424. { Constant pre-calculated to prevent overflow errors with Int64 }
  6425. mask:=$8000000000000000;
  6426. else
  6427. begin
  6428. if taicpu(p).oper[0]^.val >= 64 then
  6429. { Shouldn't happen realistically, since the register
  6430. is guaranteed to be set to zero at this point }
  6431. mask := 0
  6432. else
  6433. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6434. end;
  6435. end;
  6436. if taicpu(hp1).oper[0]^.val = mask then
  6437. begin
  6438. { Everything checks out, perform the optimisation, as long as
  6439. the FLAGS register isn't being used}
  6440. TransferUsedRegs(TmpUsedRegs);
  6441. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6442. {$ifdef x86_64}
  6443. if (hp1 <> hp2) then
  6444. begin
  6445. { "shl/mov/and" version }
  6446. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6447. { Don't do the optimisation if the FLAGS register is in use }
  6448. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6449. begin
  6450. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6451. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6452. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6453. begin
  6454. RemoveInstruction(hp1);
  6455. Result := True;
  6456. end;
  6457. { Only set Result to True if the 'mov' instruction was removed }
  6458. RemoveInstruction(hp2);
  6459. end;
  6460. end
  6461. else
  6462. {$endif x86_64}
  6463. begin
  6464. { "shl/and" version }
  6465. { Don't do the optimisation if the FLAGS register is in use }
  6466. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6467. begin
  6468. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6469. RemoveInstruction(hp1);
  6470. Result := True;
  6471. end;
  6472. end;
  6473. Exit;
  6474. end
  6475. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6476. begin
  6477. { Even if the mask doesn't allow for its removal, we might be
  6478. able to optimise the mask for the "shl/and" version, which
  6479. may permit other peephole optimisations }
  6480. {$ifdef DEBUG_AOPTCPU}
  6481. mask := taicpu(hp1).oper[0]^.val and mask;
  6482. if taicpu(hp1).oper[0]^.val <> mask then
  6483. begin
  6484. DebugMsg(
  6485. SPeepholeOptimization +
  6486. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6487. ' to $' + debug_tostr(mask) +
  6488. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6489. taicpu(hp1).oper[0]^.val := mask;
  6490. end;
  6491. {$else DEBUG_AOPTCPU}
  6492. { If debugging is off, just set the operand even if it's the same }
  6493. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6494. {$endif DEBUG_AOPTCPU}
  6495. end;
  6496. end;
  6497. {
  6498. change
  6499. shl/sal const,reg
  6500. <op> ...(...,reg,1),...
  6501. into
  6502. <op> ...(...,reg,1 shl const),...
  6503. if const in 1..3
  6504. }
  6505. if MatchOpType(taicpu(p), top_const, top_reg) and
  6506. (taicpu(p).oper[0]^.val in [1..3]) and
  6507. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6508. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6509. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6510. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6511. MatchOpType(taicpu(hp1),top_ref))
  6512. ) and
  6513. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6514. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6515. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6516. begin
  6517. TransferUsedRegs(TmpUsedRegs);
  6518. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6519. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6520. begin
  6521. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6522. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6523. RemoveCurrentP(p);
  6524. Result:=true;
  6525. exit;
  6526. end;
  6527. end;
  6528. if MatchOpType(taicpu(p), top_const, top_reg) and
  6529. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6530. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6531. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6532. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6533. begin
  6534. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6535. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6536. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6537. {$ifdef x86_64}
  6538. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6539. {$endif x86_64}
  6540. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6541. begin
  6542. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6543. taicpu(hp1).opcode:=A_MOV;
  6544. taicpu(hp1).oper[0]^.val:=0;
  6545. end
  6546. else
  6547. begin
  6548. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6549. taicpu(hp1).oper[0]^.val:=shiftval;
  6550. end;
  6551. RemoveCurrentP(p);
  6552. Result:=true;
  6553. exit;
  6554. end;
  6555. end;
  6556. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6557. begin
  6558. case shr_size of
  6559. S_B:
  6560. { No valid combinations }
  6561. Result := False;
  6562. S_W:
  6563. Result := (Shift >= 8) and (movz_size = S_BW);
  6564. S_L:
  6565. Result :=
  6566. (Shift >= 24) { Any opsize is valid for this shift } or
  6567. ((Shift >= 16) and (movz_size = S_WL));
  6568. {$ifdef x86_64}
  6569. S_Q:
  6570. Result :=
  6571. (Shift >= 56) { Any opsize is valid for this shift } or
  6572. ((Shift >= 48) and (movz_size = S_WL));
  6573. {$endif x86_64}
  6574. else
  6575. InternalError(2022081510);
  6576. end;
  6577. end;
  6578. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6579. var
  6580. hp1, hp2: tai;
  6581. Shift: TCGInt;
  6582. LimitSize: Topsize;
  6583. DoNotMerge: Boolean;
  6584. begin
  6585. Result := False;
  6586. { All these optimisations work on "shr const,%reg" }
  6587. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6588. Exit;
  6589. DoNotMerge := False;
  6590. Shift := taicpu(p).oper[0]^.val;
  6591. LimitSize := taicpu(p).opsize;
  6592. hp1 := p;
  6593. repeat
  6594. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6595. Exit;
  6596. case taicpu(hp1).opcode of
  6597. A_TEST, A_CMP, A_Jcc:
  6598. { Skip over conditional jumps and relevant comparisons }
  6599. Continue;
  6600. A_MOVZX:
  6601. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6602. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6603. begin
  6604. { Since the original register is being read as is, subsequent
  6605. SHRs must not be merged at this point }
  6606. DoNotMerge := True;
  6607. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6608. begin
  6609. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6610. begin
  6611. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6612. taicpu(hp1).opcode := A_MOV;
  6613. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6614. case taicpu(hp1).opsize of
  6615. S_BW:
  6616. taicpu(hp1).opsize := S_W;
  6617. S_BL, S_WL:
  6618. taicpu(hp1).opsize := S_L;
  6619. else
  6620. InternalError(2022081503);
  6621. end;
  6622. { p itself hasn't changed, so no need to set Result to True }
  6623. Include(OptsToCheck, aoc_ForceNewIteration);
  6624. { See if there's anything afterwards that can be
  6625. optimised, since the input register hasn't changed }
  6626. Continue;
  6627. end;
  6628. { NOTE: If the MOVZX instruction reads and writes the same
  6629. register, defer this to the post-peephole optimisation stage }
  6630. Exit;
  6631. end;
  6632. end;
  6633. A_SHL, A_SAL, A_SHR:
  6634. if (taicpu(hp1).opsize <= LimitSize) and
  6635. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6636. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6637. begin
  6638. { Make sure the sizes don't exceed the register size limit
  6639. (measured by the shift value falling below the limit) }
  6640. if taicpu(hp1).opsize < LimitSize then
  6641. LimitSize := taicpu(hp1).opsize;
  6642. if taicpu(hp1).opcode = A_SHR then
  6643. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6644. else
  6645. begin
  6646. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6647. DoNotMerge := True;
  6648. end;
  6649. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6650. Exit;
  6651. { Since we've established that the combined shift is within
  6652. limits, we can actually combine the adjacent SHR
  6653. instructions even if they're different sizes }
  6654. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6655. begin
  6656. hp2 := tai(hp1.Previous);
  6657. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6658. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6659. RemoveInstruction(hp1);
  6660. hp1 := hp2;
  6661. { Though p has changed, only the constant has, and its
  6662. effects can still be detected on the next iteration of
  6663. the repeat..until loop }
  6664. Include(OptsToCheck, aoc_ForceNewIteration);
  6665. end;
  6666. { Move onto the next instruction }
  6667. Continue;
  6668. end;
  6669. else
  6670. ;
  6671. end;
  6672. Break;
  6673. until False;
  6674. end;
  6675. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6676. var
  6677. CurrentRef: TReference;
  6678. FullReg: TRegister;
  6679. hp1, hp2: tai;
  6680. begin
  6681. Result := False;
  6682. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6683. Exit;
  6684. { We assume you've checked if the operand is actually a reference by
  6685. this point. If it isn't, you'll most likely get an access violation }
  6686. CurrentRef := first_mov.oper[1]^.ref^;
  6687. { Memory must be aligned }
  6688. if (CurrentRef.offset mod 4) <> 0 then
  6689. Exit;
  6690. Inc(CurrentRef.offset);
  6691. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6692. if MatchOperand(second_mov.oper[0]^, 0) and
  6693. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6694. GetNextInstruction(second_mov, hp1) and
  6695. (hp1.typ = ait_instruction) and
  6696. (taicpu(hp1).opcode = A_MOV) and
  6697. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6698. (taicpu(hp1).oper[0]^.val = 0) then
  6699. begin
  6700. Inc(CurrentRef.offset);
  6701. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6702. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6703. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6704. begin
  6705. case taicpu(hp1).opsize of
  6706. S_B:
  6707. if GetNextInstruction(hp1, hp2) and
  6708. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6709. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6710. (taicpu(hp2).oper[0]^.val = 0) then
  6711. begin
  6712. Inc(CurrentRef.offset);
  6713. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6714. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6715. (taicpu(hp2).opsize = S_B) then
  6716. begin
  6717. RemoveInstruction(hp1);
  6718. RemoveInstruction(hp2);
  6719. first_mov.opsize := S_L;
  6720. if first_mov.oper[0]^.typ = top_reg then
  6721. begin
  6722. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6723. { Reuse second_mov as a MOVZX instruction }
  6724. second_mov.opcode := A_MOVZX;
  6725. second_mov.opsize := S_BL;
  6726. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6727. second_mov.loadreg(1, FullReg);
  6728. first_mov.oper[0]^.reg := FullReg;
  6729. asml.Remove(second_mov);
  6730. asml.InsertBefore(second_mov, first_mov);
  6731. end
  6732. else
  6733. { It's a value }
  6734. begin
  6735. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6736. RemoveInstruction(second_mov);
  6737. end;
  6738. Result := True;
  6739. Exit;
  6740. end;
  6741. end;
  6742. S_W:
  6743. begin
  6744. RemoveInstruction(hp1);
  6745. first_mov.opsize := S_L;
  6746. if first_mov.oper[0]^.typ = top_reg then
  6747. begin
  6748. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6749. { Reuse second_mov as a MOVZX instruction }
  6750. second_mov.opcode := A_MOVZX;
  6751. second_mov.opsize := S_BL;
  6752. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6753. second_mov.loadreg(1, FullReg);
  6754. first_mov.oper[0]^.reg := FullReg;
  6755. asml.Remove(second_mov);
  6756. asml.InsertBefore(second_mov, first_mov);
  6757. end
  6758. else
  6759. { It's a value }
  6760. begin
  6761. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6762. RemoveInstruction(second_mov);
  6763. end;
  6764. Result := True;
  6765. Exit;
  6766. end;
  6767. else
  6768. ;
  6769. end;
  6770. end;
  6771. end;
  6772. end;
  6773. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6774. { returns true if a "continue" should be done after this optimization }
  6775. var
  6776. hp1, hp2, hp3: tai;
  6777. begin
  6778. Result := false;
  6779. hp3 := nil;
  6780. if MatchOpType(taicpu(p),top_ref) and
  6781. GetNextInstruction(p, hp1) and
  6782. (hp1.typ = ait_instruction) and
  6783. (((taicpu(hp1).opcode = A_FLD) and
  6784. (taicpu(p).opcode = A_FSTP)) or
  6785. ((taicpu(p).opcode = A_FISTP) and
  6786. (taicpu(hp1).opcode = A_FILD))) and
  6787. MatchOpType(taicpu(hp1),top_ref) and
  6788. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6789. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6790. begin
  6791. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6792. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6793. GetNextInstruction(hp1, hp2) and
  6794. (((hp2.typ = ait_instruction) and
  6795. IsExitCode(hp2) and
  6796. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6797. not(assigned(current_procinfo.procdef.funcretsym) and
  6798. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6799. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6800. { fstp <temp>
  6801. fld <temp>
  6802. <dealloc> <temp>
  6803. }
  6804. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6805. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6806. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6807. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6808. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6809. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6810. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6811. )
  6812. )
  6813. ) then
  6814. begin
  6815. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6816. RemoveInstruction(hp1);
  6817. RemoveCurrentP(p, hp2);
  6818. { first case: exit code }
  6819. if hp2.typ = ait_instruction then
  6820. RemoveLastDeallocForFuncRes(p);
  6821. Result := true;
  6822. end
  6823. else
  6824. { we can do this only in fast math mode as fstp is rounding ...
  6825. ... still disabled as it breaks the compiler and/or rtl }
  6826. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6827. { ... or if another fstp equal to the first one follows }
  6828. GetNextInstruction(hp1,hp2) and
  6829. (hp2.typ = ait_instruction) and
  6830. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6831. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6832. begin
  6833. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6834. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6835. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6836. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6837. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6838. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6839. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6840. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6841. ) then
  6842. begin
  6843. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6844. RemoveCurrentP(p,hp2);
  6845. RemoveInstruction(hp1);
  6846. Result := true;
  6847. end
  6848. else if { fst can't store an extended/comp value }
  6849. (taicpu(p).opsize <> S_FX) and
  6850. (taicpu(p).opsize <> S_IQ) then
  6851. begin
  6852. if (taicpu(p).opcode = A_FSTP) then
  6853. taicpu(p).opcode := A_FST
  6854. else
  6855. taicpu(p).opcode := A_FIST;
  6856. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6857. RemoveInstruction(hp1);
  6858. Result := true;
  6859. end;
  6860. end;
  6861. end;
  6862. end;
  6863. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6864. var
  6865. hp1, hp2, hp3: tai;
  6866. begin
  6867. result:=false;
  6868. if MatchOpType(taicpu(p),top_reg) and
  6869. GetNextInstruction(p, hp1) and
  6870. (hp1.typ = Ait_Instruction) and
  6871. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6872. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6873. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6874. { change to
  6875. fld reg fxxx reg,st
  6876. fxxxp st, st1 (hp1)
  6877. Remark: non commutative operations must be reversed!
  6878. }
  6879. begin
  6880. case taicpu(hp1).opcode Of
  6881. A_FMULP,A_FADDP,
  6882. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6883. begin
  6884. case taicpu(hp1).opcode Of
  6885. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6886. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6887. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6888. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6889. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6890. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6891. else
  6892. internalerror(2019050534);
  6893. end;
  6894. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6895. taicpu(hp1).oper[1]^.reg := NR_ST;
  6896. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6897. RemoveCurrentP(p, hp1);
  6898. Result:=true;
  6899. exit;
  6900. end;
  6901. else
  6902. ;
  6903. end;
  6904. end
  6905. else
  6906. if MatchOpType(taicpu(p),top_ref) and
  6907. GetNextInstruction(p, hp2) and
  6908. (hp2.typ = Ait_Instruction) and
  6909. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6910. (taicpu(p).opsize in [S_FS, S_FL]) and
  6911. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6912. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6913. if GetLastInstruction(p, hp1) and
  6914. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6915. MatchOpType(taicpu(hp1),top_ref) and
  6916. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6917. if ((taicpu(hp2).opcode = A_FMULP) or
  6918. (taicpu(hp2).opcode = A_FADDP)) then
  6919. { change to
  6920. fld/fst mem1 (hp1) fld/fst mem1
  6921. fld mem1 (p) fadd/
  6922. faddp/ fmul st, st
  6923. fmulp st, st1 (hp2) }
  6924. begin
  6925. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6926. RemoveCurrentP(p, hp1);
  6927. if (taicpu(hp2).opcode = A_FADDP) then
  6928. taicpu(hp2).opcode := A_FADD
  6929. else
  6930. taicpu(hp2).opcode := A_FMUL;
  6931. taicpu(hp2).oper[1]^.reg := NR_ST;
  6932. end
  6933. else
  6934. { change to
  6935. fld/fst mem1 (hp1) fld/fst mem1
  6936. fld mem1 (p) fld st
  6937. }
  6938. begin
  6939. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6940. taicpu(p).changeopsize(S_FL);
  6941. taicpu(p).loadreg(0,NR_ST);
  6942. end
  6943. else
  6944. begin
  6945. case taicpu(hp2).opcode Of
  6946. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6947. { change to
  6948. fld/fst mem1 (hp1) fld/fst mem1
  6949. fld mem2 (p) fxxx mem2
  6950. fxxxp st, st1 (hp2) }
  6951. begin
  6952. case taicpu(hp2).opcode Of
  6953. A_FADDP: taicpu(p).opcode := A_FADD;
  6954. A_FMULP: taicpu(p).opcode := A_FMUL;
  6955. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6956. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6957. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6958. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6959. else
  6960. internalerror(2019050533);
  6961. end;
  6962. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6963. RemoveInstruction(hp2);
  6964. end
  6965. else
  6966. ;
  6967. end
  6968. end
  6969. end;
  6970. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6971. begin
  6972. Result := condition_in(cond1, cond2) or
  6973. { Not strictly subsets due to the actual flags checked, but because we're
  6974. comparing integers, E is a subset of AE and GE and their aliases }
  6975. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6976. end;
  6977. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6978. var
  6979. v: TCGInt;
  6980. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6981. FirstMatch, TempBool: Boolean;
  6982. NewReg: TRegister;
  6983. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6984. begin
  6985. Result:=false;
  6986. { All these optimisations need a next instruction }
  6987. if not GetNextInstruction(p, hp1) then
  6988. Exit;
  6989. { Search for:
  6990. cmp ###,###
  6991. j(c1) @lbl1
  6992. ...
  6993. @lbl:
  6994. cmp ###,### (same comparison as above)
  6995. j(c2) @lbl2
  6996. If c1 is a subset of c2, change to:
  6997. cmp ###,###
  6998. j(c1) @lbl2
  6999. (@lbl1 may become a dead label as a result)
  7000. }
  7001. { Also handle cases where there are multiple jumps in a row }
  7002. p_jump := hp1;
  7003. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7004. begin
  7005. if IsJumpToLabel(taicpu(p_jump)) then
  7006. begin
  7007. { Do jump optimisations first in case the condition becomes
  7008. unnecessary }
  7009. TempBool := True;
  7010. if DoJumpOptimizations(p_jump, TempBool) or
  7011. not TempBool then
  7012. begin
  7013. if Assigned(p_jump) then
  7014. begin
  7015. hp1 := p_jump;
  7016. if (p_jump.typ in [ait_align]) then
  7017. SkipAligns(p_jump, p_jump);
  7018. { CollapseZeroDistJump will be set to the label after the
  7019. jump if it optimises, whether or not it's live or dead }
  7020. if (p_jump.typ in [ait_label]) and
  7021. not (tai_label(p_jump).labsym.is_used) then
  7022. GetNextInstruction(p_jump, p_jump);
  7023. end;
  7024. TransferUsedRegs(TmpUsedRegs);
  7025. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7026. if not Assigned(p_jump) or
  7027. (
  7028. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7029. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7030. ) then
  7031. begin
  7032. { No more conditional jumps; conditional statement is no longer required }
  7033. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7034. RemoveCurrentP(p);
  7035. Result := True;
  7036. Exit;
  7037. end;
  7038. hp1 := p_jump;
  7039. Include(OptsToCheck, aoc_ForceNewIteration);
  7040. Continue;
  7041. end;
  7042. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7043. if GetNextInstruction(p_jump, hp2) and
  7044. (
  7045. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7046. not TempBool
  7047. ) then
  7048. begin
  7049. hp1 := p_jump;
  7050. Include(OptsToCheck, aoc_ForceNewIteration);
  7051. Continue;
  7052. end;
  7053. p_label := nil;
  7054. if Assigned(JumpLabel) then
  7055. p_label := getlabelwithsym(JumpLabel);
  7056. if Assigned(p_label) and
  7057. GetNextInstruction(p_label, p_dist) and
  7058. MatchInstruction(p_dist, A_CMP, []) and
  7059. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7060. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7061. GetNextInstruction(p_dist, hp1_dist) and
  7062. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7063. begin
  7064. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7065. if JumpLabel = JumpLabel_dist then
  7066. { This is an infinite loop }
  7067. Exit;
  7068. { Best optimisation when the first condition is a subset (or equal) of the second }
  7069. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7070. begin
  7071. { Any registers used here will already be allocated }
  7072. if Assigned(JumpLabel) then
  7073. JumpLabel.DecRefs;
  7074. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7075. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7076. Result := True;
  7077. { Don't exit yet. Since p and p_jump haven't actually been
  7078. removed, we can check for more on this iteration }
  7079. end
  7080. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7081. GetNextInstruction(hp1_dist, hp1_label) and
  7082. SkipAligns(hp1_label, hp1_label) and
  7083. (hp1_label.typ = ait_label) then
  7084. begin
  7085. JumpLabel_far := tai_label(hp1_label).labsym;
  7086. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7087. { This is an infinite loop }
  7088. Exit;
  7089. if Assigned(JumpLabel_far) then
  7090. begin
  7091. { In this situation, if the first jump branches, the second one will never,
  7092. branch so change the destination label to after the second jump }
  7093. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7094. if Assigned(JumpLabel) then
  7095. JumpLabel.DecRefs;
  7096. JumpLabel_far.IncRefs;
  7097. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7098. Result := True;
  7099. { Don't exit yet. Since p and p_jump haven't actually been
  7100. removed, we can check for more on this iteration }
  7101. Continue;
  7102. end;
  7103. end;
  7104. end;
  7105. end;
  7106. { Search for:
  7107. cmp ###,###
  7108. j(c1) @lbl1
  7109. cmp ###,### (same as first)
  7110. Remove second cmp
  7111. }
  7112. if GetNextInstruction(p_jump, hp2) and
  7113. (
  7114. (
  7115. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7116. (
  7117. (
  7118. MatchOpType(taicpu(p), top_const, top_reg) and
  7119. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7120. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7121. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7122. ) or (
  7123. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7124. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7125. )
  7126. )
  7127. ) or (
  7128. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7129. MatchOperand(taicpu(p).oper[0]^, 0) and
  7130. (taicpu(p).oper[1]^.typ = top_reg) and
  7131. MatchInstruction(hp2, A_TEST, []) and
  7132. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7133. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7134. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7135. )
  7136. ) then
  7137. begin
  7138. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7139. RemoveInstruction(hp2);
  7140. Result := True;
  7141. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7142. end;
  7143. GetNextInstruction(p_jump, p_jump);
  7144. end;
  7145. if (
  7146. { Don't call GetNextInstruction again if we already have it }
  7147. (hp1 = p_jump) or
  7148. GetNextInstruction(p, hp1)
  7149. ) and
  7150. MatchInstruction(hp1, A_Jcc, []) and
  7151. IsJumpToLabel(taicpu(hp1)) and
  7152. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7153. GetNextInstruction(hp1, hp2) then
  7154. begin
  7155. {
  7156. cmp x, y (or "cmp y, x")
  7157. je @lbl
  7158. mov x, y
  7159. @lbl:
  7160. (x and y can be constants, registers or references)
  7161. Change to:
  7162. mov x, y (x and y will always be equal in the end)
  7163. @lbl: (may beceome a dead label)
  7164. Also:
  7165. cmp x, y (or "cmp y, x")
  7166. jne @lbl
  7167. mov x, y
  7168. @lbl:
  7169. (x and y can be constants, registers or references)
  7170. Change to:
  7171. Absolutely nothing! (Except @lbl if it's still live)
  7172. }
  7173. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7174. (
  7175. (
  7176. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7177. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7178. ) or (
  7179. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7180. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7181. )
  7182. ) and
  7183. GetNextInstruction(hp2, hp1_label) and
  7184. SkipAligns(hp1_label, hp1_label) and
  7185. (hp1_label.typ = ait_label) and
  7186. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7187. begin
  7188. tai_label(hp1_label).labsym.DecRefs;
  7189. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7190. begin
  7191. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7192. RemoveInstruction(hp2);
  7193. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7194. end
  7195. else
  7196. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7197. RemoveInstruction(hp1);
  7198. RemoveCurrentp(p, hp2);
  7199. Result := True;
  7200. Exit;
  7201. end;
  7202. {
  7203. Try to optimise the following:
  7204. cmp $x,### ($x and $y can be registers or constants)
  7205. je @lbl1 (only reference)
  7206. cmp $y,### (### are identical)
  7207. @Lbl:
  7208. sete %reg1
  7209. Change to:
  7210. cmp $x,###
  7211. sete %reg2 (allocate new %reg2)
  7212. cmp $y,###
  7213. sete %reg1
  7214. orb %reg2,%reg1
  7215. (dealloc %reg2)
  7216. This adds an instruction (so don't perform under -Os), but it removes
  7217. a conditional branch.
  7218. }
  7219. if not (cs_opt_size in current_settings.optimizerswitches) and
  7220. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7221. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7222. { The first operand of CMP instructions can only be a register or
  7223. immediate anyway, so no need to check }
  7224. GetNextInstruction(hp2, p_label) and
  7225. (p_label.typ = ait_label) and
  7226. (tai_label(p_label).labsym.getrefs = 1) and
  7227. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7228. GetNextInstruction(p_label, p_dist) and
  7229. MatchInstruction(p_dist, A_SETcc, []) and
  7230. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7231. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7232. begin
  7233. TransferUsedRegs(TmpUsedRegs);
  7234. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7235. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7236. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7237. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7238. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7239. { Get the instruction after the SETcc instruction so we can
  7240. allocate a new register over the entire range }
  7241. GetNextInstruction(p_dist, hp1_dist) then
  7242. begin
  7243. { Register can appear in p if it's not used afterwards, so only
  7244. allocate between hp1 and hp1_dist }
  7245. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7246. if NewReg <> NR_NO then
  7247. begin
  7248. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7249. { Change the jump instruction into a SETcc instruction }
  7250. taicpu(hp1).opcode := A_SETcc;
  7251. taicpu(hp1).opsize := S_B;
  7252. taicpu(hp1).loadreg(0, NewReg);
  7253. { This is now a dead label }
  7254. tai_label(p_label).labsym.decrefs;
  7255. { Prefer adding before the next instruction so the FLAGS
  7256. register is deallicated first }
  7257. AsmL.InsertBefore(
  7258. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7259. hp1_dist
  7260. );
  7261. Result := True;
  7262. { Don't exit yet, as p wasn't changed and hp1, while
  7263. modified, is still intact and might be optimised by the
  7264. SETcc optimisation below }
  7265. end;
  7266. end;
  7267. end;
  7268. end;
  7269. if taicpu(p).oper[0]^.typ = top_const then
  7270. begin
  7271. if (taicpu(p).oper[0]^.val = 0) and
  7272. (taicpu(p).oper[1]^.typ = top_reg) and
  7273. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7274. begin
  7275. hp2 := p;
  7276. FirstMatch := True;
  7277. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7278. anything meaningful once it's converted to "test %reg,%reg";
  7279. additionally, some jumps will always (or never) branch, so
  7280. evaluate every jump immediately following the
  7281. comparison, optimising the conditions if possible.
  7282. Similarly with SETcc... those that are always set to 0 or 1
  7283. are changed to MOV instructions }
  7284. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7285. (
  7286. GetNextInstruction(hp2, hp1) and
  7287. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7288. ) do
  7289. begin
  7290. FirstMatch := False;
  7291. case taicpu(hp1).condition of
  7292. C_B, C_C, C_NAE, C_O:
  7293. { For B/NAE:
  7294. Will never branch since an unsigned integer can never be below zero
  7295. For C/O:
  7296. Result cannot overflow because 0 is being subtracted
  7297. }
  7298. begin
  7299. if taicpu(hp1).opcode = A_Jcc then
  7300. begin
  7301. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7302. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7303. RemoveInstruction(hp1);
  7304. { Since hp1 was deleted, hp2 must not be updated }
  7305. Continue;
  7306. end
  7307. else
  7308. begin
  7309. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7310. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7311. taicpu(hp1).opcode := A_MOV;
  7312. taicpu(hp1).ops := 2;
  7313. taicpu(hp1).condition := C_None;
  7314. taicpu(hp1).opsize := S_B;
  7315. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7316. taicpu(hp1).loadconst(0, 0);
  7317. end;
  7318. end;
  7319. C_BE, C_NA:
  7320. begin
  7321. { Will only branch if equal to zero }
  7322. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7323. taicpu(hp1).condition := C_E;
  7324. end;
  7325. C_A, C_NBE:
  7326. begin
  7327. { Will only branch if not equal to zero }
  7328. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7329. taicpu(hp1).condition := C_NE;
  7330. end;
  7331. C_AE, C_NB, C_NC, C_NO:
  7332. begin
  7333. { Will always branch }
  7334. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7335. if taicpu(hp1).opcode = A_Jcc then
  7336. begin
  7337. MakeUnconditional(taicpu(hp1));
  7338. { Any jumps/set that follow will now be dead code }
  7339. RemoveDeadCodeAfterJump(taicpu(hp1));
  7340. Break;
  7341. end
  7342. else
  7343. begin
  7344. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7345. taicpu(hp1).opcode := A_MOV;
  7346. taicpu(hp1).ops := 2;
  7347. taicpu(hp1).condition := C_None;
  7348. taicpu(hp1).opsize := S_B;
  7349. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7350. taicpu(hp1).loadconst(0, 1);
  7351. end;
  7352. end;
  7353. C_None:
  7354. InternalError(2020012201);
  7355. C_P, C_PE, C_NP, C_PO:
  7356. { We can't handle parity checks and they should never be generated
  7357. after a general-purpose CMP (it's used in some floating-point
  7358. comparisons that don't use CMP) }
  7359. InternalError(2020012202);
  7360. else
  7361. { Zero/Equality, Sign, their complements and all of the
  7362. signed comparisons do not need to be converted };
  7363. end;
  7364. hp2 := hp1;
  7365. end;
  7366. { Convert the instruction to a TEST }
  7367. taicpu(p).opcode := A_TEST;
  7368. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7369. Result := True;
  7370. Exit;
  7371. end
  7372. else if (taicpu(p).oper[0]^.val = 1) and
  7373. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7374. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7375. begin
  7376. { Convert; To:
  7377. cmp $1,r/m cmp $0,r/m
  7378. jl @lbl jle @lbl
  7379. (Also do inverted conditions)
  7380. }
  7381. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7382. taicpu(p).oper[0]^.val := 0;
  7383. if taicpu(hp1).condition in [C_L, C_NGE] then
  7384. taicpu(hp1).condition := C_LE
  7385. else
  7386. taicpu(hp1).condition := C_NLE;
  7387. { If the instruction is now "cmp $0,%reg", convert it to a
  7388. TEST (and effectively do the work of the "cmp $0,%reg" in
  7389. the block above)
  7390. }
  7391. if (taicpu(p).oper[1]^.typ = top_reg) then
  7392. begin
  7393. taicpu(p).opcode := A_TEST;
  7394. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7395. end;
  7396. Result := True;
  7397. Exit;
  7398. end
  7399. else if (taicpu(p).oper[1]^.typ = top_reg)
  7400. {$ifdef x86_64}
  7401. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7402. {$endif x86_64}
  7403. then
  7404. begin
  7405. { cmp register,$8000 neg register
  7406. je target --> jo target
  7407. .... only if register is deallocated before jump.}
  7408. case Taicpu(p).opsize of
  7409. S_B: v:=$80;
  7410. S_W: v:=$8000;
  7411. S_L: v:=qword($80000000);
  7412. else
  7413. internalerror(2013112905);
  7414. end;
  7415. if (taicpu(p).oper[0]^.val=v) and
  7416. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7417. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7418. begin
  7419. TransferUsedRegs(TmpUsedRegs);
  7420. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7421. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7422. begin
  7423. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7424. Taicpu(p).opcode:=A_NEG;
  7425. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7426. Taicpu(p).clearop(1);
  7427. Taicpu(p).ops:=1;
  7428. if Taicpu(hp1).condition=C_E then
  7429. Taicpu(hp1).condition:=C_O
  7430. else
  7431. Taicpu(hp1).condition:=C_NO;
  7432. Result:=true;
  7433. exit;
  7434. end;
  7435. end;
  7436. end;
  7437. end;
  7438. if TrySwapMovCmp(p, hp1) then
  7439. begin
  7440. Result := True;
  7441. Exit;
  7442. end;
  7443. end;
  7444. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7445. var
  7446. hp1: tai;
  7447. begin
  7448. {
  7449. remove the second (v)pxor from
  7450. pxor reg,reg
  7451. ...
  7452. pxor reg,reg
  7453. }
  7454. Result:=false;
  7455. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7456. MatchOpType(taicpu(p),top_reg,top_reg) and
  7457. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7458. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7459. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7460. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7461. begin
  7462. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7463. RemoveInstruction(hp1);
  7464. Result:=true;
  7465. Exit;
  7466. end
  7467. {
  7468. replace
  7469. pxor reg1,reg1
  7470. movapd/s reg1,reg2
  7471. dealloc reg1
  7472. by
  7473. pxor reg2,reg2
  7474. }
  7475. else if GetNextInstruction(p,hp1) and
  7476. { we mix single and double opperations here because we assume that the compiler
  7477. generates vmovapd only after double operations and vmovaps only after single operations }
  7478. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7479. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7480. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7481. (taicpu(p).oper[0]^.typ=top_reg) then
  7482. begin
  7483. TransferUsedRegs(TmpUsedRegs);
  7484. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7485. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7486. begin
  7487. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7488. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7489. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7490. RemoveInstruction(hp1);
  7491. result:=true;
  7492. end;
  7493. end;
  7494. end;
  7495. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7496. var
  7497. hp1: tai;
  7498. begin
  7499. {
  7500. remove the second (v)pxor from
  7501. (v)pxor reg,reg
  7502. ...
  7503. (v)pxor reg,reg
  7504. }
  7505. Result:=false;
  7506. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7507. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7508. begin
  7509. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7510. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7511. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7512. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7513. begin
  7514. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7515. RemoveInstruction(hp1);
  7516. Result:=true;
  7517. Exit;
  7518. end;
  7519. {$ifdef x86_64}
  7520. {
  7521. replace
  7522. vpxor reg1,reg1,reg1
  7523. vmov reg,mem
  7524. by
  7525. movq $0,mem
  7526. }
  7527. if GetNextInstruction(p,hp1) and
  7528. MatchInstruction(hp1,A_VMOVSD,[]) and
  7529. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7530. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7531. begin
  7532. TransferUsedRegs(TmpUsedRegs);
  7533. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7534. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7535. begin
  7536. taicpu(hp1).loadconst(0,0);
  7537. taicpu(hp1).opcode:=A_MOV;
  7538. taicpu(hp1).opsize:=S_Q;
  7539. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7540. RemoveCurrentP(p);
  7541. result:=true;
  7542. Exit;
  7543. end;
  7544. end;
  7545. {$endif x86_64}
  7546. end
  7547. {
  7548. replace
  7549. vpxor reg1,reg1,reg2
  7550. by
  7551. vpxor reg2,reg2,reg2
  7552. to avoid unncessary data dependencies
  7553. }
  7554. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7555. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7556. begin
  7557. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7558. { avoid unncessary data dependency }
  7559. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7560. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7561. result:=true;
  7562. exit;
  7563. end;
  7564. Result:=OptPass1VOP(p);
  7565. end;
  7566. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7567. var
  7568. hp1 : tai;
  7569. begin
  7570. result:=false;
  7571. { replace
  7572. IMul const,%mreg1,%mreg2
  7573. Mov %reg2,%mreg3
  7574. dealloc %mreg3
  7575. by
  7576. Imul const,%mreg1,%mreg23
  7577. }
  7578. if (taicpu(p).ops=3) and
  7579. GetNextInstruction(p,hp1) and
  7580. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7581. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7582. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7583. begin
  7584. TransferUsedRegs(TmpUsedRegs);
  7585. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7586. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7587. begin
  7588. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7589. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7590. RemoveInstruction(hp1);
  7591. result:=true;
  7592. end;
  7593. end;
  7594. end;
  7595. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7596. var
  7597. hp1 : tai;
  7598. begin
  7599. result:=false;
  7600. { replace
  7601. IMul %reg0,%reg1,%reg2
  7602. Mov %reg2,%reg3
  7603. dealloc %reg2
  7604. by
  7605. Imul %reg0,%reg1,%reg3
  7606. }
  7607. if GetNextInstruction(p,hp1) and
  7608. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7609. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7610. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7611. begin
  7612. TransferUsedRegs(TmpUsedRegs);
  7613. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7614. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7615. begin
  7616. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7617. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7618. RemoveInstruction(hp1);
  7619. result:=true;
  7620. end;
  7621. end;
  7622. end;
  7623. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7624. var
  7625. hp1: tai;
  7626. begin
  7627. Result:=false;
  7628. { get rid of
  7629. (v)cvtss2sd reg0,<reg1,>reg2
  7630. (v)cvtss2sd reg2,<reg2,>reg0
  7631. }
  7632. if GetNextInstruction(p,hp1) and
  7633. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7634. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7635. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7636. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7637. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7638. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7639. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7640. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7641. )
  7642. ) then
  7643. begin
  7644. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7645. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7646. begin
  7647. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7648. RemoveCurrentP(p);
  7649. RemoveInstruction(hp1);
  7650. end
  7651. else
  7652. begin
  7653. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7654. if taicpu(hp1).opcode=A_CVTSD2SS then
  7655. begin
  7656. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7657. taicpu(p).opcode:=A_MOVAPS;
  7658. end
  7659. else
  7660. begin
  7661. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7662. taicpu(p).opcode:=A_VMOVAPS;
  7663. end;
  7664. taicpu(p).ops:=2;
  7665. RemoveInstruction(hp1);
  7666. end;
  7667. Result:=true;
  7668. Exit;
  7669. end;
  7670. end;
  7671. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7672. var
  7673. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7674. ThisReg: TRegister;
  7675. begin
  7676. Result := False;
  7677. if not GetNextInstruction(p,hp1) then
  7678. Exit;
  7679. {
  7680. convert
  7681. j<c> .L1
  7682. mov 1,reg
  7683. jmp .L2
  7684. .L1
  7685. mov 0,reg
  7686. .L2
  7687. into
  7688. mov 0,reg
  7689. set<not(c)> reg
  7690. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7691. would destroy the flag contents
  7692. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7693. executed at the same time as a previous comparison.
  7694. set<not(c)> reg
  7695. movzx reg, reg
  7696. }
  7697. if MatchInstruction(hp1,A_MOV,[]) and
  7698. (taicpu(hp1).oper[0]^.typ = top_const) and
  7699. (
  7700. (
  7701. (taicpu(hp1).oper[1]^.typ = top_reg)
  7702. {$ifdef i386}
  7703. { Under i386, ESI, EDI, EBP and ESP
  7704. don't have an 8-bit representation }
  7705. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7706. {$endif i386}
  7707. ) or (
  7708. {$ifdef i386}
  7709. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7710. {$endif i386}
  7711. (taicpu(hp1).opsize = S_B)
  7712. )
  7713. ) and
  7714. GetNextInstruction(hp1,hp2) and
  7715. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7716. GetNextInstruction(hp2,hp3) and
  7717. SkipAligns(hp3, hp3) and
  7718. (hp3.typ=ait_label) and
  7719. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7720. GetNextInstruction(hp3,hp4) and
  7721. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7722. (taicpu(hp4).oper[0]^.typ = top_const) and
  7723. (
  7724. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7725. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7726. ) and
  7727. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7728. GetNextInstruction(hp4,hp5) and
  7729. SkipAligns(hp5, hp5) and
  7730. (hp5.typ=ait_label) and
  7731. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7732. begin
  7733. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7734. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7735. tai_label(hp3).labsym.DecRefs;
  7736. { If this isn't the only reference to the middle label, we can
  7737. still make a saving - only that the first jump and everything
  7738. that follows will remain. }
  7739. if (tai_label(hp3).labsym.getrefs = 0) then
  7740. begin
  7741. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7742. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7743. else
  7744. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7745. { remove jump, first label and second MOV (also catching any aligns) }
  7746. repeat
  7747. if not GetNextInstruction(hp2, hp3) then
  7748. InternalError(2021040810);
  7749. RemoveInstruction(hp2);
  7750. hp2 := hp3;
  7751. until hp2 = hp5;
  7752. { Don't decrement reference count before the removal loop
  7753. above, otherwise GetNextInstruction won't stop on the
  7754. the label }
  7755. tai_label(hp5).labsym.DecRefs;
  7756. end
  7757. else
  7758. begin
  7759. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7760. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7761. else
  7762. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7763. end;
  7764. taicpu(p).opcode:=A_SETcc;
  7765. taicpu(p).opsize:=S_B;
  7766. taicpu(p).is_jmp:=False;
  7767. if taicpu(hp1).opsize=S_B then
  7768. begin
  7769. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7770. if taicpu(hp1).oper[1]^.typ = top_reg then
  7771. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7772. RemoveInstruction(hp1);
  7773. end
  7774. else
  7775. begin
  7776. { Will be a register because the size can't be S_B otherwise }
  7777. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7778. taicpu(p).loadreg(0, ThisReg);
  7779. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7780. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7781. begin
  7782. case taicpu(hp1).opsize of
  7783. S_W:
  7784. taicpu(hp1).opsize := S_BW;
  7785. S_L:
  7786. taicpu(hp1).opsize := S_BL;
  7787. {$ifdef x86_64}
  7788. S_Q:
  7789. begin
  7790. taicpu(hp1).opsize := S_BL;
  7791. { Change the destination register to 32-bit }
  7792. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7793. end;
  7794. {$endif x86_64}
  7795. else
  7796. InternalError(2021040820);
  7797. end;
  7798. taicpu(hp1).opcode := A_MOVZX;
  7799. taicpu(hp1).loadreg(0, ThisReg);
  7800. end
  7801. else
  7802. begin
  7803. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7804. { hp1 is already a MOV instruction with the correct register }
  7805. taicpu(hp1).loadconst(0, 0);
  7806. { Inserting it right before p will guarantee that the flags are also tracked }
  7807. asml.Remove(hp1);
  7808. asml.InsertBefore(hp1, p);
  7809. end;
  7810. end;
  7811. Result:=true;
  7812. exit;
  7813. end
  7814. else if (hp1.typ = ait_label) then
  7815. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7816. end;
  7817. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7818. var
  7819. hp1, hp2, hp3: tai;
  7820. SourceRef, TargetRef: TReference;
  7821. CurrentReg: TRegister;
  7822. begin
  7823. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7824. if not UseAVX then
  7825. InternalError(2021100501);
  7826. Result := False;
  7827. { Look for the following to simplify:
  7828. vmovdqa/u x(mem1), %xmmreg
  7829. vmovdqa/u %xmmreg, y(mem2)
  7830. vmovdqa/u x+16(mem1), %xmmreg
  7831. vmovdqa/u %xmmreg, y+16(mem2)
  7832. Change to:
  7833. vmovdqa/u x(mem1), %ymmreg
  7834. vmovdqa/u %ymmreg, y(mem2)
  7835. vpxor %ymmreg, %ymmreg, %ymmreg
  7836. ( The VPXOR instruction is to zero the upper half, thus removing the
  7837. need to call the potentially expensive VZEROUPPER instruction. Other
  7838. peephole optimisations can remove VPXOR if it's unnecessary )
  7839. }
  7840. TransferUsedRegs(TmpUsedRegs);
  7841. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7842. { NOTE: In the optimisations below, if the references dictate that an
  7843. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7844. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7845. if (taicpu(p).opsize = S_XMM) and
  7846. MatchOpType(taicpu(p), top_ref, top_reg) and
  7847. GetNextInstruction(p, hp1) and
  7848. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7849. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7850. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7851. begin
  7852. SourceRef := taicpu(p).oper[0]^.ref^;
  7853. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7854. if GetNextInstruction(hp1, hp2) and
  7855. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7856. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7857. begin
  7858. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7859. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7860. Inc(SourceRef.offset, 16);
  7861. { Reuse the register in the first block move }
  7862. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7863. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7864. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7865. begin
  7866. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7867. Inc(TargetRef.offset, 16);
  7868. if GetNextInstruction(hp2, hp3) and
  7869. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7870. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7871. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7872. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7873. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7874. begin
  7875. { Update the register tracking to the new size }
  7876. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7877. { Remember that the offsets are 16 ahead }
  7878. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7879. if not (
  7880. ((SourceRef.offset mod 32) = 16) and
  7881. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7882. ) then
  7883. taicpu(p).opcode := A_VMOVDQU;
  7884. taicpu(p).opsize := S_YMM;
  7885. taicpu(p).oper[1]^.reg := CurrentReg;
  7886. if not (
  7887. ((TargetRef.offset mod 32) = 16) and
  7888. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7889. ) then
  7890. taicpu(hp1).opcode := A_VMOVDQU;
  7891. taicpu(hp1).opsize := S_YMM;
  7892. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7893. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7894. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7895. if (pi_uses_ymm in current_procinfo.flags) then
  7896. RemoveInstruction(hp2)
  7897. else
  7898. begin
  7899. taicpu(hp2).opcode := A_VPXOR;
  7900. taicpu(hp2).opsize := S_YMM;
  7901. taicpu(hp2).loadreg(0, CurrentReg);
  7902. taicpu(hp2).loadreg(1, CurrentReg);
  7903. taicpu(hp2).loadreg(2, CurrentReg);
  7904. taicpu(hp2).ops := 3;
  7905. end;
  7906. RemoveInstruction(hp3);
  7907. Result := True;
  7908. Exit;
  7909. end;
  7910. end
  7911. else
  7912. begin
  7913. { See if the next references are 16 less rather than 16 greater }
  7914. Dec(SourceRef.offset, 32); { -16 the other way }
  7915. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7916. begin
  7917. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7918. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7919. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7920. GetNextInstruction(hp2, hp3) and
  7921. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7922. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7923. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7924. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7925. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7926. begin
  7927. { Update the register tracking to the new size }
  7928. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7929. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7930. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7931. if not(
  7932. ((SourceRef.offset mod 32) = 0) and
  7933. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7934. ) then
  7935. taicpu(hp2).opcode := A_VMOVDQU;
  7936. taicpu(hp2).opsize := S_YMM;
  7937. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7938. if not (
  7939. ((TargetRef.offset mod 32) = 0) and
  7940. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7941. ) then
  7942. taicpu(hp3).opcode := A_VMOVDQU;
  7943. taicpu(hp3).opsize := S_YMM;
  7944. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7945. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7946. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7947. if (pi_uses_ymm in current_procinfo.flags) then
  7948. RemoveInstruction(hp1)
  7949. else
  7950. begin
  7951. taicpu(hp1).opcode := A_VPXOR;
  7952. taicpu(hp1).opsize := S_YMM;
  7953. taicpu(hp1).loadreg(0, CurrentReg);
  7954. taicpu(hp1).loadreg(1, CurrentReg);
  7955. taicpu(hp1).loadreg(2, CurrentReg);
  7956. taicpu(hp1).ops := 3;
  7957. Asml.Remove(hp1);
  7958. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7959. end;
  7960. RemoveCurrentP(p, hp2);
  7961. Result := True;
  7962. Exit;
  7963. end;
  7964. end;
  7965. end;
  7966. end;
  7967. end;
  7968. end;
  7969. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7970. var
  7971. hp2, hp3, first_assignment: tai;
  7972. IncCount, OperIdx: Integer;
  7973. OrigLabel: TAsmLabel;
  7974. begin
  7975. Count := 0;
  7976. Result := False;
  7977. first_assignment := nil;
  7978. if (LoopCount >= 20) then
  7979. begin
  7980. { Guard against infinite loops }
  7981. Exit;
  7982. end;
  7983. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7984. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7985. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7986. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7987. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7988. Exit;
  7989. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7990. {
  7991. change
  7992. jmp .L1
  7993. ...
  7994. .L1:
  7995. mov ##, ## ( multiple movs possible )
  7996. jmp/ret
  7997. into
  7998. mov ##, ##
  7999. jmp/ret
  8000. }
  8001. if not Assigned(hp1) then
  8002. begin
  8003. hp1 := GetLabelWithSym(OrigLabel);
  8004. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8005. Exit;
  8006. end;
  8007. hp2 := hp1;
  8008. while Assigned(hp2) do
  8009. begin
  8010. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8011. SkipLabels(hp2,hp2);
  8012. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8013. Break;
  8014. case taicpu(hp2).opcode of
  8015. A_MOVSD:
  8016. begin
  8017. if taicpu(hp2).ops = 0 then
  8018. { Wrong MOVSD }
  8019. Break;
  8020. Inc(Count);
  8021. if Count >= 5 then
  8022. { Too many to be worthwhile }
  8023. Break;
  8024. GetNextInstruction(hp2, hp2);
  8025. Continue;
  8026. end;
  8027. A_MOV,
  8028. A_MOVD,
  8029. A_MOVQ,
  8030. A_MOVSX,
  8031. {$ifdef x86_64}
  8032. A_MOVSXD,
  8033. {$endif x86_64}
  8034. A_MOVZX,
  8035. A_MOVAPS,
  8036. A_MOVUPS,
  8037. A_MOVSS,
  8038. A_MOVAPD,
  8039. A_MOVUPD,
  8040. A_MOVDQA,
  8041. A_MOVDQU,
  8042. A_VMOVSS,
  8043. A_VMOVAPS,
  8044. A_VMOVUPS,
  8045. A_VMOVSD,
  8046. A_VMOVAPD,
  8047. A_VMOVUPD,
  8048. A_VMOVDQA,
  8049. A_VMOVDQU:
  8050. begin
  8051. Inc(Count);
  8052. if Count >= 5 then
  8053. { Too many to be worthwhile }
  8054. Break;
  8055. GetNextInstruction(hp2, hp2);
  8056. Continue;
  8057. end;
  8058. A_JMP:
  8059. begin
  8060. { Guard against infinite loops }
  8061. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8062. Exit;
  8063. { Analyse this jump first in case it also duplicates assignments }
  8064. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8065. begin
  8066. { Something did change! }
  8067. Result := True;
  8068. Inc(Count, IncCount);
  8069. if Count >= 5 then
  8070. begin
  8071. { Too many to be worthwhile }
  8072. Exit;
  8073. end;
  8074. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8075. Break;
  8076. end;
  8077. Result := True;
  8078. Break;
  8079. end;
  8080. A_RET:
  8081. begin
  8082. Result := True;
  8083. Break;
  8084. end;
  8085. else
  8086. Break;
  8087. end;
  8088. end;
  8089. if Result then
  8090. begin
  8091. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8092. if Count = 0 then
  8093. begin
  8094. Result := False;
  8095. Exit;
  8096. end;
  8097. hp3 := p;
  8098. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8099. while True do
  8100. begin
  8101. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8102. SkipLabels(hp1,hp1);
  8103. if (hp1.typ <> ait_instruction) then
  8104. InternalError(2021040720);
  8105. case taicpu(hp1).opcode of
  8106. A_JMP:
  8107. begin
  8108. { Change the original jump to the new destination }
  8109. OrigLabel.decrefs;
  8110. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8111. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8112. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8113. if not Assigned(first_assignment) then
  8114. InternalError(2021040810)
  8115. else
  8116. p := first_assignment;
  8117. Exit;
  8118. end;
  8119. A_RET:
  8120. begin
  8121. { Now change the jump into a RET instruction }
  8122. ConvertJumpToRET(p, hp1);
  8123. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8124. if not Assigned(first_assignment) then
  8125. InternalError(2021040811)
  8126. else
  8127. p := first_assignment;
  8128. Exit;
  8129. end;
  8130. else
  8131. begin
  8132. { Duplicate the MOV instruction }
  8133. hp3:=tai(hp1.getcopy);
  8134. if first_assignment = nil then
  8135. first_assignment := hp3;
  8136. asml.InsertBefore(hp3, p);
  8137. { Make sure the compiler knows about any final registers written here }
  8138. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8139. with taicpu(hp3).oper[OperIdx]^ do
  8140. begin
  8141. case typ of
  8142. top_ref:
  8143. begin
  8144. if (ref^.base <> NR_NO) and
  8145. (getsupreg(ref^.base) <> RS_ESP) and
  8146. (getsupreg(ref^.base) <> RS_EBP)
  8147. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8148. then
  8149. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8150. if (ref^.index <> NR_NO) and
  8151. (getsupreg(ref^.index) <> RS_ESP) and
  8152. (getsupreg(ref^.index) <> RS_EBP)
  8153. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8154. (ref^.index <> ref^.base) then
  8155. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8156. end;
  8157. top_reg:
  8158. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8159. else
  8160. ;
  8161. end;
  8162. end;
  8163. end;
  8164. end;
  8165. if not GetNextInstruction(hp1, hp1) then
  8166. { Should have dropped out earlier }
  8167. InternalError(2021040710);
  8168. end;
  8169. end;
  8170. end;
  8171. const
  8172. WriteOp: array[0..3] of set of TInsChange = (
  8173. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8174. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8175. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8176. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8177. RegWriteFlags: array[0..7] of set of TInsChange = (
  8178. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8179. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8180. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8181. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8182. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8183. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8184. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8185. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8186. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8187. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8188. var
  8189. hp2: tai;
  8190. X: Integer;
  8191. begin
  8192. { If we have something like:
  8193. op ###,###
  8194. mov ###,###
  8195. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8196. interfere in regards to what they write to.
  8197. NOTE: p must be a 2-operand instruction
  8198. }
  8199. Result := False;
  8200. if (hp1.typ <> ait_instruction) or
  8201. taicpu(hp1).is_jmp or
  8202. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8203. Exit;
  8204. { NOP is a pipeline fence, likely marking the beginning of the function
  8205. epilogue, so drop out. Similarly, drop out if POP or RET are
  8206. encountered }
  8207. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8208. Exit;
  8209. if (taicpu(hp1).opcode = A_MOVSD) and
  8210. (taicpu(hp1).ops = 0) then
  8211. { Wrong MOVSD }
  8212. Exit;
  8213. { Check for writes to specific registers first }
  8214. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8215. for X := 0 to 7 do
  8216. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8217. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8218. Exit;
  8219. for X := 0 to taicpu(hp1).ops - 1 do
  8220. begin
  8221. { Check to see if this operand writes to something }
  8222. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8223. { And matches something in the CMP/TEST instruction }
  8224. (
  8225. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8226. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8227. (
  8228. { If it's a register, make sure the register written to doesn't
  8229. appear in the cmp instruction as part of a reference }
  8230. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8231. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8232. )
  8233. ) then
  8234. Exit;
  8235. end;
  8236. { Check p to make sure it doesn't write to something that affects hp1 }
  8237. { Check for writes to specific registers first }
  8238. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8239. for X := 0 to 7 do
  8240. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8241. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8242. Exit;
  8243. for X := 0 to taicpu(p).ops - 1 do
  8244. begin
  8245. { Check to see if this operand writes to something }
  8246. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8247. { And matches something in hp1 }
  8248. (taicpu(p).oper[X]^.typ = top_reg) and
  8249. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8250. Exit;
  8251. end;
  8252. { The instruction can be safely moved }
  8253. asml.Remove(hp1);
  8254. { Try to insert after the last instructions where the FLAGS register is not
  8255. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8256. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8257. asml.InsertBefore(hp1, hp2)
  8258. { Failing that, try to insert after the last instructions where the
  8259. FLAGS register is not yet in use }
  8260. else if GetLastInstruction(p, hp2) and
  8261. (
  8262. (hp2.typ <> ait_instruction) or
  8263. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8264. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8265. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8266. ) then
  8267. asml.InsertAfter(hp1, hp2)
  8268. else
  8269. { Note, if p.Previous is nil (even if it should logically never be the
  8270. case), FindRegAllocBackward immediately exits with False and so we
  8271. safely land here (we can't just pass p because FindRegAllocBackward
  8272. immediately exits on an instruction). [Kit] }
  8273. asml.InsertBefore(hp1, p);
  8274. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8275. { We can't trust UsedRegs because we're looking backwards, although we
  8276. know the registers are allocated after p at the very least, so manually
  8277. create tai_regalloc objects if needed }
  8278. for X := 0 to taicpu(hp1).ops - 1 do
  8279. case taicpu(hp1).oper[X]^.typ of
  8280. top_reg:
  8281. begin
  8282. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8283. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8284. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8285. end;
  8286. top_ref:
  8287. begin
  8288. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8289. begin
  8290. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8291. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8292. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8293. end;
  8294. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8295. begin
  8296. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8297. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8298. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8299. end;
  8300. end;
  8301. else
  8302. ;
  8303. end;
  8304. Result := True;
  8305. end;
  8306. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8307. var
  8308. hp2: tai;
  8309. X: Integer;
  8310. begin
  8311. { If we have something like:
  8312. cmp ###,%reg1
  8313. mov 0,%reg2
  8314. And no modified registers are shared, move the instruction to before
  8315. the comparison as this means it can be optimised without worrying
  8316. about the FLAGS register. (CMP/MOV is generated by
  8317. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8318. As long as the second instruction doesn't use the flags or one of the
  8319. registers used by CMP or TEST (also check any references that use the
  8320. registers), then it can be moved prior to the comparison.
  8321. }
  8322. Result := False;
  8323. if not TrySwapMovOp(p, hp1) then
  8324. Exit;
  8325. if taicpu(hp1).opcode = A_LEA then
  8326. { The flags will be overwritten by the CMP/TEST instruction }
  8327. ConvertLEA(taicpu(hp1));
  8328. Result := True;
  8329. { Can we move it one further back? }
  8330. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8331. { Check to see if CMP/TEST is a comparison against zero }
  8332. (
  8333. (
  8334. (taicpu(p).opcode = A_CMP) and
  8335. MatchOperand(taicpu(p).oper[0]^, 0)
  8336. ) or
  8337. (
  8338. (taicpu(p).opcode = A_TEST) and
  8339. (
  8340. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8341. MatchOperand(taicpu(p).oper[0]^, -1)
  8342. )
  8343. )
  8344. ) and
  8345. { These instructions set the zero flag if the result is zero }
  8346. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8347. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8348. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8349. TrySwapMovOp(hp2, hp1);
  8350. end;
  8351. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8352. function IsXCHGAcceptable: Boolean; inline;
  8353. begin
  8354. { Always accept if optimising for size }
  8355. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8356. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8357. than 3, so it becomes a saving compared to three MOVs with two of
  8358. them able to execute simultaneously. [Kit] }
  8359. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8360. end;
  8361. var
  8362. NewRef: TReference;
  8363. hp1, hp2, hp3, hp4: Tai;
  8364. {$ifndef x86_64}
  8365. OperIdx: Integer;
  8366. {$endif x86_64}
  8367. NewInstr : Taicpu;
  8368. NewAligh : Tai_align;
  8369. DestLabel: TAsmLabel;
  8370. TempTracking: TAllUsedRegs;
  8371. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8372. var
  8373. NextInstr: tai;
  8374. begin
  8375. Result := False;
  8376. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8377. if not GetNextInstruction(InputInstr, NextInstr) or
  8378. (
  8379. { The FLAGS register isn't always tracked properly, so do not
  8380. perform this optimisation if a conditional statement follows }
  8381. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8382. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8383. ) then
  8384. begin
  8385. reference_reset(NewRef, 1, []);
  8386. NewRef.base := taicpu(p).oper[0]^.reg;
  8387. NewRef.scalefactor := 1;
  8388. if taicpu(InputInstr).opcode = A_ADD then
  8389. begin
  8390. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8391. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8392. end
  8393. else
  8394. begin
  8395. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8396. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8397. end;
  8398. taicpu(p).opcode := A_LEA;
  8399. taicpu(p).loadref(0, NewRef);
  8400. RemoveInstruction(InputInstr);
  8401. Result := True;
  8402. end;
  8403. end;
  8404. begin
  8405. Result:=false;
  8406. { This optimisation adds an instruction, so only do it for speed }
  8407. if not (cs_opt_size in current_settings.optimizerswitches) and
  8408. MatchOpType(taicpu(p), top_const, top_reg) and
  8409. (taicpu(p).oper[0]^.val = 0) then
  8410. begin
  8411. { To avoid compiler warning }
  8412. DestLabel := nil;
  8413. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8414. InternalError(2021040750);
  8415. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8416. Exit;
  8417. case hp1.typ of
  8418. ait_align,
  8419. ait_label:
  8420. begin
  8421. { Change:
  8422. mov $0,%reg mov $0,%reg
  8423. @Lbl1: @Lbl1:
  8424. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8425. je @Lbl2 jne @Lbl2
  8426. To: To:
  8427. mov $0,%reg mov $0,%reg
  8428. jmp @Lbl2 jmp @Lbl3
  8429. (align) (align)
  8430. @Lbl1: @Lbl1:
  8431. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8432. je @Lbl2 je @Lbl2
  8433. @Lbl3: <-- Only if label exists
  8434. (Not if it's optimised for size)
  8435. }
  8436. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8437. Exit;
  8438. if (hp2.typ = ait_instruction) and
  8439. (
  8440. { Register sizes must exactly match }
  8441. (
  8442. (taicpu(hp2).opcode = A_CMP) and
  8443. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8444. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8445. ) or (
  8446. (taicpu(hp2).opcode = A_TEST) and
  8447. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8448. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8449. )
  8450. ) and GetNextInstruction(hp2, hp3) and
  8451. (hp3.typ = ait_instruction) and
  8452. (taicpu(hp3).opcode = A_JCC) and
  8453. (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
  8454. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8455. begin
  8456. { Check condition of jump }
  8457. { Always true? }
  8458. if condition_in(C_E, taicpu(hp3).condition) then
  8459. begin
  8460. { Copy label symbol and obtain matching label entry for the
  8461. conditional jump, as this will be our destination}
  8462. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8463. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8464. Result := True;
  8465. end
  8466. { Always false? }
  8467. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8468. begin
  8469. { This is only worth it if there's a jump to take }
  8470. case hp2.typ of
  8471. ait_instruction:
  8472. begin
  8473. if taicpu(hp2).opcode = A_JMP then
  8474. begin
  8475. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8476. { An unconditional jump follows the conditional jump which will always be false,
  8477. so use this jump's destination for the new jump }
  8478. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8479. Result := True;
  8480. end
  8481. else if taicpu(hp2).opcode = A_JCC then
  8482. begin
  8483. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8484. if condition_in(C_E, taicpu(hp2).condition) then
  8485. begin
  8486. { A second conditional jump follows the conditional jump which will always be false,
  8487. while the second jump is always True, so use this jump's destination for the new jump }
  8488. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8489. Result := True;
  8490. end;
  8491. { Don't risk it if the jump isn't always true (Result remains False) }
  8492. end;
  8493. end;
  8494. else
  8495. { If anything else don't optimise };
  8496. end;
  8497. end;
  8498. if Result then
  8499. begin
  8500. { Just so we have something to insert as a paremeter}
  8501. reference_reset(NewRef, 1, []);
  8502. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8503. { Now actually load the correct parameter (this also
  8504. increases the reference count) }
  8505. NewInstr.loadsymbol(0, DestLabel, 0);
  8506. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8507. begin
  8508. { Get instruction before original label (may not be p under -O3) }
  8509. if not GetLastInstruction(hp1, hp2) then
  8510. { Shouldn't fail here }
  8511. InternalError(2021040701);
  8512. { Before the aligns too }
  8513. while (hp2.typ = ait_align) do
  8514. if not GetLastInstruction(hp2, hp2) then
  8515. { Shouldn't fail here }
  8516. InternalError(2021040702);
  8517. end
  8518. else
  8519. hp2 := p;
  8520. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8521. AsmL.InsertAfter(NewInstr, hp2);
  8522. { Add new alignment field }
  8523. (* AsmL.InsertAfter(
  8524. cai_align.create_max(
  8525. current_settings.alignment.jumpalign,
  8526. current_settings.alignment.jumpalignskipmax
  8527. ),
  8528. NewInstr
  8529. ); *)
  8530. end;
  8531. Exit;
  8532. end;
  8533. end;
  8534. else
  8535. ;
  8536. end;
  8537. end;
  8538. if not GetNextInstruction(p, hp1) then
  8539. Exit;
  8540. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8541. and DoMovCmpMemOpt(p, hp1) then
  8542. begin
  8543. Result := True;
  8544. Exit;
  8545. end
  8546. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8547. begin
  8548. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8549. further, but we can't just put this jump optimisation in pass 1
  8550. because it tends to perform worse when conditional jumps are
  8551. nearby (e.g. when converting CMOV instructions). [Kit] }
  8552. CopyUsedRegs(TempTracking);
  8553. UpdateUsedRegs(tai(p.Next));
  8554. if OptPass2JMP(hp1) then
  8555. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8556. Result := OptPass1MOV(p);
  8557. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8558. returned True and the instruction is still a MOV, thus checking
  8559. the optimisations below }
  8560. { If OptPass2JMP returned False, no optimisations were done to
  8561. the jump and there are no further optimisations that can be done
  8562. to the MOV instruction on this pass }
  8563. { Restore register state }
  8564. RestoreUsedRegs(TempTracking);
  8565. ReleaseUsedRegs(TempTracking);
  8566. end
  8567. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8568. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8569. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8570. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8571. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8572. begin
  8573. { Change:
  8574. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8575. addl/q $x,%reg2 subl/q $x,%reg2
  8576. To:
  8577. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8578. }
  8579. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8580. { be lazy, checking separately for sub would be slightly better }
  8581. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8582. begin
  8583. TransferUsedRegs(TmpUsedRegs);
  8584. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8585. if TryMovArith2Lea(hp1) then
  8586. begin
  8587. Result := True;
  8588. Exit;
  8589. end
  8590. end
  8591. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8592. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8593. { Same as above, but also adds or subtracts to %reg2 in between.
  8594. It's still valid as long as the flags aren't in use }
  8595. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8596. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8597. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8598. { be lazy, checking separately for sub would be slightly better }
  8599. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8600. begin
  8601. TransferUsedRegs(TmpUsedRegs);
  8602. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8603. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8604. if TryMovArith2Lea(hp2) then
  8605. begin
  8606. Result := True;
  8607. Exit;
  8608. end;
  8609. end;
  8610. end
  8611. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8612. {$ifdef x86_64}
  8613. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8614. {$else x86_64}
  8615. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8616. {$endif x86_64}
  8617. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8618. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8619. { mov reg1, reg2 mov reg1, reg2
  8620. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8621. begin
  8622. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8623. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8624. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8625. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8626. TransferUsedRegs(TmpUsedRegs);
  8627. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8628. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8629. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8630. then
  8631. begin
  8632. RemoveCurrentP(p, hp1);
  8633. Result:=true;
  8634. end;
  8635. exit;
  8636. end
  8637. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8638. IsXCHGAcceptable and
  8639. { XCHG doesn't support 8-byte registers }
  8640. (taicpu(p).opsize <> S_B) and
  8641. MatchInstruction(hp1, A_MOV, []) and
  8642. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8643. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8644. GetNextInstruction(hp1, hp2) and
  8645. MatchInstruction(hp2, A_MOV, []) and
  8646. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8647. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8648. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8649. begin
  8650. { mov %reg1,%reg2
  8651. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8652. mov %reg2,%reg3
  8653. (%reg2 not used afterwards)
  8654. Note that xchg takes 3 cycles to execute, and generally mov's take
  8655. only one cycle apiece, but the first two mov's can be executed in
  8656. parallel, only taking 2 cycles overall. Older processors should
  8657. therefore only optimise for size. [Kit]
  8658. }
  8659. TransferUsedRegs(TmpUsedRegs);
  8660. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8661. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8662. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8663. begin
  8664. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8665. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8666. taicpu(hp1).opcode := A_XCHG;
  8667. RemoveCurrentP(p, hp1);
  8668. RemoveInstruction(hp2);
  8669. Result := True;
  8670. Exit;
  8671. end;
  8672. end
  8673. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8674. MatchInstruction(hp1, A_SAR, []) then
  8675. begin
  8676. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8677. begin
  8678. { the use of %edx also covers the opsize being S_L }
  8679. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8680. begin
  8681. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8682. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8683. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8684. begin
  8685. { Change:
  8686. movl %eax,%edx
  8687. sarl $31,%edx
  8688. To:
  8689. cltd
  8690. }
  8691. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8692. RemoveInstruction(hp1);
  8693. taicpu(p).opcode := A_CDQ;
  8694. taicpu(p).opsize := S_NO;
  8695. taicpu(p).clearop(1);
  8696. taicpu(p).clearop(0);
  8697. taicpu(p).ops:=0;
  8698. Result := True;
  8699. end
  8700. else if (cs_opt_size in current_settings.optimizerswitches) and
  8701. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8702. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8703. begin
  8704. { Change:
  8705. movl %edx,%eax
  8706. sarl $31,%edx
  8707. To:
  8708. movl %edx,%eax
  8709. cltd
  8710. Note that this creates a dependency between the two instructions,
  8711. so only perform if optimising for size.
  8712. }
  8713. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8714. taicpu(hp1).opcode := A_CDQ;
  8715. taicpu(hp1).opsize := S_NO;
  8716. taicpu(hp1).clearop(1);
  8717. taicpu(hp1).clearop(0);
  8718. taicpu(hp1).ops:=0;
  8719. end;
  8720. {$ifndef x86_64}
  8721. end
  8722. { Don't bother if CMOV is supported, because a more optimal
  8723. sequence would have been generated for the Abs() intrinsic }
  8724. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8725. { the use of %eax also covers the opsize being S_L }
  8726. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8727. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8728. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8729. GetNextInstruction(hp1, hp2) and
  8730. MatchInstruction(hp2, A_XOR, [S_L]) and
  8731. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8732. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8733. GetNextInstruction(hp2, hp3) and
  8734. MatchInstruction(hp3, A_SUB, [S_L]) and
  8735. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8736. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8737. begin
  8738. { Change:
  8739. movl %eax,%edx
  8740. sarl $31,%eax
  8741. xorl %eax,%edx
  8742. subl %eax,%edx
  8743. (Instruction that uses %edx)
  8744. (%eax deallocated)
  8745. (%edx deallocated)
  8746. To:
  8747. cltd
  8748. xorl %edx,%eax <-- Note the registers have swapped
  8749. subl %edx,%eax
  8750. (Instruction that uses %eax) <-- %eax rather than %edx
  8751. }
  8752. TransferUsedRegs(TmpUsedRegs);
  8753. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8754. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8755. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8756. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8757. begin
  8758. if GetNextInstruction(hp3, hp4) and
  8759. not RegModifiedByInstruction(NR_EDX, hp4) and
  8760. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8761. begin
  8762. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8763. taicpu(p).opcode := A_CDQ;
  8764. taicpu(p).clearop(1);
  8765. taicpu(p).clearop(0);
  8766. taicpu(p).ops:=0;
  8767. RemoveInstruction(hp1);
  8768. taicpu(hp2).loadreg(0, NR_EDX);
  8769. taicpu(hp2).loadreg(1, NR_EAX);
  8770. taicpu(hp3).loadreg(0, NR_EDX);
  8771. taicpu(hp3).loadreg(1, NR_EAX);
  8772. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8773. { Convert references in the following instruction (hp4) from %edx to %eax }
  8774. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8775. with taicpu(hp4).oper[OperIdx]^ do
  8776. case typ of
  8777. top_reg:
  8778. if getsupreg(reg) = RS_EDX then
  8779. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8780. top_ref:
  8781. begin
  8782. if getsupreg(reg) = RS_EDX then
  8783. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8784. if getsupreg(reg) = RS_EDX then
  8785. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8786. end;
  8787. else
  8788. ;
  8789. end;
  8790. end;
  8791. end;
  8792. {$else x86_64}
  8793. end;
  8794. end
  8795. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8796. { the use of %rdx also covers the opsize being S_Q }
  8797. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8798. begin
  8799. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8800. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8801. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8802. begin
  8803. { Change:
  8804. movq %rax,%rdx
  8805. sarq $63,%rdx
  8806. To:
  8807. cqto
  8808. }
  8809. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8810. RemoveInstruction(hp1);
  8811. taicpu(p).opcode := A_CQO;
  8812. taicpu(p).opsize := S_NO;
  8813. taicpu(p).clearop(1);
  8814. taicpu(p).clearop(0);
  8815. taicpu(p).ops:=0;
  8816. Result := True;
  8817. end
  8818. else if (cs_opt_size in current_settings.optimizerswitches) and
  8819. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8820. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8821. begin
  8822. { Change:
  8823. movq %rdx,%rax
  8824. sarq $63,%rdx
  8825. To:
  8826. movq %rdx,%rax
  8827. cqto
  8828. Note that this creates a dependency between the two instructions,
  8829. so only perform if optimising for size.
  8830. }
  8831. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8832. taicpu(hp1).opcode := A_CQO;
  8833. taicpu(hp1).opsize := S_NO;
  8834. taicpu(hp1).clearop(1);
  8835. taicpu(hp1).clearop(0);
  8836. taicpu(hp1).ops:=0;
  8837. {$endif x86_64}
  8838. end;
  8839. end;
  8840. end
  8841. else if MatchInstruction(hp1, A_MOV, []) and
  8842. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8843. { Though "GetNextInstruction" could be factored out, along with
  8844. the instructions that depend on hp2, it is an expensive call that
  8845. should be delayed for as long as possible, hence we do cheaper
  8846. checks first that are likely to be False. [Kit] }
  8847. begin
  8848. if (
  8849. (
  8850. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8851. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8852. (
  8853. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8854. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8855. )
  8856. ) or
  8857. (
  8858. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8859. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8860. (
  8861. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8862. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8863. )
  8864. )
  8865. ) and
  8866. GetNextInstruction(hp1, hp2) and
  8867. MatchInstruction(hp2, A_SAR, []) and
  8868. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8869. begin
  8870. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8871. begin
  8872. { Change:
  8873. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8874. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8875. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8876. To:
  8877. movl r/m,%eax <- Note the change in register
  8878. cltd
  8879. }
  8880. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8881. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8882. taicpu(p).loadreg(1, NR_EAX);
  8883. taicpu(hp1).opcode := A_CDQ;
  8884. taicpu(hp1).clearop(1);
  8885. taicpu(hp1).clearop(0);
  8886. taicpu(hp1).ops:=0;
  8887. RemoveInstruction(hp2);
  8888. (*
  8889. {$ifdef x86_64}
  8890. end
  8891. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8892. { This code sequence does not get generated - however it might become useful
  8893. if and when 128-bit signed integer types make an appearance, so the code
  8894. is kept here for when it is eventually needed. [Kit] }
  8895. (
  8896. (
  8897. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8898. (
  8899. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8900. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8901. )
  8902. ) or
  8903. (
  8904. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8905. (
  8906. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8907. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8908. )
  8909. )
  8910. ) and
  8911. GetNextInstruction(hp1, hp2) and
  8912. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8913. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8914. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8915. begin
  8916. { Change:
  8917. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8918. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8919. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8920. To:
  8921. movq r/m,%rax <- Note the change in register
  8922. cqto
  8923. }
  8924. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8925. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8926. taicpu(p).loadreg(1, NR_RAX);
  8927. taicpu(hp1).opcode := A_CQO;
  8928. taicpu(hp1).clearop(1);
  8929. taicpu(hp1).clearop(0);
  8930. taicpu(hp1).ops:=0;
  8931. RemoveInstruction(hp2);
  8932. {$endif x86_64}
  8933. *)
  8934. end;
  8935. end;
  8936. {$ifdef x86_64}
  8937. end
  8938. else if (taicpu(p).opsize = S_L) and
  8939. (taicpu(p).oper[1]^.typ = top_reg) and
  8940. (
  8941. MatchInstruction(hp1, A_MOV,[]) and
  8942. (taicpu(hp1).opsize = S_L) and
  8943. (taicpu(hp1).oper[1]^.typ = top_reg)
  8944. ) and (
  8945. GetNextInstruction(hp1, hp2) and
  8946. (tai(hp2).typ=ait_instruction) and
  8947. (taicpu(hp2).opsize = S_Q) and
  8948. (
  8949. (
  8950. MatchInstruction(hp2, A_ADD,[]) and
  8951. (taicpu(hp2).opsize = S_Q) and
  8952. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8953. (
  8954. (
  8955. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8956. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8957. ) or (
  8958. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8959. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8960. )
  8961. )
  8962. ) or (
  8963. MatchInstruction(hp2, A_LEA,[]) and
  8964. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8965. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8966. (
  8967. (
  8968. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8969. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8970. ) or (
  8971. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8972. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8973. )
  8974. ) and (
  8975. (
  8976. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8977. ) or (
  8978. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8979. )
  8980. )
  8981. )
  8982. )
  8983. ) and (
  8984. GetNextInstruction(hp2, hp3) and
  8985. MatchInstruction(hp3, A_SHR,[]) and
  8986. (taicpu(hp3).opsize = S_Q) and
  8987. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8988. (taicpu(hp3).oper[0]^.val = 1) and
  8989. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8990. ) then
  8991. begin
  8992. { Change movl x, reg1d movl x, reg1d
  8993. movl y, reg2d movl y, reg2d
  8994. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8995. shrq $1, reg1q shrq $1, reg1q
  8996. ( reg1d and reg2d can be switched around in the first two instructions )
  8997. To movl x, reg1d
  8998. addl y, reg1d
  8999. rcrl $1, reg1d
  9000. This corresponds to the common expression (x + y) shr 1, where
  9001. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9002. smaller code, but won't account for x + y causing an overflow). [Kit]
  9003. }
  9004. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9005. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9006. { Change first MOV command to have the same register as the final output }
  9007. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9008. else
  9009. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9010. { Change second MOV command to an ADD command. This is easier than
  9011. converting the existing command because it means we don't have to
  9012. touch 'y', which might be a complicated reference, and also the
  9013. fact that the third command might either be ADD or LEA. [Kit] }
  9014. taicpu(hp1).opcode := A_ADD;
  9015. { Delete old ADD/LEA instruction }
  9016. RemoveInstruction(hp2);
  9017. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9018. taicpu(hp3).opcode := A_RCR;
  9019. taicpu(hp3).changeopsize(S_L);
  9020. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9021. {$endif x86_64}
  9022. end;
  9023. if FuncMov2Func(p, hp1) then
  9024. begin
  9025. Result := True;
  9026. Exit;
  9027. end;
  9028. end;
  9029. {$push}
  9030. {$q-}{$r-}
  9031. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9032. var
  9033. ThisReg: TRegister;
  9034. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9035. TargetSubReg: TSubRegister;
  9036. hp1, hp2: tai;
  9037. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9038. { Store list of found instructions so we don't have to call
  9039. GetNextInstructionUsingReg multiple times }
  9040. InstrList: array of taicpu;
  9041. InstrMax, Index: Integer;
  9042. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9043. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9044. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9045. WorkingValue: TCgInt;
  9046. PreMessage: string;
  9047. { Data flow analysis }
  9048. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9049. BitwiseOnly, OrXorUsed,
  9050. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9051. function CheckOverflowConditions: Boolean;
  9052. begin
  9053. Result := True;
  9054. if (TestValSignedMax > SignedUpperLimit) then
  9055. UpperSignedOverflow := True;
  9056. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9057. LowerSignedOverflow := True;
  9058. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9059. LowerUnsignedOverflow := True;
  9060. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9061. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9062. begin
  9063. { Absolute overflow }
  9064. Result := False;
  9065. Exit;
  9066. end;
  9067. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9068. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9069. ShiftDownOverflow := True;
  9070. if (TestValMin < 0) or (TestValMax < 0) then
  9071. begin
  9072. LowerUnsignedOverflow := True;
  9073. UpperUnsignedOverflow := True;
  9074. end;
  9075. end;
  9076. function AdjustInitialLoadAndSize: Boolean;
  9077. begin
  9078. Result := False;
  9079. if not p_removed then
  9080. begin
  9081. if TargetSize = MinSize then
  9082. begin
  9083. { Convert the input MOVZX to a MOV }
  9084. if (taicpu(p).oper[0]^.typ = top_reg) and
  9085. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9086. begin
  9087. { Or remove it completely! }
  9088. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9089. RemoveCurrentP(p);
  9090. p_removed := True;
  9091. end
  9092. else
  9093. begin
  9094. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9095. taicpu(p).opcode := A_MOV;
  9096. taicpu(p).oper[1]^.reg := ThisReg;
  9097. taicpu(p).opsize := TargetSize;
  9098. end;
  9099. Result := True;
  9100. end
  9101. else if TargetSize <> MaxSize then
  9102. begin
  9103. case MaxSize of
  9104. S_L:
  9105. if TargetSize = S_W then
  9106. begin
  9107. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9108. taicpu(p).opsize := S_BW;
  9109. taicpu(p).oper[1]^.reg := ThisReg;
  9110. Result := True;
  9111. end
  9112. else
  9113. InternalError(2020112341);
  9114. S_W:
  9115. if TargetSize = S_L then
  9116. begin
  9117. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9118. taicpu(p).opsize := S_BL;
  9119. taicpu(p).oper[1]^.reg := ThisReg;
  9120. Result := True;
  9121. end
  9122. else
  9123. InternalError(2020112342);
  9124. else
  9125. ;
  9126. end;
  9127. end
  9128. else if not hp1_removed and not RegInUse then
  9129. begin
  9130. { If we have something like:
  9131. movzbl (oper),%regd
  9132. add x, %regd
  9133. movzbl %regb, %regd
  9134. We can reduce the register size to the input of the final
  9135. movzbl instruction. Overflows won't have any effect.
  9136. }
  9137. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9138. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9139. begin
  9140. TargetSize := S_B;
  9141. setsubreg(ThisReg, R_SUBL);
  9142. Result := True;
  9143. end
  9144. else if (taicpu(p).opsize = S_WL) and
  9145. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9146. begin
  9147. TargetSize := S_W;
  9148. setsubreg(ThisReg, R_SUBW);
  9149. Result := True;
  9150. end;
  9151. if Result then
  9152. begin
  9153. { Convert the input MOVZX to a MOV }
  9154. if (taicpu(p).oper[0]^.typ = top_reg) and
  9155. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9156. begin
  9157. { Or remove it completely! }
  9158. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9159. RemoveCurrentP(p);
  9160. p_removed := True;
  9161. end
  9162. else
  9163. begin
  9164. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9165. taicpu(p).opcode := A_MOV;
  9166. taicpu(p).oper[1]^.reg := ThisReg;
  9167. taicpu(p).opsize := TargetSize;
  9168. end;
  9169. end;
  9170. end;
  9171. end;
  9172. end;
  9173. procedure AdjustFinalLoad;
  9174. begin
  9175. if not LowerUnsignedOverflow then
  9176. begin
  9177. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9178. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9179. begin
  9180. { Convert the output MOVZX to a MOV }
  9181. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9182. begin
  9183. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9184. if (MinSize = S_B) or
  9185. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9186. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9187. begin
  9188. { Remove it completely! }
  9189. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9190. { Be careful; if p = hp1 and p was also removed, p
  9191. will become a dangling pointer }
  9192. if p = hp1 then
  9193. begin
  9194. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9195. p_removed := True;
  9196. end
  9197. else
  9198. RemoveInstruction(hp1);
  9199. hp1_removed := True;
  9200. end;
  9201. end
  9202. else
  9203. begin
  9204. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9205. taicpu(hp1).opcode := A_MOV;
  9206. taicpu(hp1).oper[0]^.reg := ThisReg;
  9207. taicpu(hp1).opsize := TargetSize;
  9208. end;
  9209. end
  9210. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9211. begin
  9212. { Need to change the size of the output }
  9213. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9214. taicpu(hp1).oper[0]^.reg := ThisReg;
  9215. taicpu(hp1).opsize := S_BL;
  9216. end;
  9217. end;
  9218. end;
  9219. function CompressInstructions: Boolean;
  9220. var
  9221. LocalIndex: Integer;
  9222. begin
  9223. Result := False;
  9224. { The objective here is to try to find a combination that
  9225. removes one of the MOV/Z instructions. }
  9226. if (
  9227. (taicpu(p).oper[0]^.typ <> top_reg) or
  9228. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9229. ) and
  9230. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9231. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9232. begin
  9233. { Make a preference to remove the second MOVZX instruction }
  9234. case taicpu(hp1).opsize of
  9235. S_BL, S_WL:
  9236. begin
  9237. TargetSize := S_L;
  9238. TargetSubReg := R_SUBD;
  9239. end;
  9240. S_BW:
  9241. begin
  9242. TargetSize := S_W;
  9243. TargetSubReg := R_SUBW;
  9244. end;
  9245. else
  9246. InternalError(2020112302);
  9247. end;
  9248. end
  9249. else
  9250. begin
  9251. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9252. begin
  9253. { Exceeded lower bound but not upper bound }
  9254. TargetSize := MaxSize;
  9255. end
  9256. else if not LowerUnsignedOverflow then
  9257. begin
  9258. { Size didn't exceed lower bound }
  9259. TargetSize := MinSize;
  9260. end
  9261. else
  9262. Exit;
  9263. end;
  9264. case TargetSize of
  9265. S_B:
  9266. TargetSubReg := R_SUBL;
  9267. S_W:
  9268. TargetSubReg := R_SUBW;
  9269. S_L:
  9270. TargetSubReg := R_SUBD;
  9271. else
  9272. InternalError(2020112350);
  9273. end;
  9274. { Update the register to its new size }
  9275. setsubreg(ThisReg, TargetSubReg);
  9276. RegInUse := False;
  9277. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9278. begin
  9279. { Check to see if the active register is used afterwards;
  9280. if not, we can change it and make a saving. }
  9281. TransferUsedRegs(TmpUsedRegs);
  9282. { The target register may be marked as in use to cross
  9283. a jump to a distant label, so exclude it }
  9284. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9285. hp2 := p;
  9286. repeat
  9287. { Explicitly check for the excluded register (don't include the first
  9288. instruction as it may be reading from here }
  9289. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9290. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9291. begin
  9292. RegInUse := True;
  9293. Break;
  9294. end;
  9295. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9296. if not GetNextInstruction(hp2, hp2) then
  9297. InternalError(2020112340);
  9298. until (hp2 = hp1);
  9299. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9300. { We might still be able to get away with this }
  9301. RegInUse := not
  9302. (
  9303. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9304. (hp2.typ = ait_instruction) and
  9305. (
  9306. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9307. instruction that doesn't actually contain ThisReg }
  9308. (cs_opt_level3 in current_settings.optimizerswitches) or
  9309. RegInInstruction(ThisReg, hp2)
  9310. ) and
  9311. RegLoadedWithNewValue(ThisReg, hp2)
  9312. );
  9313. if not RegInUse then
  9314. begin
  9315. { Force the register size to the same as this instruction so it can be removed}
  9316. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9317. begin
  9318. TargetSize := S_L;
  9319. TargetSubReg := R_SUBD;
  9320. end
  9321. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9322. begin
  9323. TargetSize := S_W;
  9324. TargetSubReg := R_SUBW;
  9325. end;
  9326. ThisReg := taicpu(hp1).oper[1]^.reg;
  9327. setsubreg(ThisReg, TargetSubReg);
  9328. RegChanged := True;
  9329. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9330. TransferUsedRegs(TmpUsedRegs);
  9331. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9332. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9333. if p = hp1 then
  9334. begin
  9335. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9336. p_removed := True;
  9337. end
  9338. else
  9339. RemoveInstruction(hp1);
  9340. hp1_removed := True;
  9341. { Instruction will become "mov %reg,%reg" }
  9342. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9343. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9344. begin
  9345. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9346. RemoveCurrentP(p);
  9347. p_removed := True;
  9348. end
  9349. else
  9350. taicpu(p).oper[1]^.reg := ThisReg;
  9351. Result := True;
  9352. end
  9353. else
  9354. begin
  9355. if TargetSize <> MaxSize then
  9356. begin
  9357. { Since the register is in use, we have to force it to
  9358. MaxSize otherwise part of it may become undefined later on }
  9359. TargetSize := MaxSize;
  9360. case TargetSize of
  9361. S_B:
  9362. TargetSubReg := R_SUBL;
  9363. S_W:
  9364. TargetSubReg := R_SUBW;
  9365. S_L:
  9366. TargetSubReg := R_SUBD;
  9367. else
  9368. InternalError(2020112351);
  9369. end;
  9370. setsubreg(ThisReg, TargetSubReg);
  9371. end;
  9372. AdjustFinalLoad;
  9373. end;
  9374. end
  9375. else
  9376. AdjustFinalLoad;
  9377. Result := AdjustInitialLoadAndSize or Result;
  9378. { Now go through every instruction we found and change the
  9379. size. If TargetSize = MaxSize, then almost no changes are
  9380. needed and Result can remain False if it hasn't been set
  9381. yet.
  9382. If RegChanged is True, then the register requires changing
  9383. and so the point about TargetSize = MaxSize doesn't apply. }
  9384. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9385. begin
  9386. for LocalIndex := 0 to InstrMax do
  9387. begin
  9388. { If p_removed is true, then the original MOV/Z was removed
  9389. and removing the AND instruction may not be safe if it
  9390. appears first }
  9391. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9392. InternalError(2020112310);
  9393. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9394. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9395. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9396. InstrList[LocalIndex].opsize := TargetSize;
  9397. end;
  9398. Result := True;
  9399. end;
  9400. end;
  9401. begin
  9402. Result := False;
  9403. p_removed := False;
  9404. hp1_removed := False;
  9405. ThisReg := taicpu(p).oper[1]^.reg;
  9406. { Check for:
  9407. movs/z ###,%ecx (or %cx or %rcx)
  9408. ...
  9409. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9410. (dealloc %ecx)
  9411. Change to:
  9412. mov ###,%cl (if ### = %cl, then remove completely)
  9413. ...
  9414. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9415. }
  9416. if (getsupreg(ThisReg) = RS_ECX) and
  9417. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9418. (hp1.typ = ait_instruction) and
  9419. (
  9420. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9421. instruction that doesn't actually contain ECX }
  9422. (cs_opt_level3 in current_settings.optimizerswitches) or
  9423. RegInInstruction(NR_ECX, hp1) or
  9424. (
  9425. { It's common for the shift/rotate's read/write register to be
  9426. initialised in between, so under -O2 and under, search ahead
  9427. one more instruction
  9428. }
  9429. GetNextInstruction(hp1, hp1) and
  9430. (hp1.typ = ait_instruction) and
  9431. RegInInstruction(NR_ECX, hp1)
  9432. )
  9433. ) and
  9434. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9435. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9436. begin
  9437. TransferUsedRegs(TmpUsedRegs);
  9438. hp2 := p;
  9439. repeat
  9440. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9441. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9442. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9443. begin
  9444. case taicpu(p).opsize of
  9445. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9446. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9447. begin
  9448. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9449. RemoveCurrentP(p);
  9450. end
  9451. else
  9452. begin
  9453. taicpu(p).opcode := A_MOV;
  9454. taicpu(p).opsize := S_B;
  9455. taicpu(p).oper[1]^.reg := NR_CL;
  9456. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9457. end;
  9458. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9459. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9460. begin
  9461. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9462. RemoveCurrentP(p);
  9463. end
  9464. else
  9465. begin
  9466. taicpu(p).opcode := A_MOV;
  9467. taicpu(p).opsize := S_W;
  9468. taicpu(p).oper[1]^.reg := NR_CX;
  9469. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9470. end;
  9471. {$ifdef x86_64}
  9472. S_LQ:
  9473. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9474. begin
  9475. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9476. RemoveCurrentP(p);
  9477. end
  9478. else
  9479. begin
  9480. taicpu(p).opcode := A_MOV;
  9481. taicpu(p).opsize := S_L;
  9482. taicpu(p).oper[1]^.reg := NR_ECX;
  9483. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9484. end;
  9485. {$endif x86_64}
  9486. else
  9487. InternalError(2021120401);
  9488. end;
  9489. Result := True;
  9490. Exit;
  9491. end;
  9492. end;
  9493. { This is anything but quick! }
  9494. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9495. Exit;
  9496. SetLength(InstrList, 0);
  9497. InstrMax := -1;
  9498. case taicpu(p).opsize of
  9499. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9500. begin
  9501. {$if defined(i386) or defined(i8086)}
  9502. { If the target size is 8-bit, make sure we can actually encode it }
  9503. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9504. Exit;
  9505. {$endif i386 or i8086}
  9506. LowerLimit := $FF;
  9507. SignedLowerLimit := $7F;
  9508. SignedLowerLimitBottom := -128;
  9509. MinSize := S_B;
  9510. if taicpu(p).opsize = S_BW then
  9511. begin
  9512. MaxSize := S_W;
  9513. UpperLimit := $FFFF;
  9514. SignedUpperLimit := $7FFF;
  9515. SignedUpperLimitBottom := -32768;
  9516. end
  9517. else
  9518. begin
  9519. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9520. MaxSize := S_L;
  9521. UpperLimit := $FFFFFFFF;
  9522. SignedUpperLimit := $7FFFFFFF;
  9523. SignedUpperLimitBottom := -2147483648;
  9524. end;
  9525. end;
  9526. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9527. begin
  9528. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9529. LowerLimit := $FFFF;
  9530. SignedLowerLimit := $7FFF;
  9531. SignedLowerLimitBottom := -32768;
  9532. UpperLimit := $FFFFFFFF;
  9533. SignedUpperLimit := $7FFFFFFF;
  9534. SignedUpperLimitBottom := -2147483648;
  9535. MinSize := S_W;
  9536. MaxSize := S_L;
  9537. end;
  9538. {$ifdef x86_64}
  9539. S_LQ:
  9540. begin
  9541. { Both the lower and upper limits are set to 32-bit. If a limit
  9542. is breached, then optimisation is impossible }
  9543. LowerLimit := $FFFFFFFF;
  9544. SignedLowerLimit := $7FFFFFFF;
  9545. SignedLowerLimitBottom := -2147483648;
  9546. UpperLimit := $FFFFFFFF;
  9547. SignedUpperLimit := $7FFFFFFF;
  9548. SignedUpperLimitBottom := -2147483648;
  9549. MinSize := S_L;
  9550. MaxSize := S_L;
  9551. end;
  9552. {$endif x86_64}
  9553. else
  9554. InternalError(2020112301);
  9555. end;
  9556. TestValMin := 0;
  9557. TestValMax := LowerLimit;
  9558. TestValSignedMax := SignedLowerLimit;
  9559. TryShiftDownLimit := LowerLimit;
  9560. TryShiftDown := S_NO;
  9561. ShiftDownOverflow := False;
  9562. RegChanged := False;
  9563. BitwiseOnly := True;
  9564. OrXorUsed := False;
  9565. UpperSignedOverflow := False;
  9566. LowerSignedOverflow := False;
  9567. UpperUnsignedOverflow := False;
  9568. LowerUnsignedOverflow := False;
  9569. hp1 := p;
  9570. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9571. (hp1.typ = ait_instruction) and
  9572. (
  9573. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9574. instruction that doesn't actually contain ThisReg }
  9575. (cs_opt_level3 in current_settings.optimizerswitches) or
  9576. { This allows this Movx optimisation to work through the SETcc instructions
  9577. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9578. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9579. skip over these SETcc instructions). }
  9580. (taicpu(hp1).opcode = A_SETcc) or
  9581. RegInInstruction(ThisReg, hp1)
  9582. ) do
  9583. begin
  9584. case taicpu(hp1).opcode of
  9585. A_INC,A_DEC:
  9586. begin
  9587. { Has to be an exact match on the register }
  9588. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9589. Break;
  9590. if taicpu(hp1).opcode = A_INC then
  9591. begin
  9592. Inc(TestValMin);
  9593. Inc(TestValMax);
  9594. Inc(TestValSignedMax);
  9595. end
  9596. else
  9597. begin
  9598. Dec(TestValMin);
  9599. Dec(TestValMax);
  9600. Dec(TestValSignedMax);
  9601. end;
  9602. end;
  9603. A_TEST, A_CMP:
  9604. begin
  9605. if (
  9606. { Too high a risk of non-linear behaviour that breaks DFA
  9607. here, unless it's cmp $0,%reg, which is equivalent to
  9608. test %reg,%reg }
  9609. OrXorUsed and
  9610. (taicpu(hp1).opcode = A_CMP) and
  9611. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9612. ) or
  9613. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9614. { Has to be an exact match on the register }
  9615. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9616. (
  9617. { Permit "test %reg,%reg" }
  9618. (taicpu(hp1).opcode = A_TEST) and
  9619. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9620. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9621. ) or
  9622. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9623. { Make sure the comparison value is not smaller than the
  9624. smallest allowed signed value for the minimum size (e.g.
  9625. -128 for 8-bit) }
  9626. not (
  9627. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9628. { Is it in the negative range? }
  9629. (
  9630. (taicpu(hp1).oper[0]^.val < 0) and
  9631. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9632. )
  9633. ) then
  9634. Break;
  9635. { Check to see if the active register is used afterwards }
  9636. TransferUsedRegs(TmpUsedRegs);
  9637. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9638. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9639. begin
  9640. { Make sure the comparison or any previous instructions
  9641. hasn't pushed the test values outside of the range of
  9642. MinSize }
  9643. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9644. begin
  9645. { Exceeded lower bound but not upper bound }
  9646. Exit;
  9647. end
  9648. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9649. begin
  9650. { Size didn't exceed lower bound }
  9651. TargetSize := MinSize;
  9652. end
  9653. else
  9654. Break;
  9655. case TargetSize of
  9656. S_B:
  9657. TargetSubReg := R_SUBL;
  9658. S_W:
  9659. TargetSubReg := R_SUBW;
  9660. S_L:
  9661. TargetSubReg := R_SUBD;
  9662. else
  9663. InternalError(2021051002);
  9664. end;
  9665. if TargetSize <> MaxSize then
  9666. begin
  9667. { Update the register to its new size }
  9668. setsubreg(ThisReg, TargetSubReg);
  9669. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9670. taicpu(hp1).oper[1]^.reg := ThisReg;
  9671. taicpu(hp1).opsize := TargetSize;
  9672. { Convert the input MOVZX to a MOV if necessary }
  9673. AdjustInitialLoadAndSize;
  9674. if (InstrMax >= 0) then
  9675. begin
  9676. for Index := 0 to InstrMax do
  9677. begin
  9678. { If p_removed is true, then the original MOV/Z was removed
  9679. and removing the AND instruction may not be safe if it
  9680. appears first }
  9681. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9682. InternalError(2020112311);
  9683. if InstrList[Index].oper[0]^.typ = top_reg then
  9684. InstrList[Index].oper[0]^.reg := ThisReg;
  9685. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9686. InstrList[Index].opsize := MinSize;
  9687. end;
  9688. end;
  9689. Result := True;
  9690. end;
  9691. Exit;
  9692. end;
  9693. end;
  9694. A_SETcc:
  9695. begin
  9696. { This allows this Movx optimisation to work through the SETcc instructions
  9697. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9698. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9699. skip over these SETcc instructions). }
  9700. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9701. { Of course, break out if the current register is used }
  9702. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9703. Break
  9704. else
  9705. { We must use Continue so the instruction doesn't get added
  9706. to InstrList }
  9707. Continue;
  9708. end;
  9709. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9710. begin
  9711. if
  9712. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9713. { Has to be an exact match on the register }
  9714. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9715. (
  9716. (
  9717. (taicpu(hp1).oper[0]^.typ = top_const) and
  9718. (
  9719. (
  9720. (taicpu(hp1).opcode = A_SHL) and
  9721. (
  9722. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9723. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9724. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9725. )
  9726. ) or (
  9727. (taicpu(hp1).opcode <> A_SHL) and
  9728. (
  9729. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9730. { Is it in the negative range? }
  9731. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9732. )
  9733. )
  9734. )
  9735. ) or (
  9736. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9737. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9738. )
  9739. ) then
  9740. Break;
  9741. { Only process OR and XOR if there are only bitwise operations,
  9742. since otherwise they can too easily fool the data flow
  9743. analysis (they can cause non-linear behaviour) }
  9744. case taicpu(hp1).opcode of
  9745. A_ADD:
  9746. begin
  9747. if OrXorUsed then
  9748. { Too high a risk of non-linear behaviour that breaks DFA here }
  9749. Break
  9750. else
  9751. BitwiseOnly := False;
  9752. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9753. begin
  9754. TestValMin := TestValMin * 2;
  9755. TestValMax := TestValMax * 2;
  9756. TestValSignedMax := TestValSignedMax * 2;
  9757. end
  9758. else
  9759. begin
  9760. WorkingValue := taicpu(hp1).oper[0]^.val;
  9761. TestValMin := TestValMin + WorkingValue;
  9762. TestValMax := TestValMax + WorkingValue;
  9763. TestValSignedMax := TestValSignedMax + WorkingValue;
  9764. end;
  9765. end;
  9766. A_SUB:
  9767. begin
  9768. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9769. begin
  9770. TestValMin := 0;
  9771. TestValMax := 0;
  9772. TestValSignedMax := 0;
  9773. end
  9774. else
  9775. begin
  9776. if OrXorUsed then
  9777. { Too high a risk of non-linear behaviour that breaks DFA here }
  9778. Break
  9779. else
  9780. BitwiseOnly := False;
  9781. WorkingValue := taicpu(hp1).oper[0]^.val;
  9782. TestValMin := TestValMin - WorkingValue;
  9783. TestValMax := TestValMax - WorkingValue;
  9784. TestValSignedMax := TestValSignedMax - WorkingValue;
  9785. end;
  9786. end;
  9787. A_AND:
  9788. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9789. begin
  9790. { we might be able to go smaller if AND appears first }
  9791. if InstrMax = -1 then
  9792. case MinSize of
  9793. S_B:
  9794. ;
  9795. S_W:
  9796. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9797. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9798. begin
  9799. TryShiftDown := S_B;
  9800. TryShiftDownLimit := $FF;
  9801. end;
  9802. S_L:
  9803. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9804. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9805. begin
  9806. TryShiftDown := S_B;
  9807. TryShiftDownLimit := $FF;
  9808. end
  9809. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9810. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9811. begin
  9812. TryShiftDown := S_W;
  9813. TryShiftDownLimit := $FFFF;
  9814. end;
  9815. else
  9816. InternalError(2020112320);
  9817. end;
  9818. WorkingValue := taicpu(hp1).oper[0]^.val;
  9819. TestValMin := TestValMin and WorkingValue;
  9820. TestValMax := TestValMax and WorkingValue;
  9821. TestValSignedMax := TestValSignedMax and WorkingValue;
  9822. end;
  9823. A_OR:
  9824. begin
  9825. if not BitwiseOnly then
  9826. Break;
  9827. OrXorUsed := True;
  9828. WorkingValue := taicpu(hp1).oper[0]^.val;
  9829. TestValMin := TestValMin or WorkingValue;
  9830. TestValMax := TestValMax or WorkingValue;
  9831. TestValSignedMax := TestValSignedMax or WorkingValue;
  9832. end;
  9833. A_XOR:
  9834. begin
  9835. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9836. begin
  9837. TestValMin := 0;
  9838. TestValMax := 0;
  9839. TestValSignedMax := 0;
  9840. end
  9841. else
  9842. begin
  9843. if not BitwiseOnly then
  9844. Break;
  9845. OrXorUsed := True;
  9846. WorkingValue := taicpu(hp1).oper[0]^.val;
  9847. TestValMin := TestValMin xor WorkingValue;
  9848. TestValMax := TestValMax xor WorkingValue;
  9849. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9850. end;
  9851. end;
  9852. A_SHL:
  9853. begin
  9854. BitwiseOnly := False;
  9855. WorkingValue := taicpu(hp1).oper[0]^.val;
  9856. TestValMin := TestValMin shl WorkingValue;
  9857. TestValMax := TestValMax shl WorkingValue;
  9858. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9859. end;
  9860. A_SHR,
  9861. { The first instruction was MOVZX, so the value won't be negative }
  9862. A_SAR:
  9863. begin
  9864. if InstrMax <> -1 then
  9865. BitwiseOnly := False
  9866. else
  9867. { we might be able to go smaller if SHR appears first }
  9868. case MinSize of
  9869. S_B:
  9870. ;
  9871. S_W:
  9872. if (taicpu(hp1).oper[0]^.val >= 8) then
  9873. begin
  9874. TryShiftDown := S_B;
  9875. TryShiftDownLimit := $FF;
  9876. TryShiftDownSignedLimit := $7F;
  9877. TryShiftDownSignedLimitLower := -128;
  9878. end;
  9879. S_L:
  9880. if (taicpu(hp1).oper[0]^.val >= 24) then
  9881. begin
  9882. TryShiftDown := S_B;
  9883. TryShiftDownLimit := $FF;
  9884. TryShiftDownSignedLimit := $7F;
  9885. TryShiftDownSignedLimitLower := -128;
  9886. end
  9887. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9888. begin
  9889. TryShiftDown := S_W;
  9890. TryShiftDownLimit := $FFFF;
  9891. TryShiftDownSignedLimit := $7FFF;
  9892. TryShiftDownSignedLimitLower := -32768;
  9893. end;
  9894. else
  9895. InternalError(2020112321);
  9896. end;
  9897. WorkingValue := taicpu(hp1).oper[0]^.val;
  9898. if taicpu(hp1).opcode = A_SAR then
  9899. begin
  9900. TestValMin := SarInt64(TestValMin, WorkingValue);
  9901. TestValMax := SarInt64(TestValMax, WorkingValue);
  9902. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9903. end
  9904. else
  9905. begin
  9906. TestValMin := TestValMin shr WorkingValue;
  9907. TestValMax := TestValMax shr WorkingValue;
  9908. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9909. end;
  9910. end;
  9911. else
  9912. InternalError(2020112303);
  9913. end;
  9914. end;
  9915. (*
  9916. A_IMUL:
  9917. case taicpu(hp1).ops of
  9918. 2:
  9919. begin
  9920. if not MatchOpType(hp1, top_reg, top_reg) or
  9921. { Has to be an exact match on the register }
  9922. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9923. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9924. Break;
  9925. TestValMin := TestValMin * TestValMin;
  9926. TestValMax := TestValMax * TestValMax;
  9927. TestValSignedMax := TestValSignedMax * TestValMax;
  9928. end;
  9929. 3:
  9930. begin
  9931. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9932. { Has to be an exact match on the register }
  9933. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9934. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9935. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9936. { Is it in the negative range? }
  9937. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9938. Break;
  9939. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9940. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9941. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9942. end;
  9943. else
  9944. Break;
  9945. end;
  9946. A_IDIV:
  9947. case taicpu(hp1).ops of
  9948. 3:
  9949. begin
  9950. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9951. { Has to be an exact match on the register }
  9952. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9953. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9954. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9955. { Is it in the negative range? }
  9956. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9957. Break;
  9958. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9959. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9960. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9961. end;
  9962. else
  9963. Break;
  9964. end;
  9965. *)
  9966. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9967. begin
  9968. { If there are no instructions in between, then we might be able to make a saving }
  9969. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9970. Break;
  9971. { We have something like:
  9972. movzbw %dl,%dx
  9973. ...
  9974. movswl %dx,%edx
  9975. Change the latter to a zero-extension then enter the
  9976. A_MOVZX case branch.
  9977. }
  9978. {$ifdef x86_64}
  9979. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9980. begin
  9981. { this becomes a zero extension from 32-bit to 64-bit, but
  9982. the upper 32 bits are already zero, so just delete the
  9983. instruction }
  9984. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9985. RemoveInstruction(hp1);
  9986. Result := True;
  9987. Exit;
  9988. end
  9989. else
  9990. {$endif x86_64}
  9991. begin
  9992. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9993. taicpu(hp1).opcode := A_MOVZX;
  9994. {$ifdef x86_64}
  9995. case taicpu(hp1).opsize of
  9996. S_BQ:
  9997. begin
  9998. taicpu(hp1).opsize := S_BL;
  9999. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10000. end;
  10001. S_WQ:
  10002. begin
  10003. taicpu(hp1).opsize := S_WL;
  10004. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10005. end;
  10006. S_LQ:
  10007. begin
  10008. taicpu(hp1).opcode := A_MOV;
  10009. taicpu(hp1).opsize := S_L;
  10010. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10011. { In this instance, we need to break out because the
  10012. instruction is no longer MOVZX or MOVSXD }
  10013. Result := True;
  10014. Exit;
  10015. end;
  10016. else
  10017. ;
  10018. end;
  10019. {$endif x86_64}
  10020. Result := CompressInstructions;
  10021. Exit;
  10022. end;
  10023. end;
  10024. A_MOVZX:
  10025. begin
  10026. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10027. Break;
  10028. if (InstrMax = -1) then
  10029. begin
  10030. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10031. begin
  10032. { Optimise around i40003 }
  10033. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10034. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10035. {$ifndef x86_64}
  10036. and (
  10037. (taicpu(p).oper[0]^.typ <> top_reg) or
  10038. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10039. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10040. )
  10041. {$endif not x86_64}
  10042. then
  10043. begin
  10044. if (taicpu(p).oper[0]^.typ = top_reg) then
  10045. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10046. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10047. taicpu(p).opsize := S_BL;
  10048. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10049. RemoveInstruction(hp1);
  10050. Result := True;
  10051. Exit;
  10052. end;
  10053. end
  10054. else
  10055. begin
  10056. { Will return false if the second parameter isn't ThisReg
  10057. (can happen on -O2 and under) }
  10058. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10059. begin
  10060. { The two MOVZX instructions are adjacent, so remove the first one }
  10061. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10062. RemoveCurrentP(p);
  10063. Result := True;
  10064. Exit;
  10065. end;
  10066. Break;
  10067. end;
  10068. end;
  10069. Result := CompressInstructions;
  10070. Exit;
  10071. end;
  10072. else
  10073. { This includes ADC, SBB and IDIV }
  10074. Break;
  10075. end;
  10076. if not CheckOverflowConditions then
  10077. Break;
  10078. { Contains highest index (so instruction count - 1) }
  10079. Inc(InstrMax);
  10080. if InstrMax > High(InstrList) then
  10081. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10082. InstrList[InstrMax] := taicpu(hp1);
  10083. end;
  10084. end;
  10085. {$pop}
  10086. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10087. var
  10088. hp1 : tai;
  10089. begin
  10090. Result:=false;
  10091. if (taicpu(p).ops >= 2) and
  10092. ((taicpu(p).oper[0]^.typ = top_const) or
  10093. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10094. (taicpu(p).oper[1]^.typ = top_reg) and
  10095. ((taicpu(p).ops = 2) or
  10096. ((taicpu(p).oper[2]^.typ = top_reg) and
  10097. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10098. GetLastInstruction(p,hp1) and
  10099. MatchInstruction(hp1,A_MOV,[]) and
  10100. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10101. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10102. begin
  10103. TransferUsedRegs(TmpUsedRegs);
  10104. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10105. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10106. { change
  10107. mov reg1,reg2
  10108. imul y,reg2 to imul y,reg1,reg2 }
  10109. begin
  10110. taicpu(p).ops := 3;
  10111. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10112. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10113. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10114. RemoveInstruction(hp1);
  10115. result:=true;
  10116. end;
  10117. end;
  10118. end;
  10119. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10120. var
  10121. ThisLabel: TAsmLabel;
  10122. begin
  10123. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10124. ThisLabel.decrefs;
  10125. taicpu(p).condition := C_None;
  10126. taicpu(p).opcode := A_RET;
  10127. taicpu(p).is_jmp := false;
  10128. taicpu(p).ops := taicpu(ret_p).ops;
  10129. case taicpu(ret_p).ops of
  10130. 0:
  10131. taicpu(p).clearop(0);
  10132. 1:
  10133. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10134. else
  10135. internalerror(2016041301);
  10136. end;
  10137. { If the original label is now dead, it might turn out that the label
  10138. immediately follows p. As a result, everything beyond it, which will
  10139. be just some final register configuration and a RET instruction, is
  10140. now dead code. [Kit] }
  10141. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10142. running RemoveDeadCodeAfterJump for each RET instruction, because
  10143. this optimisation rarely happens and most RETs appear at the end of
  10144. routines where there is nothing that can be stripped. [Kit] }
  10145. if not ThisLabel.is_used then
  10146. RemoveDeadCodeAfterJump(p);
  10147. end;
  10148. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10149. var
  10150. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10151. Unconditional, PotentialModified: Boolean;
  10152. OperPtr: POper;
  10153. NewRef: TReference;
  10154. InstrList: array of taicpu;
  10155. InstrMax, Index: Integer;
  10156. const
  10157. {$ifdef DEBUG_AOPTCPU}
  10158. SNoFlags: shortstring = ' so the flags aren''t modified';
  10159. {$else DEBUG_AOPTCPU}
  10160. SNoFlags = '';
  10161. {$endif DEBUG_AOPTCPU}
  10162. begin
  10163. Result:=false;
  10164. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10165. begin
  10166. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10167. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10168. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10169. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10170. GetNextInstruction(hp1, hp2) and
  10171. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10172. { Change from: To:
  10173. set(C) %reg j(~C) label
  10174. test %reg,%reg/cmp $0,%reg
  10175. je label
  10176. set(C) %reg j(C) label
  10177. test %reg,%reg/cmp $0,%reg
  10178. jne label
  10179. (Also do something similar with sete/setne instead of je/jne)
  10180. }
  10181. begin
  10182. { Before we do anything else, we need to check the instructions
  10183. in between SETcc and TEST to make sure they don't modify the
  10184. FLAGS register - if -O2 or under, there won't be any
  10185. instructions between SET and TEST }
  10186. TransferUsedRegs(TmpUsedRegs);
  10187. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10188. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10189. begin
  10190. next := p;
  10191. SetLength(InstrList, 0);
  10192. InstrMax := -1;
  10193. PotentialModified := False;
  10194. { Make a note of every instruction that modifies the FLAGS
  10195. register }
  10196. while GetNextInstruction(next, next) and (next <> hp1) do
  10197. begin
  10198. if next.typ <> ait_instruction then
  10199. { GetNextInstructionUsingReg should have returned False }
  10200. InternalError(2021051701);
  10201. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10202. begin
  10203. case taicpu(next).opcode of
  10204. A_SETcc,
  10205. A_CMOVcc,
  10206. A_Jcc:
  10207. begin
  10208. if PotentialModified then
  10209. { Not safe because the flags were modified earlier }
  10210. Exit
  10211. else
  10212. { Condition is the same as the initial SETcc, so this is safe
  10213. (don't add to instruction list though) }
  10214. Continue;
  10215. end;
  10216. A_ADD:
  10217. begin
  10218. if (taicpu(next).opsize = S_B) or
  10219. { LEA doesn't support 8-bit operands }
  10220. (taicpu(next).oper[1]^.typ <> top_reg) or
  10221. { Must write to a register }
  10222. (taicpu(next).oper[0]^.typ = top_ref) then
  10223. { Require a constant or a register }
  10224. Exit;
  10225. PotentialModified := True;
  10226. end;
  10227. A_SUB:
  10228. begin
  10229. if (taicpu(next).opsize = S_B) or
  10230. { LEA doesn't support 8-bit operands }
  10231. (taicpu(next).oper[1]^.typ <> top_reg) or
  10232. { Must write to a register }
  10233. (taicpu(next).oper[0]^.typ <> top_const) or
  10234. (taicpu(next).oper[0]^.val = $80000000) then
  10235. { Can't subtract a register with LEA - also
  10236. check that the value isn't -2^31, as this
  10237. can't be negated }
  10238. Exit;
  10239. PotentialModified := True;
  10240. end;
  10241. A_SAL,
  10242. A_SHL:
  10243. begin
  10244. if (taicpu(next).opsize = S_B) or
  10245. { LEA doesn't support 8-bit operands }
  10246. (taicpu(next).oper[1]^.typ <> top_reg) or
  10247. { Must write to a register }
  10248. (taicpu(next).oper[0]^.typ <> top_const) or
  10249. (taicpu(next).oper[0]^.val < 0) or
  10250. (taicpu(next).oper[0]^.val > 3) then
  10251. Exit;
  10252. PotentialModified := True;
  10253. end;
  10254. A_IMUL:
  10255. begin
  10256. if (taicpu(next).ops <> 3) or
  10257. (taicpu(next).oper[1]^.typ <> top_reg) or
  10258. { Must write to a register }
  10259. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10260. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10261. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10262. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10263. Exit
  10264. else
  10265. PotentialModified := True;
  10266. end;
  10267. else
  10268. { Don't know how to change this, so abort }
  10269. Exit;
  10270. end;
  10271. { Contains highest index (so instruction count - 1) }
  10272. Inc(InstrMax);
  10273. if InstrMax > High(InstrList) then
  10274. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10275. InstrList[InstrMax] := taicpu(next);
  10276. end;
  10277. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10278. end;
  10279. if not Assigned(next) or (next <> hp1) then
  10280. { It should be equal to hp1 }
  10281. InternalError(2021051702);
  10282. { Cycle through each instruction and check to see if we can
  10283. change them to versions that don't modify the flags }
  10284. if (InstrMax >= 0) then
  10285. begin
  10286. for Index := 0 to InstrMax do
  10287. case InstrList[Index].opcode of
  10288. A_ADD:
  10289. begin
  10290. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10291. InstrList[Index].opcode := A_LEA;
  10292. reference_reset(NewRef, 1, []);
  10293. NewRef.base := InstrList[Index].oper[1]^.reg;
  10294. if InstrList[Index].oper[0]^.typ = top_reg then
  10295. begin
  10296. NewRef.index := InstrList[Index].oper[0]^.reg;
  10297. NewRef.scalefactor := 1;
  10298. end
  10299. else
  10300. NewRef.offset := InstrList[Index].oper[0]^.val;
  10301. InstrList[Index].loadref(0, NewRef);
  10302. end;
  10303. A_SUB:
  10304. begin
  10305. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10306. InstrList[Index].opcode := A_LEA;
  10307. reference_reset(NewRef, 1, []);
  10308. NewRef.base := InstrList[Index].oper[1]^.reg;
  10309. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10310. InstrList[Index].loadref(0, NewRef);
  10311. end;
  10312. A_SHL,
  10313. A_SAL:
  10314. begin
  10315. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10316. InstrList[Index].opcode := A_LEA;
  10317. reference_reset(NewRef, 1, []);
  10318. NewRef.index := InstrList[Index].oper[1]^.reg;
  10319. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10320. InstrList[Index].loadref(0, NewRef);
  10321. end;
  10322. A_IMUL:
  10323. begin
  10324. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10325. InstrList[Index].opcode := A_LEA;
  10326. reference_reset(NewRef, 1, []);
  10327. NewRef.index := InstrList[Index].oper[1]^.reg;
  10328. case InstrList[Index].oper[0]^.val of
  10329. 2, 4, 8:
  10330. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10331. else {3, 5 and 9}
  10332. begin
  10333. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10334. NewRef.base := InstrList[Index].oper[1]^.reg;
  10335. end;
  10336. end;
  10337. InstrList[Index].loadref(0, NewRef);
  10338. end;
  10339. else
  10340. InternalError(2021051710);
  10341. end;
  10342. end;
  10343. { Mark the FLAGS register as used across this whole block }
  10344. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10345. end;
  10346. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10347. JumpC := taicpu(hp2).condition;
  10348. Unconditional := False;
  10349. if conditions_equal(JumpC, C_E) then
  10350. SetC := inverse_cond(taicpu(p).condition)
  10351. else if conditions_equal(JumpC, C_NE) then
  10352. SetC := taicpu(p).condition
  10353. else
  10354. { We've got something weird here (and inefficent) }
  10355. begin
  10356. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10357. SetC := C_NONE;
  10358. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10359. if condition_in(C_AE, JumpC) then
  10360. Unconditional := True
  10361. else
  10362. { Not sure what to do with this jump - drop out }
  10363. Exit;
  10364. end;
  10365. RemoveInstruction(hp1);
  10366. if Unconditional then
  10367. MakeUnconditional(taicpu(hp2))
  10368. else
  10369. begin
  10370. if SetC = C_NONE then
  10371. InternalError(2018061402);
  10372. taicpu(hp2).SetCondition(SetC);
  10373. end;
  10374. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10375. TmpUsedRegs }
  10376. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10377. begin
  10378. RemoveCurrentp(p, hp2);
  10379. if taicpu(hp2).opcode = A_SETcc then
  10380. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10381. else
  10382. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10383. end
  10384. else
  10385. if taicpu(hp2).opcode = A_SETcc then
  10386. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10387. else
  10388. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10389. Result := True;
  10390. end
  10391. else if
  10392. { Make sure the instructions are adjacent }
  10393. (
  10394. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10395. GetNextInstruction(p, hp1)
  10396. ) and
  10397. MatchInstruction(hp1, A_MOV, [S_B]) and
  10398. { Writing to memory is allowed }
  10399. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10400. begin
  10401. {
  10402. Watch out for sequences such as:
  10403. set(c)b %regb
  10404. movb %regb,(ref)
  10405. movb $0,1(ref)
  10406. movb $0,2(ref)
  10407. movb $0,3(ref)
  10408. Much more efficient to turn it into:
  10409. movl $0,%regl
  10410. set(c)b %regb
  10411. movl %regl,(ref)
  10412. Or:
  10413. set(c)b %regb
  10414. movzbl %regb,%regl
  10415. movl %regl,(ref)
  10416. }
  10417. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10418. GetNextInstruction(hp1, hp2) and
  10419. MatchInstruction(hp2, A_MOV, [S_B]) and
  10420. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10421. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10422. begin
  10423. { Don't do anything else except set Result to True }
  10424. end
  10425. else
  10426. begin
  10427. if taicpu(p).oper[0]^.typ = top_reg then
  10428. begin
  10429. TransferUsedRegs(TmpUsedRegs);
  10430. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10431. end;
  10432. { If it's not a register, it's a memory address }
  10433. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10434. begin
  10435. { Even if the register is still in use, we can minimise the
  10436. pipeline stall by changing the MOV into another SETcc. }
  10437. taicpu(hp1).opcode := A_SETcc;
  10438. taicpu(hp1).condition := taicpu(p).condition;
  10439. if taicpu(hp1).oper[1]^.typ = top_ref then
  10440. begin
  10441. { Swapping the operand pointers like this is probably a
  10442. bit naughty, but it is far faster than using loadoper
  10443. to transfer the reference from oper[1] to oper[0] if
  10444. you take into account the extra procedure calls and
  10445. the memory allocation and deallocation required }
  10446. OperPtr := taicpu(hp1).oper[1];
  10447. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10448. taicpu(hp1).oper[0] := OperPtr;
  10449. end
  10450. else
  10451. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10452. taicpu(hp1).clearop(1);
  10453. taicpu(hp1).ops := 1;
  10454. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10455. end
  10456. else
  10457. begin
  10458. if taicpu(hp1).oper[1]^.typ = top_reg then
  10459. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10460. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10461. RemoveInstruction(hp1);
  10462. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10463. end
  10464. end;
  10465. Result := True;
  10466. end;
  10467. end;
  10468. end;
  10469. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10470. var
  10471. hp1: tai;
  10472. Count: Integer;
  10473. OrigLabel: TAsmLabel;
  10474. begin
  10475. result := False;
  10476. { Sometimes, the optimisations below can permit this }
  10477. RemoveDeadCodeAfterJump(p);
  10478. 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
  10479. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10480. begin
  10481. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10482. { Also a side-effect of optimisations }
  10483. if CollapseZeroDistJump(p, OrigLabel) then
  10484. begin
  10485. Result := True;
  10486. Exit;
  10487. end;
  10488. hp1 := GetLabelWithSym(OrigLabel);
  10489. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10490. begin
  10491. if taicpu(hp1).opcode = A_RET then
  10492. begin
  10493. {
  10494. change
  10495. jmp .L1
  10496. ...
  10497. .L1:
  10498. ret
  10499. into
  10500. ret
  10501. }
  10502. begin
  10503. ConvertJumpToRET(p, hp1);
  10504. result:=true;
  10505. end;
  10506. end
  10507. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10508. not (cs_opt_size in current_settings.optimizerswitches) and
  10509. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10510. begin
  10511. Result := True;
  10512. Exit;
  10513. end;
  10514. end;
  10515. end;
  10516. end;
  10517. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10518. begin
  10519. Result := assigned(p) and
  10520. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10521. (taicpu(p).oper[1]^.typ = top_reg) and
  10522. (
  10523. (taicpu(p).oper[0]^.typ = top_reg) or
  10524. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10525. it is not expected that this can cause a seg. violation }
  10526. (
  10527. (taicpu(p).oper[0]^.typ = top_ref) and
  10528. { TODO: Can we detect which references become constants at this
  10529. stage so we don't have to do a blanket ban? }
  10530. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10531. (
  10532. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10533. (
  10534. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10535. not RefModified and
  10536. { If the reference also appears in the condition, then we know it's safe, otherwise
  10537. any kind of access violation would have occurred already }
  10538. Assigned(cond_p) and
  10539. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10540. (cond_p.typ = ait_instruction) and
  10541. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10542. { Just consider 2-operand comparison instructions for now to be safe }
  10543. (taicpu(cond_p).ops = 2) and
  10544. (
  10545. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10546. (
  10547. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10548. { Don't risk identical registers but different offsets, as we may have constructs
  10549. such as buffer streams with things like length fields that indicate whether
  10550. any more data follows. And there are probably some contrived examples where
  10551. writing to offsets behind the one being read also lead to access violations }
  10552. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10553. (
  10554. { Check that we're not modifying a register that appears in the reference }
  10555. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10556. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10557. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10558. )
  10559. )
  10560. )
  10561. )
  10562. )
  10563. )
  10564. );
  10565. end;
  10566. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10567. begin
  10568. { Update integer registers, ignoring deallocations }
  10569. repeat
  10570. while assigned(p) and
  10571. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10572. (p.typ = ait_label) or
  10573. ((p.typ = ait_marker) and
  10574. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10575. p := tai(p.next);
  10576. while assigned(p) and
  10577. (p.typ=ait_RegAlloc) Do
  10578. begin
  10579. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10580. begin
  10581. case tai_regalloc(p).ratype of
  10582. ra_alloc :
  10583. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10584. else
  10585. ;
  10586. end;
  10587. end;
  10588. p := tai(p.next);
  10589. end;
  10590. until not(assigned(p)) or
  10591. (not(p.typ in SkipInstr) and
  10592. not((p.typ = ait_label) and
  10593. labelCanBeSkipped(tai_label(p))));
  10594. end;
  10595. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10596. var
  10597. hp1,hp2: tai;
  10598. carryadd_opcode : TAsmOp;
  10599. symbol: TAsmSymbol;
  10600. increg, tmpreg: TRegister;
  10601. RefModified: Boolean;
  10602. {$ifndef i8086}
  10603. { Code and variables specific to CMOV optimisations }
  10604. hp3,hp4,hp5,
  10605. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10606. l, c, w, x : Longint;
  10607. condition, second_condition : TAsmCond;
  10608. FoundMatchingJump, RegMatch: Boolean;
  10609. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10610. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10611. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10612. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10613. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10614. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10615. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10616. new register to store the constant }
  10617. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10618. var
  10619. RegSize: TSubRegister;
  10620. CurrentVal: TCGInt;
  10621. ANewReg: TRegister;
  10622. X: ShortInt;
  10623. begin
  10624. Result := False;
  10625. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10626. Exit;
  10627. if StoredCount >= MAX_CMOV_REGISTERS then
  10628. { Arrays are full }
  10629. Exit;
  10630. { Remember that CMOV can't encode 8-bit registers }
  10631. case taicpu(p).opsize of
  10632. S_W:
  10633. RegSize := R_SUBW;
  10634. S_L:
  10635. RegSize := R_SUBD;
  10636. {$ifdef x86_64}
  10637. S_Q:
  10638. RegSize := R_SUBQ;
  10639. {$endif x86_64}
  10640. else
  10641. InternalError(2021100401);
  10642. end;
  10643. { See if the value has already been reserved for another CMOV instruction }
  10644. CurrentVal := taicpu(p).oper[0]^.val;
  10645. for X := 0 to StoredCount - 1 do
  10646. if ConstVals[X] = CurrentVal then
  10647. begin
  10648. ConstRegs[StoredCount] := ConstRegs[X];
  10649. ConstSizes[StoredCount] := RegSize;
  10650. ConstVals[StoredCount] := CurrentVal;
  10651. Result := True;
  10652. Inc(StoredCount);
  10653. { Don't increase CMOVCount this time, since we're re-using a register }
  10654. Exit;
  10655. end;
  10656. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10657. if ANewReg = NR_NO then
  10658. { No free registers }
  10659. Exit;
  10660. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10661. up vying for the same register }
  10662. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10663. ConstRegs[StoredCount] := ANewReg;
  10664. ConstSizes[StoredCount] := RegSize;
  10665. ConstVals[StoredCount] := CurrentVal;
  10666. Inc(StoredCount);
  10667. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10668. MOV required adds complexity and will cause diminishing returns
  10669. sooner than normal. This is more of an approximate weighting than
  10670. anything else. }
  10671. Inc(CMOVCount);
  10672. Result := True;
  10673. end;
  10674. {$endif i8086}
  10675. begin
  10676. result:=false;
  10677. if GetNextInstruction(p,hp1) then
  10678. begin
  10679. if (hp1.typ=ait_label) then
  10680. begin
  10681. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10682. Exit;
  10683. end
  10684. else if (hp1.typ<>ait_instruction) then
  10685. Exit;
  10686. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10687. if (
  10688. (
  10689. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10690. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10691. (Taicpu(hp1).oper[0]^.val=1)
  10692. ) or
  10693. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10694. ) and
  10695. GetNextInstruction(hp1,hp2) and
  10696. SkipAligns(hp2, hp2) and
  10697. (hp2.typ = ait_label) and
  10698. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10699. { jb @@1 cmc
  10700. inc/dec operand --> adc/sbb operand,0
  10701. @@1:
  10702. ... and ...
  10703. jnb @@1
  10704. inc/dec operand --> adc/sbb operand,0
  10705. @@1: }
  10706. begin
  10707. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10708. begin
  10709. case taicpu(hp1).opcode of
  10710. A_INC,
  10711. A_ADD:
  10712. carryadd_opcode:=A_ADC;
  10713. A_DEC,
  10714. A_SUB:
  10715. carryadd_opcode:=A_SBB;
  10716. else
  10717. InternalError(2021011001);
  10718. end;
  10719. Taicpu(p).clearop(0);
  10720. Taicpu(p).ops:=0;
  10721. Taicpu(p).is_jmp:=false;
  10722. Taicpu(p).opcode:=A_CMC;
  10723. Taicpu(p).condition:=C_NONE;
  10724. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10725. Taicpu(hp1).ops:=2;
  10726. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10727. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10728. else
  10729. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10730. Taicpu(hp1).loadconst(0,0);
  10731. Taicpu(hp1).opcode:=carryadd_opcode;
  10732. result:=true;
  10733. exit;
  10734. end
  10735. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10736. begin
  10737. case taicpu(hp1).opcode of
  10738. A_INC,
  10739. A_ADD:
  10740. carryadd_opcode:=A_ADC;
  10741. A_DEC,
  10742. A_SUB:
  10743. carryadd_opcode:=A_SBB;
  10744. else
  10745. InternalError(2021011002);
  10746. end;
  10747. Taicpu(hp1).ops:=2;
  10748. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  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. RemoveCurrentP(p, hp1);
  10756. result:=true;
  10757. exit;
  10758. end
  10759. {
  10760. jcc @@1 setcc tmpreg
  10761. inc/dec/add/sub operand -> (movzx tmpreg)
  10762. @@1: add/sub tmpreg,operand
  10763. While this increases code size slightly, it makes the code much faster if the
  10764. jump is unpredictable
  10765. }
  10766. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10767. begin
  10768. { search for an available register which is volatile }
  10769. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10770. if increg <> NR_NO then
  10771. begin
  10772. { We don't need to check if tmpreg is in hp1 or not, because
  10773. it will be marked as in use at p (if not, this is
  10774. indictive of a compiler bug). }
  10775. TAsmLabel(symbol).decrefs;
  10776. Taicpu(p).clearop(0);
  10777. Taicpu(p).ops:=1;
  10778. Taicpu(p).is_jmp:=false;
  10779. Taicpu(p).opcode:=A_SETcc;
  10780. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10781. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10782. Taicpu(p).loadreg(0,increg);
  10783. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10784. begin
  10785. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10786. R_SUBW:
  10787. begin
  10788. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10789. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10790. end;
  10791. R_SUBD:
  10792. begin
  10793. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10794. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10795. end;
  10796. {$ifdef x86_64}
  10797. R_SUBQ:
  10798. begin
  10799. { MOVZX doesn't have a 64-bit variant, because
  10800. the 32-bit version implicitly zeroes the
  10801. upper 32-bits of the destination register }
  10802. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10803. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10804. setsubreg(tmpreg, R_SUBQ);
  10805. end;
  10806. {$endif x86_64}
  10807. else
  10808. Internalerror(2020030601);
  10809. end;
  10810. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10811. asml.InsertAfter(hp2,p);
  10812. end
  10813. else
  10814. tmpreg := increg;
  10815. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10816. begin
  10817. Taicpu(hp1).ops:=2;
  10818. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10819. end;
  10820. Taicpu(hp1).loadreg(0,tmpreg);
  10821. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10822. Result := True;
  10823. { p is no longer a Jcc instruction, so exit }
  10824. Exit;
  10825. end;
  10826. end;
  10827. end;
  10828. { Detect the following:
  10829. jmp<cond> @Lbl1
  10830. jmp @Lbl2
  10831. ...
  10832. @Lbl1:
  10833. ret
  10834. Change to:
  10835. jmp<inv_cond> @Lbl2
  10836. ret
  10837. }
  10838. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10839. begin
  10840. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10841. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10842. MatchInstruction(hp2,A_RET,[S_NO]) then
  10843. begin
  10844. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10845. { Change label address to that of the unconditional jump }
  10846. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10847. TAsmLabel(symbol).DecRefs;
  10848. taicpu(hp1).opcode := A_RET;
  10849. taicpu(hp1).is_jmp := false;
  10850. taicpu(hp1).ops := taicpu(hp2).ops;
  10851. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10852. case taicpu(hp2).ops of
  10853. 0:
  10854. taicpu(hp1).clearop(0);
  10855. 1:
  10856. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10857. else
  10858. internalerror(2016041302);
  10859. end;
  10860. end;
  10861. {$ifndef i8086}
  10862. end
  10863. {
  10864. convert
  10865. j<c> .L1
  10866. mov 1,reg
  10867. jmp .L2
  10868. .L1
  10869. mov 0,reg
  10870. .L2
  10871. into
  10872. mov 0,reg
  10873. set<not(c)> reg
  10874. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10875. would destroy the flag contents
  10876. }
  10877. else if MatchInstruction(hp1,A_MOV,[]) and
  10878. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10879. {$ifdef i386}
  10880. (
  10881. { Under i386, ESI, EDI, EBP and ESP
  10882. don't have an 8-bit representation }
  10883. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10884. ) and
  10885. {$endif i386}
  10886. (taicpu(hp1).oper[0]^.val=1) and
  10887. GetNextInstruction(hp1,hp2) and
  10888. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10889. GetNextInstruction(hp2,hp3) and
  10890. { skip align }
  10891. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10892. (hp3.typ=ait_label) and
  10893. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10894. (tai_label(hp3).labsym.getrefs=1) and
  10895. GetNextInstruction(hp3,hp4) and
  10896. MatchInstruction(hp4,A_MOV,[]) and
  10897. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10898. (taicpu(hp4).oper[0]^.val=0) and
  10899. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10900. GetNextInstruction(hp4,hp5) and
  10901. (hp5.typ=ait_label) and
  10902. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10903. (tai_label(hp5).labsym.getrefs=1) then
  10904. begin
  10905. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10906. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10907. { remove last label }
  10908. RemoveInstruction(hp5);
  10909. { remove second label }
  10910. RemoveInstruction(hp3);
  10911. { if align is present remove it }
  10912. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10913. RemoveInstruction(hp3);
  10914. { remove jmp }
  10915. RemoveInstruction(hp2);
  10916. if taicpu(hp1).opsize=S_B then
  10917. RemoveInstruction(hp1)
  10918. else
  10919. taicpu(hp1).loadconst(0,0);
  10920. taicpu(hp4).opcode:=A_SETcc;
  10921. taicpu(hp4).opsize:=S_B;
  10922. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10923. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10924. taicpu(hp4).opercnt:=1;
  10925. taicpu(hp4).ops:=1;
  10926. taicpu(hp4).freeop(1);
  10927. RemoveCurrentP(p);
  10928. Result:=true;
  10929. exit;
  10930. end
  10931. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10932. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10933. begin
  10934. { check for
  10935. jCC xxx
  10936. <several movs>
  10937. xxx:
  10938. Also spot:
  10939. Jcc xxx
  10940. <several movs>
  10941. jmp xxx
  10942. Change to:
  10943. <several cmovs with inverted condition>
  10944. jmp xxx (only for the 2nd case)
  10945. }
  10946. hp2 := p;
  10947. hp_lblxxx := hp1;
  10948. hp_flagalloc := nil;
  10949. hp_stop := nil;
  10950. FoundMatchingJump := False;
  10951. { Remember the first instruction in the first block of MOVs }
  10952. hpmov1 := hp1;
  10953. TransferUsedRegs(TmpUsedRegs);
  10954. while assigned(hp_lblxxx) and
  10955. { stop on labels }
  10956. (hp_lblxxx.typ <> ait_label) do
  10957. begin
  10958. { Keep track of all integer registers that are used }
  10959. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10960. if hp_lblxxx.typ = ait_instruction then
  10961. begin
  10962. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10963. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10964. begin
  10965. hp_stop := hp_lblxxx;
  10966. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10967. begin
  10968. { We found Jcc xxx; <several movs>; Jmp xxx }
  10969. FoundMatchingJump := True;
  10970. Break;
  10971. end;
  10972. { If it's not the jump we're looking for, it's
  10973. possibly the "if..else" variant }
  10974. end
  10975. { Check to see if we have a valid MOV instruction instead }
  10976. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10977. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10978. Break
  10979. else
  10980. { This will be a valid MOV }
  10981. hp_stop := hp_lblxxx;
  10982. end;
  10983. hp2 := hp_lblxxx;
  10984. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10985. end;
  10986. { Just make sure the last MOV is included if there's no jump }
  10987. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10988. hp_stop := hp_lblxxx;
  10989. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10990. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10991. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10992. jmp yyy; xxx:; movs; yyy:" variation }
  10993. if assigned(hp_lblxxx) and
  10994. (
  10995. { If we found JMP xxx, we don't actually need a label
  10996. (hp_lblxxx is the JMP instruction instead) }
  10997. FoundMatchingJump or
  10998. { Make sure we actually have the right label }
  10999. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11000. ) then
  11001. begin
  11002. { Use TmpUsedRegs to track registers that we reserve }
  11003. { When allocating temporary registers, try to look one
  11004. instruction back, as defining them before a CMP or TEST
  11005. instruction will be faster, and also avoid picking a
  11006. register that was only just deallocated }
  11007. if GetLastInstruction(p, hp_prev) and
  11008. 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
  11009. begin
  11010. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11011. for l := 0 to 1 do
  11012. with taicpu(hp_prev).oper[l]^ do
  11013. case typ of
  11014. top_reg:
  11015. if getregtype(reg) = R_INTREGISTER then
  11016. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11017. top_ref:
  11018. begin
  11019. if
  11020. {$ifdef x86_64}
  11021. (ref^.base <> NR_RIP) and
  11022. {$endif x86_64}
  11023. (ref^.base <> NR_NO) then
  11024. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11025. if (ref^.index <> NR_NO) then
  11026. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11027. end
  11028. else
  11029. ;
  11030. end;
  11031. { When inserting instructions before hp_prev, try to insert
  11032. them before the allocation of the FLAGS register }
  11033. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11034. { If not found, set it equal to hp_prev so it's something sensible }
  11035. hp_flagalloc := hp_prev;
  11036. hp_prev2 := nil;
  11037. { When dealing with a comparison against zero, take
  11038. note of the instruction before it to see if we can
  11039. move instructions further back in order to benefit
  11040. PostPeepholeOptTestOr.
  11041. }
  11042. if (
  11043. (
  11044. (taicpu(hp_prev).opcode = A_CMP) and
  11045. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11046. ) or
  11047. (
  11048. (taicpu(hp_prev).opcode = A_TEST) and
  11049. (
  11050. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11051. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11052. )
  11053. )
  11054. ) and
  11055. GetLastInstruction(hp_prev, hp_prev2) then
  11056. begin
  11057. if (hp_prev2.typ = ait_instruction) and
  11058. { These instructions set the zero flag if the result is zero }
  11059. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11060. begin
  11061. { Also mark all the registers in this previous instruction
  11062. as 'in use', even if they've just been deallocated }
  11063. for l := 0 to 1 do
  11064. with taicpu(hp_prev2).oper[l]^ do
  11065. case typ of
  11066. top_reg:
  11067. if getregtype(reg) = R_INTREGISTER then
  11068. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11069. top_ref:
  11070. begin
  11071. if
  11072. {$ifdef x86_64}
  11073. (ref^.base <> NR_RIP) and
  11074. {$endif x86_64}
  11075. (ref^.base <> NR_NO) then
  11076. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11077. if (ref^.index <> NR_NO) then
  11078. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11079. end
  11080. else
  11081. ;
  11082. end;
  11083. end
  11084. else
  11085. { Unsuitable instruction }
  11086. hp_prev2 := nil;
  11087. end;
  11088. end
  11089. else
  11090. begin
  11091. hp_prev := p;
  11092. { When inserting instructions before hp_prev, try to insert
  11093. them before the allocation of the FLAGS register }
  11094. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11095. { If not found, set it equal to p so it's something sensible }
  11096. hp_flagalloc := p;
  11097. hp_prev2 := nil;
  11098. end;
  11099. l := 0;
  11100. c := 0;
  11101. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11102. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11103. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11104. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11105. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11106. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11107. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11108. RefModified := False;
  11109. while assigned(hp1) and
  11110. { Stop on the label we found }
  11111. (hp1 <> hp_lblxxx) do
  11112. begin
  11113. case hp1.typ of
  11114. ait_instruction:
  11115. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11116. begin
  11117. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11118. begin
  11119. Inc(l);
  11120. { MOV instruction will be writing to a register }
  11121. if Assigned(hp_prev) and
  11122. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11123. (hp_prev.typ = ait_instruction) and
  11124. (taicpu(hp_prev).ops = 2) and
  11125. (
  11126. (
  11127. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11128. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11129. ) or
  11130. (
  11131. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11132. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11133. )
  11134. ) then
  11135. { It is no longer safe to use the reference in the condition.
  11136. this prevents problems such as:
  11137. mov (%reg),%reg
  11138. mov (%reg),...
  11139. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11140. (fixes #40165)
  11141. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11142. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11143. }
  11144. RefModified := True;
  11145. end
  11146. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11147. { CMOV with constants grows the code size }
  11148. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11149. begin
  11150. { Register was reserved by TryCMOVConst and
  11151. stored on ConstRegs[c] }
  11152. end
  11153. else
  11154. Break;
  11155. end
  11156. else
  11157. Break;
  11158. else
  11159. ;
  11160. end;
  11161. GetNextInstruction(hp1,hp1);
  11162. end;
  11163. if (hp1 = hp_lblxxx) then
  11164. begin
  11165. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11166. begin
  11167. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11168. TmpUsedRegs[R_INTREGISTER].Clear;
  11169. x := 0;
  11170. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11171. condition := inverse_cond(taicpu(p).condition);
  11172. UpdateUsedRegs(tai(p.next));
  11173. hp1 := hpmov1;
  11174. repeat
  11175. if not Assigned(hp1) then
  11176. InternalError(2018062900);
  11177. if (hp1.typ = ait_instruction) then
  11178. begin
  11179. { Extra safeguard }
  11180. if (taicpu(hp1).opcode <> A_MOV) then
  11181. InternalError(2018062901);
  11182. if taicpu(hp1).oper[0]^.typ = top_const then
  11183. begin
  11184. if x >= MAX_CMOV_REGISTERS then
  11185. InternalError(2021100410);
  11186. { If it's in TmpUsedRegs, then this register
  11187. is being used more than once and hence has
  11188. already had its value defined (it gets
  11189. added to UsedRegs through AllocRegBetween
  11190. below) }
  11191. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11192. begin
  11193. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11194. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11195. asml.InsertBefore(hp_new, hp_flagalloc);
  11196. if Assigned(hp_prev2) then
  11197. TrySwapMovOp(hp_prev2, hp_new);
  11198. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11199. ConstMovs[X] := hp_new;
  11200. end
  11201. else
  11202. { We just need an instruction between hp_prev and hp1
  11203. where we know the register is marked as in use }
  11204. hp_new := hpmov1;
  11205. { Keep track of largest write for this register so it can be optimised later }
  11206. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11207. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11208. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11209. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11210. Inc(x);
  11211. end;
  11212. taicpu(hp1).opcode := A_CMOVcc;
  11213. taicpu(hp1).condition := condition;
  11214. end;
  11215. UpdateUsedRegs(tai(hp1.next));
  11216. GetNextInstruction(hp1, hp1);
  11217. until (hp1 = hp_lblxxx);
  11218. { Update initialisation MOVs to the smallest possible size }
  11219. for c := 0 to x - 1 do
  11220. if Assigned(ConstMovs[c]) then
  11221. begin
  11222. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11223. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11224. end;
  11225. hp2 := hp_lblxxx;
  11226. repeat
  11227. if not Assigned(hp2) then
  11228. InternalError(2018062910);
  11229. case hp2.typ of
  11230. ait_label:
  11231. { What we expected - break out of the loop (it won't be a dead label at the top of
  11232. a cluster because that was optimised at an earlier stage) }
  11233. Break;
  11234. ait_align:
  11235. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11236. begin
  11237. hp2 := tai(hp2.Next);
  11238. Continue;
  11239. end;
  11240. ait_instruction:
  11241. begin
  11242. if taicpu(hp2).opcode<>A_JMP then
  11243. InternalError(2018062912);
  11244. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11245. Break;
  11246. end
  11247. else
  11248. begin
  11249. { Might be a comment or temporary allocation entry }
  11250. if not (hp2.typ in SkipInstr) then
  11251. InternalError(2018062911);
  11252. hp2 := tai(hp2.Next);
  11253. Continue;
  11254. end;
  11255. end;
  11256. until False;
  11257. { Now we can safely decrement the reference count }
  11258. tasmlabel(symbol).decrefs;
  11259. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11260. { Remove the original jump }
  11261. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11262. if hp2.typ=ait_instruction then
  11263. begin
  11264. p := hp2;
  11265. Result := True;
  11266. end
  11267. else
  11268. begin
  11269. UpdateUsedRegs(tai(hp2.next));
  11270. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11271. { Remove the label if this is its final reference }
  11272. if (tasmlabel(symbol).getrefs=0) then
  11273. begin
  11274. { Make sure the aligns get stripped too }
  11275. hp1 := tai(hp_lblxxx.Previous);
  11276. while Assigned(hp1) and (hp1.typ = ait_align) do
  11277. begin
  11278. hp_lblxxx := hp1;
  11279. hp1 := tai(hp_lblxxx.Previous);
  11280. end;
  11281. StripLabelFast(hp_lblxxx);
  11282. end;
  11283. end;
  11284. Exit;
  11285. end;
  11286. end
  11287. else if assigned(hp_lblxxx) and
  11288. { check further for
  11289. jCC xxx
  11290. <several movs 1>
  11291. jmp yyy
  11292. xxx:
  11293. <several movs 2>
  11294. yyy:
  11295. }
  11296. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11297. { hp1 should be pointing to jmp yyy }
  11298. MatchInstruction(hp1, A_JMP, []) and
  11299. { real label and jump, no further references to the
  11300. label are allowed }
  11301. (TAsmLabel(symbol).getrefs=1) and
  11302. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11303. begin
  11304. hp_jump := hp1;
  11305. { Don't set c to zero }
  11306. l := 0;
  11307. w := 0;
  11308. GetNextInstruction(hp_lblxxx, hpmov2);
  11309. hp2 := hp_lblxxx;
  11310. hp_lblyyy := hpmov2;
  11311. while assigned(hp_lblyyy) and
  11312. { stop on labels }
  11313. (hp_lblyyy.typ <> ait_label) do
  11314. begin
  11315. { Keep track of all integer registers that are used }
  11316. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11317. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11318. Break;
  11319. hp2 := hp_lblyyy;
  11320. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11321. end;
  11322. { Analyse the second batch of MOVs to see if the setup is valid }
  11323. RefModified := False;
  11324. hp1 := hpmov2;
  11325. while assigned(hp1) and
  11326. (hp1 <> hp_lblyyy) do
  11327. begin
  11328. case hp1.typ of
  11329. ait_instruction:
  11330. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11331. begin
  11332. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11333. begin
  11334. Inc(l);
  11335. { MOV instruction will be writing to a register }
  11336. if Assigned(hp_prev) and
  11337. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11338. (hp_prev.typ = ait_instruction) and
  11339. (taicpu(hp_prev).ops = 2) and
  11340. (
  11341. (
  11342. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11343. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11344. ) or
  11345. (
  11346. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11347. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11348. )
  11349. ) then
  11350. { It is no longer safe to use the reference in the condition.
  11351. this prevents problems such as:
  11352. mov (%reg),%reg
  11353. mov (%reg),...
  11354. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11355. (fixes #40165)
  11356. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11357. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11358. }
  11359. RefModified := True;
  11360. end
  11361. else if not (cs_opt_size in current_settings.optimizerswitches)
  11362. { CMOV with constants grows the code size }
  11363. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11364. begin
  11365. { Register was reserved by TryCMOVConst and
  11366. stored on ConstRegs[c] }
  11367. end
  11368. else
  11369. Break;
  11370. end
  11371. else
  11372. Break;
  11373. else
  11374. ;
  11375. end;
  11376. GetNextInstruction(hp1,hp1);
  11377. end;
  11378. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11379. TmpUsedRegs[R_INTREGISTER].Clear;
  11380. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11381. (hp1 = hp_lblyyy) and
  11382. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11383. begin
  11384. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11385. second_condition := taicpu(p).condition;
  11386. condition := inverse_cond(taicpu(p).condition);
  11387. UpdateUsedRegs(tai(p.next));
  11388. { Scan through the first set of MOVs to update UsedRegs,
  11389. but don't process them yet }
  11390. hp1 := hpmov1;
  11391. repeat
  11392. if not Assigned(hp1) then
  11393. InternalError(2018062901);
  11394. UpdateUsedRegs(tai(hp1.next));
  11395. GetNextInstruction(hp1, hp1);
  11396. until (hp1 = hp_lblxxx);
  11397. UpdateUsedRegs(tai(hp_lblxxx.next));
  11398. { Process the second set of MOVs first,
  11399. because if a destination register is
  11400. shared between the first and second MOV
  11401. sets, it is more efficient to turn the
  11402. first one into a MOV instruction and place
  11403. it before the CMP if possible, but we
  11404. won't know which registers are shared
  11405. until we've processed at least one list,
  11406. so we might as well make it the second
  11407. one since that won't be modified again. }
  11408. hp1 := hpmov2;
  11409. repeat
  11410. if not Assigned(hp1) then
  11411. InternalError(2018062902);
  11412. if (hp1.typ = ait_instruction) then
  11413. begin
  11414. { Extra safeguard }
  11415. if (taicpu(hp1).opcode <> A_MOV) then
  11416. InternalError(2018062903);
  11417. if taicpu(hp1).oper[0]^.typ = top_const then
  11418. begin
  11419. RegMatch := False;
  11420. for x := 0 to c - 1 do
  11421. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11422. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11423. begin
  11424. RegMatch := True;
  11425. { If it's in TmpUsedRegs, then this register
  11426. is being used more than once and hence has
  11427. already had its value defined (it gets
  11428. added to UsedRegs through AllocRegBetween
  11429. below) }
  11430. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11431. begin
  11432. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11433. asml.InsertBefore(hp_new, hp_flagalloc);
  11434. if Assigned(hp_prev2) then
  11435. TrySwapMovOp(hp_prev2, hp_new);
  11436. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11437. ConstMovs[X] := hp_new;
  11438. end
  11439. else
  11440. { We just need an instruction between hp_prev and hp1
  11441. where we know the register is marked as in use }
  11442. hp_new := hpmov2;
  11443. { Keep track of largest write for this register so it can be optimised later }
  11444. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11445. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11446. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11447. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11448. Break;
  11449. end;
  11450. if not RegMatch then
  11451. InternalError(2021100411);
  11452. end;
  11453. taicpu(hp1).opcode := A_CMOVcc;
  11454. taicpu(hp1).condition := second_condition;
  11455. { Store these writes to search for
  11456. duplicates later on }
  11457. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11458. Inc(w);
  11459. end;
  11460. UpdateUsedRegs(tai(hp1.next));
  11461. GetNextInstruction(hp1, hp1);
  11462. until (hp1 = hp_lblyyy);
  11463. { Now do the first set of MOVs }
  11464. hp1 := hpmov1;
  11465. repeat
  11466. if not Assigned(hp1) then
  11467. InternalError(2018062904);
  11468. if (hp1.typ = ait_instruction) then
  11469. begin
  11470. RegMatch := False;
  11471. { Extra safeguard }
  11472. if (taicpu(hp1).opcode <> A_MOV) then
  11473. InternalError(2018062905);
  11474. { Search through the RegWrites list to see
  11475. if there are any opposing CMOV pairs that
  11476. write to the same register }
  11477. for x := 0 to w - 1 do
  11478. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11479. begin
  11480. { We have a match. Keep this as a MOV }
  11481. { Move ahead in preparation }
  11482. GetNextInstruction(hp1, hp1);
  11483. RegMatch := True;
  11484. Break;
  11485. end;
  11486. if RegMatch then
  11487. Continue;
  11488. if taicpu(hp1).oper[0]^.typ = top_const then
  11489. begin
  11490. RegMatch := False;
  11491. for x := 0 to c - 1 do
  11492. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11493. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11494. begin
  11495. RegMatch := True;
  11496. { If it's in TmpUsedRegs, then this register
  11497. is being used more than once and hence has
  11498. already had its value defined (it gets
  11499. added to UsedRegs through AllocRegBetween
  11500. below) }
  11501. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11502. begin
  11503. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11504. asml.InsertBefore(hp_new, hp_flagalloc);
  11505. if Assigned(hp_prev2) then
  11506. TrySwapMovOp(hp_prev2, hp_new);
  11507. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11508. ConstMovs[X] := hp_new;
  11509. end
  11510. else
  11511. { We just need an instruction between hp_prev and hp1
  11512. where we know the register is marked as in use }
  11513. hp_new := hpmov1;
  11514. { Keep track of largest write for this register so it can be optimised later }
  11515. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11516. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11517. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11518. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11519. Break;
  11520. end;
  11521. if not RegMatch then
  11522. InternalError(2021100412);
  11523. end;
  11524. taicpu(hp1).opcode := A_CMOVcc;
  11525. taicpu(hp1).condition := condition;
  11526. end;
  11527. GetNextInstruction(hp1, hp1);
  11528. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11529. { Update initialisation MOVs to the smallest possible size }
  11530. for x := 0 to c - 1 do
  11531. if Assigned(ConstMovs[x]) then
  11532. begin
  11533. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11534. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11535. end;
  11536. UpdateUsedRegs(tai(hp_jump.next));
  11537. UpdateUsedRegs(tai(hp_lblyyy.next));
  11538. { Get first instruction after label }
  11539. hp1 := p;
  11540. GetNextInstruction(hp_lblyyy, p);
  11541. { Don't dereference yet, as doing so will cause
  11542. GetNextInstruction to skip the label and
  11543. optional align marker. [Kit] }
  11544. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11545. { remove Jcc }
  11546. RemoveInstruction(hp1);
  11547. { Now we can safely decrement it }
  11548. tasmlabel(symbol).decrefs;
  11549. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11550. { Make sure the aligns get stripped too }
  11551. hp1 := tai(hp_lblxxx.Previous);
  11552. while Assigned(hp1) and (hp1.typ = ait_align) do
  11553. begin
  11554. hp_lblxxx := hp1;
  11555. hp1 := tai(hp_lblxxx.Previous);
  11556. end;
  11557. StripLabelFast(hp_lblxxx);
  11558. { remove jmp }
  11559. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11560. RemoveInstruction(hp_jump);
  11561. { As before, now we can safely decrement it }
  11562. TAsmLabel(symbol).decrefs;
  11563. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11564. if TAsmLabel(symbol).getrefs = 0 then
  11565. begin
  11566. { Make sure the aligns get stripped too }
  11567. hp1 := tai(hp_lblyyy.Previous);
  11568. while Assigned(hp1) and (hp1.typ = ait_align) do
  11569. begin
  11570. hp_lblyyy := hp1;
  11571. hp1 := tai(hp_lblyyy.Previous);
  11572. end;
  11573. StripLabelFast(hp_lblyyy);
  11574. end;
  11575. if Assigned(p) then
  11576. result := True;
  11577. exit;
  11578. end;
  11579. end;
  11580. end;
  11581. {$endif i8086}
  11582. end;
  11583. end;
  11584. end;
  11585. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11586. var
  11587. hp1,hp2,hp3: tai;
  11588. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11589. NewSize: TOpSize;
  11590. NewRegSize: TSubRegister;
  11591. Limit: TCgInt;
  11592. SwapOper: POper;
  11593. begin
  11594. result:=false;
  11595. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11596. GetNextInstruction(p,hp1) and
  11597. (hp1.typ = ait_instruction);
  11598. if reg_and_hp1_is_instr and
  11599. (
  11600. (taicpu(hp1).opcode <> A_LEA) or
  11601. { If the LEA instruction can be converted into an arithmetic instruction,
  11602. it may be possible to then fold it. }
  11603. (
  11604. { If the flags register is in use, don't change the instruction
  11605. to an ADD otherwise this will scramble the flags. [Kit] }
  11606. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11607. ConvertLEA(taicpu(hp1))
  11608. )
  11609. ) and
  11610. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11611. GetNextInstruction(hp1,hp2) and
  11612. MatchInstruction(hp2,A_MOV,[]) and
  11613. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11614. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11615. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11616. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11617. {$ifdef i386}
  11618. { not all registers have byte size sub registers on i386 }
  11619. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11620. {$endif i386}
  11621. (((taicpu(hp1).ops=2) and
  11622. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11623. ((taicpu(hp1).ops=1) and
  11624. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11625. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11626. begin
  11627. { change movsX/movzX reg/ref, reg2
  11628. add/sub/or/... reg3/$const, reg2
  11629. mov reg2 reg/ref
  11630. to add/sub/or/... reg3/$const, reg/ref }
  11631. { by example:
  11632. movswl %si,%eax movswl %si,%eax p
  11633. decl %eax addl %edx,%eax hp1
  11634. movw %ax,%si movw %ax,%si hp2
  11635. ->
  11636. movswl %si,%eax movswl %si,%eax p
  11637. decw %eax addw %edx,%eax hp1
  11638. movw %ax,%si movw %ax,%si hp2
  11639. }
  11640. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11641. {
  11642. ->
  11643. movswl %si,%eax movswl %si,%eax p
  11644. decw %si addw %dx,%si hp1
  11645. movw %ax,%si movw %ax,%si hp2
  11646. }
  11647. case taicpu(hp1).ops of
  11648. 1:
  11649. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11650. 2:
  11651. begin
  11652. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11653. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11654. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11655. end;
  11656. else
  11657. internalerror(2008042702);
  11658. end;
  11659. {
  11660. ->
  11661. decw %si addw %dx,%si p
  11662. }
  11663. DebugMsg(SPeepholeOptimization + 'var3',p);
  11664. RemoveCurrentP(p, hp1);
  11665. RemoveInstruction(hp2);
  11666. Result := True;
  11667. Exit;
  11668. end;
  11669. if reg_and_hp1_is_instr and
  11670. (taicpu(hp1).opcode = A_MOV) and
  11671. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11672. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11673. {$ifdef x86_64}
  11674. { check for implicit extension to 64 bit }
  11675. or
  11676. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11677. (taicpu(hp1).opsize=S_Q) and
  11678. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11679. )
  11680. {$endif x86_64}
  11681. )
  11682. then
  11683. begin
  11684. { change
  11685. movx %reg1,%reg2
  11686. mov %reg2,%reg3
  11687. dealloc %reg2
  11688. into
  11689. movx %reg,%reg3
  11690. }
  11691. TransferUsedRegs(TmpUsedRegs);
  11692. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11693. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11694. begin
  11695. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11696. {$ifdef x86_64}
  11697. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11698. (taicpu(hp1).opsize=S_Q) then
  11699. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11700. else
  11701. {$endif x86_64}
  11702. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11703. RemoveInstruction(hp1);
  11704. Result := True;
  11705. Exit;
  11706. end;
  11707. end;
  11708. if reg_and_hp1_is_instr and
  11709. ((taicpu(hp1).opcode=A_MOV) or
  11710. (taicpu(hp1).opcode=A_ADD) or
  11711. (taicpu(hp1).opcode=A_SUB) or
  11712. (taicpu(hp1).opcode=A_CMP) or
  11713. (taicpu(hp1).opcode=A_OR) or
  11714. (taicpu(hp1).opcode=A_XOR) or
  11715. (taicpu(hp1).opcode=A_AND)
  11716. ) and
  11717. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11718. begin
  11719. AndTest := (taicpu(hp1).opcode=A_AND) and
  11720. GetNextInstruction(hp1, hp2) and
  11721. (hp2.typ = ait_instruction) and
  11722. (
  11723. (
  11724. (taicpu(hp2).opcode=A_TEST) and
  11725. (
  11726. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11727. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11728. (
  11729. { If the AND and TEST instructions share a constant, this is also valid }
  11730. (taicpu(hp1).oper[0]^.typ = top_const) and
  11731. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11732. )
  11733. ) and
  11734. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11735. ) or
  11736. (
  11737. (taicpu(hp2).opcode=A_CMP) and
  11738. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11739. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11740. )
  11741. );
  11742. { change
  11743. movx (oper),%reg2
  11744. and $x,%reg2
  11745. test %reg2,%reg2
  11746. dealloc %reg2
  11747. into
  11748. op %reg1,%reg3
  11749. if the second op accesses only the bits stored in reg1
  11750. }
  11751. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11752. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11753. (taicpu(hp1).oper[0]^.typ = top_const) and
  11754. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11755. AndTest then
  11756. begin
  11757. { Check if the AND constant is in range }
  11758. case taicpu(p).opsize of
  11759. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11760. begin
  11761. NewSize := S_B;
  11762. Limit := $FF;
  11763. end;
  11764. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11765. begin
  11766. NewSize := S_W;
  11767. Limit := $FFFF;
  11768. end;
  11769. {$ifdef x86_64}
  11770. S_LQ:
  11771. begin
  11772. NewSize := S_L;
  11773. Limit := $FFFFFFFF;
  11774. end;
  11775. {$endif x86_64}
  11776. else
  11777. InternalError(2021120303);
  11778. end;
  11779. if (
  11780. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11781. { Check for negative operands }
  11782. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11783. ) and
  11784. GetNextInstruction(hp2,hp3) and
  11785. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11786. (taicpu(hp3).condition in [C_E,C_NE]) then
  11787. begin
  11788. TransferUsedRegs(TmpUsedRegs);
  11789. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11790. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11791. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11792. begin
  11793. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11794. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11795. taicpu(hp1).opcode := A_TEST;
  11796. taicpu(hp1).opsize := NewSize;
  11797. RemoveInstruction(hp2);
  11798. RemoveCurrentP(p, hp1);
  11799. Result:=true;
  11800. exit;
  11801. end;
  11802. end;
  11803. end;
  11804. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11805. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11806. (taicpu(hp1).opsize=S_B)) or
  11807. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11808. (taicpu(hp1).opsize=S_W))
  11809. {$ifdef x86_64}
  11810. or ((taicpu(p).opsize=S_LQ) and
  11811. (taicpu(hp1).opsize=S_L))
  11812. {$endif x86_64}
  11813. ) and
  11814. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11815. begin
  11816. { change
  11817. movx %reg1,%reg2
  11818. op %reg2,%reg3
  11819. dealloc %reg2
  11820. into
  11821. op %reg1,%reg3
  11822. if the second op accesses only the bits stored in reg1
  11823. }
  11824. TransferUsedRegs(TmpUsedRegs);
  11825. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11826. if AndTest then
  11827. begin
  11828. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11829. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11830. end
  11831. else
  11832. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11833. if not RegUsed then
  11834. begin
  11835. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11836. if taicpu(p).oper[0]^.typ=top_reg then
  11837. begin
  11838. case taicpu(hp1).opsize of
  11839. S_B:
  11840. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11841. S_W:
  11842. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11843. S_L:
  11844. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11845. else
  11846. Internalerror(2020102301);
  11847. end;
  11848. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11849. end
  11850. else
  11851. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11852. RemoveCurrentP(p);
  11853. if AndTest then
  11854. RemoveInstruction(hp2);
  11855. result:=true;
  11856. exit;
  11857. end;
  11858. end
  11859. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11860. (
  11861. { Bitwise operations only }
  11862. (taicpu(hp1).opcode=A_AND) or
  11863. (taicpu(hp1).opcode=A_TEST) or
  11864. (
  11865. (taicpu(hp1).oper[0]^.typ = top_const) and
  11866. (
  11867. (taicpu(hp1).opcode=A_OR) or
  11868. (taicpu(hp1).opcode=A_XOR)
  11869. )
  11870. )
  11871. ) and
  11872. (
  11873. (taicpu(hp1).oper[0]^.typ = top_const) or
  11874. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11875. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11876. ) then
  11877. begin
  11878. { change
  11879. movx %reg2,%reg2
  11880. op const,%reg2
  11881. into
  11882. op const,%reg2 (smaller version)
  11883. movx %reg2,%reg2
  11884. also change
  11885. movx %reg1,%reg2
  11886. and/test (oper),%reg2
  11887. dealloc %reg2
  11888. into
  11889. and/test (oper),%reg1
  11890. }
  11891. case taicpu(p).opsize of
  11892. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11893. begin
  11894. NewSize := S_B;
  11895. NewRegSize := R_SUBL;
  11896. Limit := $FF;
  11897. end;
  11898. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11899. begin
  11900. NewSize := S_W;
  11901. NewRegSize := R_SUBW;
  11902. Limit := $FFFF;
  11903. end;
  11904. {$ifdef x86_64}
  11905. S_LQ:
  11906. begin
  11907. NewSize := S_L;
  11908. NewRegSize := R_SUBD;
  11909. Limit := $FFFFFFFF;
  11910. end;
  11911. {$endif x86_64}
  11912. else
  11913. Internalerror(2021120302);
  11914. end;
  11915. TransferUsedRegs(TmpUsedRegs);
  11916. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11917. if AndTest then
  11918. begin
  11919. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11920. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11921. end
  11922. else
  11923. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11924. if
  11925. (
  11926. (taicpu(p).opcode = A_MOVZX) and
  11927. (
  11928. (taicpu(hp1).opcode=A_AND) or
  11929. (taicpu(hp1).opcode=A_TEST)
  11930. ) and
  11931. not (
  11932. { If both are references, then the final instruction will have
  11933. both operands as references, which is not allowed }
  11934. (taicpu(p).oper[0]^.typ = top_ref) and
  11935. (taicpu(hp1).oper[0]^.typ = top_ref)
  11936. ) and
  11937. not RegUsed
  11938. ) or
  11939. (
  11940. (
  11941. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11942. not RegUsed
  11943. ) and
  11944. (taicpu(p).oper[0]^.typ = top_reg) and
  11945. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11946. (taicpu(hp1).oper[0]^.typ = top_const) and
  11947. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11948. ) then
  11949. begin
  11950. {$if defined(i386) or defined(i8086)}
  11951. { If the target size is 8-bit, make sure we can actually encode it }
  11952. 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
  11953. Exit;
  11954. {$endif i386 or i8086}
  11955. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11956. taicpu(hp1).opsize := NewSize;
  11957. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11958. if AndTest then
  11959. begin
  11960. RemoveInstruction(hp2);
  11961. if not RegUsed then
  11962. begin
  11963. taicpu(hp1).opcode := A_TEST;
  11964. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11965. begin
  11966. { Make sure the reference is the second operand }
  11967. SwapOper := taicpu(hp1).oper[0];
  11968. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11969. taicpu(hp1).oper[1] := SwapOper;
  11970. end;
  11971. end;
  11972. end;
  11973. case taicpu(hp1).oper[0]^.typ of
  11974. top_reg:
  11975. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11976. top_const:
  11977. { For the AND/TEST case }
  11978. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11979. else
  11980. ;
  11981. end;
  11982. if RegUsed then
  11983. begin
  11984. AsmL.Remove(p);
  11985. AsmL.InsertAfter(p, hp1);
  11986. p := hp1;
  11987. end
  11988. else
  11989. RemoveCurrentP(p, hp1);
  11990. result:=true;
  11991. exit;
  11992. end;
  11993. end;
  11994. end;
  11995. if reg_and_hp1_is_instr and
  11996. (taicpu(p).oper[0]^.typ = top_reg) and
  11997. (
  11998. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11999. ) and
  12000. (taicpu(hp1).oper[0]^.typ = top_const) and
  12001. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12002. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12003. { Minimum shift value allowed is the bit difference between the sizes }
  12004. (taicpu(hp1).oper[0]^.val >=
  12005. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12006. 8 * (
  12007. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12008. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12009. )
  12010. ) then
  12011. begin
  12012. { For:
  12013. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12014. shl/sal ##, %reg1
  12015. Remove the movsx/movzx instruction if the shift overwrites the
  12016. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12017. }
  12018. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12019. RemoveCurrentP(p, hp1);
  12020. Result := True;
  12021. Exit;
  12022. end
  12023. else if reg_and_hp1_is_instr and
  12024. (taicpu(p).oper[0]^.typ = top_reg) and
  12025. (
  12026. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12027. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12028. ) and
  12029. (taicpu(hp1).oper[0]^.typ = top_const) and
  12030. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12031. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12032. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12033. (taicpu(hp1).oper[0]^.val <
  12034. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12035. 8 * (
  12036. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12037. )
  12038. ) then
  12039. begin
  12040. { For:
  12041. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12042. sar ##, %reg1 shr ##, %reg1
  12043. Move the shift to before the movx instruction if the shift value
  12044. is not too large.
  12045. }
  12046. asml.Remove(hp1);
  12047. asml.InsertBefore(hp1, p);
  12048. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12049. case taicpu(p).opsize of
  12050. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12051. taicpu(hp1).opsize := S_B;
  12052. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12053. taicpu(hp1).opsize := S_W;
  12054. {$ifdef x86_64}
  12055. S_LQ:
  12056. taicpu(hp1).opsize := S_L;
  12057. {$endif}
  12058. else
  12059. InternalError(2020112401);
  12060. end;
  12061. if (taicpu(hp1).opcode = A_SHR) then
  12062. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12063. else
  12064. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12065. Result := True;
  12066. end;
  12067. if reg_and_hp1_is_instr and
  12068. (taicpu(p).oper[0]^.typ = top_reg) and
  12069. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12070. (
  12071. (taicpu(hp1).opcode = taicpu(p).opcode)
  12072. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12073. {$ifdef x86_64}
  12074. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12075. {$endif x86_64}
  12076. ) then
  12077. begin
  12078. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12079. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12080. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12081. begin
  12082. {
  12083. For example:
  12084. movzbw %al,%ax
  12085. movzwl %ax,%eax
  12086. Compress into:
  12087. movzbl %al,%eax
  12088. }
  12089. RegUsed := False;
  12090. case taicpu(p).opsize of
  12091. S_BW:
  12092. case taicpu(hp1).opsize of
  12093. S_WL:
  12094. begin
  12095. taicpu(p).opsize := S_BL;
  12096. RegUsed := True;
  12097. end;
  12098. {$ifdef x86_64}
  12099. S_WQ:
  12100. begin
  12101. if taicpu(p).opcode = A_MOVZX then
  12102. begin
  12103. taicpu(p).opsize := S_BL;
  12104. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12105. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12106. end
  12107. else
  12108. taicpu(p).opsize := S_BQ;
  12109. RegUsed := True;
  12110. end;
  12111. {$endif x86_64}
  12112. else
  12113. ;
  12114. end;
  12115. {$ifdef x86_64}
  12116. S_BL:
  12117. case taicpu(hp1).opsize of
  12118. S_LQ:
  12119. begin
  12120. if taicpu(p).opcode = A_MOVZX then
  12121. begin
  12122. taicpu(p).opsize := S_BL;
  12123. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12124. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12125. end
  12126. else
  12127. taicpu(p).opsize := S_BQ;
  12128. RegUsed := True;
  12129. end;
  12130. else
  12131. ;
  12132. end;
  12133. S_WL:
  12134. case taicpu(hp1).opsize of
  12135. S_LQ:
  12136. begin
  12137. if taicpu(p).opcode = A_MOVZX then
  12138. begin
  12139. taicpu(p).opsize := S_WL;
  12140. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12141. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12142. end
  12143. else
  12144. taicpu(p).opsize := S_WQ;
  12145. RegUsed := True;
  12146. end;
  12147. else
  12148. ;
  12149. end;
  12150. {$endif x86_64}
  12151. else
  12152. ;
  12153. end;
  12154. if RegUsed then
  12155. begin
  12156. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12157. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12158. RemoveInstruction(hp1);
  12159. Result := True;
  12160. Exit;
  12161. end;
  12162. end;
  12163. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12164. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12165. GetNextInstruction(hp1, hp2) and
  12166. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12167. (
  12168. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12169. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12170. {$ifdef x86_64}
  12171. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12172. {$endif x86_64}
  12173. ) and
  12174. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12175. (
  12176. (
  12177. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12178. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12179. ) or
  12180. (
  12181. { Only allow the operands in reverse order for TEST instructions }
  12182. (taicpu(hp2).opcode = A_TEST) and
  12183. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12184. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12185. )
  12186. ) then
  12187. begin
  12188. {
  12189. For example:
  12190. movzbl %al,%eax
  12191. movzbl (ref),%edx
  12192. andl %edx,%eax
  12193. (%edx deallocated)
  12194. Change to:
  12195. andb (ref),%al
  12196. movzbl %al,%eax
  12197. Rules are:
  12198. - First two instructions have the same opcode and opsize
  12199. - First instruction's operands are the same super-register
  12200. - Second instruction operates on a different register
  12201. - Third instruction is AND, OR, XOR or TEST
  12202. - Third instruction's operands are the destination registers of the first two instructions
  12203. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12204. - Second instruction's destination register is deallocated afterwards
  12205. }
  12206. TransferUsedRegs(TmpUsedRegs);
  12207. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12208. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12209. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12210. begin
  12211. case taicpu(p).opsize of
  12212. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12213. NewSize := S_B;
  12214. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12215. NewSize := S_W;
  12216. {$ifdef x86_64}
  12217. S_LQ:
  12218. NewSize := S_L;
  12219. {$endif x86_64}
  12220. else
  12221. InternalError(2021120301);
  12222. end;
  12223. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12224. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12225. taicpu(hp2).opsize := NewSize;
  12226. RemoveInstruction(hp1);
  12227. { With TEST, it's best to keep the MOVX instruction at the top }
  12228. if (taicpu(hp2).opcode <> A_TEST) then
  12229. begin
  12230. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12231. asml.Remove(p);
  12232. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12233. asml.InsertAfter(p, hp2);
  12234. p := hp2;
  12235. end
  12236. else
  12237. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12238. Result := True;
  12239. Exit;
  12240. end;
  12241. end;
  12242. end;
  12243. if taicpu(p).opcode=A_MOVZX then
  12244. begin
  12245. { removes superfluous And's after movzx's }
  12246. if reg_and_hp1_is_instr and
  12247. (taicpu(hp1).opcode = A_AND) and
  12248. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12249. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12250. {$ifdef x86_64}
  12251. { check for implicit extension to 64 bit }
  12252. or
  12253. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12254. (taicpu(hp1).opsize=S_Q) and
  12255. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12256. )
  12257. {$endif x86_64}
  12258. )
  12259. then
  12260. begin
  12261. case taicpu(p).opsize Of
  12262. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12263. if (taicpu(hp1).oper[0]^.val = $ff) then
  12264. begin
  12265. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12266. RemoveInstruction(hp1);
  12267. Result:=true;
  12268. exit;
  12269. end;
  12270. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12271. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12272. begin
  12273. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12274. RemoveInstruction(hp1);
  12275. Result:=true;
  12276. exit;
  12277. end;
  12278. {$ifdef x86_64}
  12279. S_LQ:
  12280. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12281. begin
  12282. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12283. RemoveInstruction(hp1);
  12284. Result:=true;
  12285. exit;
  12286. end;
  12287. {$endif x86_64}
  12288. else
  12289. ;
  12290. end;
  12291. { we cannot get rid of the and, but can we get rid of the movz ?}
  12292. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12293. begin
  12294. case taicpu(p).opsize Of
  12295. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12296. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12297. begin
  12298. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12299. RemoveCurrentP(p,hp1);
  12300. Result:=true;
  12301. exit;
  12302. end;
  12303. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12304. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12305. begin
  12306. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12307. RemoveCurrentP(p,hp1);
  12308. Result:=true;
  12309. exit;
  12310. end;
  12311. {$ifdef x86_64}
  12312. S_LQ:
  12313. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12314. begin
  12315. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12316. RemoveCurrentP(p,hp1);
  12317. Result:=true;
  12318. exit;
  12319. end;
  12320. {$endif x86_64}
  12321. else
  12322. ;
  12323. end;
  12324. end;
  12325. end;
  12326. { changes some movzx constructs to faster synonyms (all examples
  12327. are given with eax/ax, but are also valid for other registers)}
  12328. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12329. begin
  12330. case taicpu(p).opsize of
  12331. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12332. (the machine code is equivalent to movzbl %al,%eax), but the
  12333. code generator still generates that assembler instruction and
  12334. it is silently converted. This should probably be checked.
  12335. [Kit] }
  12336. S_BW:
  12337. begin
  12338. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12339. (
  12340. not IsMOVZXAcceptable
  12341. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12342. or (
  12343. (cs_opt_size in current_settings.optimizerswitches) and
  12344. (taicpu(p).oper[1]^.reg = NR_AX)
  12345. )
  12346. ) then
  12347. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12348. begin
  12349. DebugMsg(SPeepholeOptimization + 'var7',p);
  12350. taicpu(p).opcode := A_AND;
  12351. taicpu(p).changeopsize(S_W);
  12352. taicpu(p).loadConst(0,$ff);
  12353. Result := True;
  12354. end
  12355. else if not IsMOVZXAcceptable and
  12356. GetNextInstruction(p, hp1) and
  12357. (tai(hp1).typ = ait_instruction) and
  12358. (taicpu(hp1).opcode = A_AND) and
  12359. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12360. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12361. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12362. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12363. begin
  12364. DebugMsg(SPeepholeOptimization + 'var8',p);
  12365. taicpu(p).opcode := A_MOV;
  12366. taicpu(p).changeopsize(S_W);
  12367. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12368. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12369. Result := True;
  12370. end;
  12371. end;
  12372. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12373. S_BL:
  12374. if not IsMOVZXAcceptable then
  12375. begin
  12376. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12377. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12378. begin
  12379. DebugMsg(SPeepholeOptimization + 'var9',p);
  12380. taicpu(p).opcode := A_AND;
  12381. taicpu(p).changeopsize(S_L);
  12382. taicpu(p).loadConst(0,$ff);
  12383. Result := True;
  12384. end
  12385. else if GetNextInstruction(p, hp1) and
  12386. (tai(hp1).typ = ait_instruction) and
  12387. (taicpu(hp1).opcode = A_AND) and
  12388. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12389. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12390. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12391. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12392. begin
  12393. DebugMsg(SPeepholeOptimization + 'var10',p);
  12394. taicpu(p).opcode := A_MOV;
  12395. taicpu(p).changeopsize(S_L);
  12396. { do not use R_SUBWHOLE
  12397. as movl %rdx,%eax
  12398. is invalid in assembler PM }
  12399. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12400. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12401. Result := True;
  12402. end;
  12403. end;
  12404. {$endif i8086}
  12405. S_WL:
  12406. if not IsMOVZXAcceptable then
  12407. begin
  12408. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12409. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12410. begin
  12411. DebugMsg(SPeepholeOptimization + 'var11',p);
  12412. taicpu(p).opcode := A_AND;
  12413. taicpu(p).changeopsize(S_L);
  12414. taicpu(p).loadConst(0,$ffff);
  12415. Result := True;
  12416. end
  12417. else if GetNextInstruction(p, hp1) and
  12418. (tai(hp1).typ = ait_instruction) and
  12419. (taicpu(hp1).opcode = A_AND) and
  12420. (taicpu(hp1).oper[0]^.typ = top_const) and
  12421. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12422. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12423. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12424. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12425. begin
  12426. DebugMsg(SPeepholeOptimization + 'var12',p);
  12427. taicpu(p).opcode := A_MOV;
  12428. taicpu(p).changeopsize(S_L);
  12429. { do not use R_SUBWHOLE
  12430. as movl %rdx,%eax
  12431. is invalid in assembler PM }
  12432. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12433. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12434. Result := True;
  12435. end;
  12436. end;
  12437. else
  12438. InternalError(2017050705);
  12439. end;
  12440. end
  12441. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12442. begin
  12443. if GetNextInstruction(p, hp1) and
  12444. (tai(hp1).typ = ait_instruction) and
  12445. (taicpu(hp1).opcode = A_AND) and
  12446. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12447. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12448. begin
  12449. //taicpu(p).opcode := A_MOV;
  12450. case taicpu(p).opsize Of
  12451. S_BL:
  12452. begin
  12453. DebugMsg(SPeepholeOptimization + 'var13',p);
  12454. taicpu(hp1).changeopsize(S_L);
  12455. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12456. end;
  12457. S_WL:
  12458. begin
  12459. DebugMsg(SPeepholeOptimization + 'var14',p);
  12460. taicpu(hp1).changeopsize(S_L);
  12461. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12462. end;
  12463. S_BW:
  12464. begin
  12465. DebugMsg(SPeepholeOptimization + 'var15',p);
  12466. taicpu(hp1).changeopsize(S_W);
  12467. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12468. end;
  12469. else
  12470. Internalerror(2017050704)
  12471. end;
  12472. Result := True;
  12473. end;
  12474. end;
  12475. end;
  12476. end;
  12477. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12478. var
  12479. hp1, hp2 : tai;
  12480. MaskLength : Cardinal;
  12481. MaskedBits : TCgInt;
  12482. ActiveReg : TRegister;
  12483. begin
  12484. Result:=false;
  12485. { There are no optimisations for reference targets }
  12486. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12487. Exit;
  12488. while GetNextInstruction(p, hp1) and
  12489. (hp1.typ = ait_instruction) do
  12490. begin
  12491. if (taicpu(p).oper[0]^.typ = top_const) then
  12492. begin
  12493. case taicpu(hp1).opcode of
  12494. A_AND:
  12495. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12496. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12497. { the second register must contain the first one, so compare their subreg types }
  12498. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12499. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12500. { change
  12501. and const1, reg
  12502. and const2, reg
  12503. to
  12504. and (const1 and const2), reg
  12505. }
  12506. begin
  12507. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12508. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12509. RemoveCurrentP(p, hp1);
  12510. Result:=true;
  12511. exit;
  12512. end;
  12513. A_CMP:
  12514. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12515. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12516. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12517. { Just check that the condition on the next instruction is compatible }
  12518. GetNextInstruction(hp1, hp2) and
  12519. (hp2.typ = ait_instruction) and
  12520. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12521. then
  12522. { change
  12523. and 2^n, reg
  12524. cmp 2^n, reg
  12525. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12526. to
  12527. and 2^n, reg
  12528. test reg, reg
  12529. j(~c) / set(~c) / cmov(~c)
  12530. }
  12531. begin
  12532. { Keep TEST instruction in, rather than remove it, because
  12533. it may trigger other optimisations such as MovAndTest2Test }
  12534. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12535. taicpu(hp1).opcode := A_TEST;
  12536. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12537. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12538. Result := True;
  12539. Exit;
  12540. end
  12541. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12542. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12543. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12544. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12545. { change
  12546. and $ff/$ff/$ffff, reg
  12547. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12548. dealloc reg
  12549. to
  12550. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12551. }
  12552. begin
  12553. TransferUsedRegs(TmpUsedRegs);
  12554. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12555. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12556. begin
  12557. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12558. case taicpu(p).oper[0]^.val of
  12559. $ff:
  12560. begin
  12561. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12562. taicpu(hp1).opsize:=S_B;
  12563. end;
  12564. $ffff:
  12565. begin
  12566. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12567. taicpu(hp1).opsize:=S_W;
  12568. end;
  12569. $ffffffff:
  12570. begin
  12571. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12572. taicpu(hp1).opsize:=S_L;
  12573. end;
  12574. else
  12575. Internalerror(2023030401);
  12576. end;
  12577. RemoveCurrentP(p);
  12578. Result := True;
  12579. Exit;
  12580. end;
  12581. end;
  12582. A_MOVZX:
  12583. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12584. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12585. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12586. (
  12587. (
  12588. (taicpu(p).opsize=S_W) and
  12589. (taicpu(hp1).opsize=S_BW)
  12590. ) or
  12591. (
  12592. (taicpu(p).opsize=S_L) and
  12593. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12594. )
  12595. {$ifdef x86_64}
  12596. or
  12597. (
  12598. (taicpu(p).opsize=S_Q) and
  12599. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12600. )
  12601. {$endif x86_64}
  12602. ) then
  12603. begin
  12604. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12605. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12606. ) or
  12607. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12608. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12609. then
  12610. begin
  12611. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12612. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12613. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12614. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12615. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12616. }
  12617. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12618. RemoveInstruction(hp1);
  12619. { See if there are other optimisations possible }
  12620. Continue;
  12621. end;
  12622. end;
  12623. A_SHL:
  12624. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12625. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12626. begin
  12627. {$ifopt R+}
  12628. {$define RANGE_WAS_ON}
  12629. {$R-}
  12630. {$endif}
  12631. { get length of potential and mask }
  12632. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12633. { really a mask? }
  12634. {$ifdef RANGE_WAS_ON}
  12635. {$R+}
  12636. {$endif}
  12637. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12638. { unmasked part shifted out? }
  12639. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12640. begin
  12641. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12642. RemoveCurrentP(p, hp1);
  12643. Result:=true;
  12644. exit;
  12645. end;
  12646. end;
  12647. A_SHR:
  12648. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12649. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12650. (taicpu(hp1).oper[0]^.val <= 63) then
  12651. begin
  12652. { Does SHR combined with the AND cover all the bits?
  12653. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12654. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12655. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12656. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12657. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12658. begin
  12659. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12660. RemoveCurrentP(p, hp1);
  12661. Result := True;
  12662. Exit;
  12663. end;
  12664. end;
  12665. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12666. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12667. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12668. begin
  12669. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12670. (
  12671. (
  12672. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12673. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12674. ) or (
  12675. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12676. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12677. {$ifdef x86_64}
  12678. ) or (
  12679. (taicpu(hp1).opsize = S_LQ) and
  12680. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12681. {$endif x86_64}
  12682. )
  12683. ) then
  12684. begin
  12685. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12686. begin
  12687. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12688. RemoveInstruction(hp1);
  12689. { See if there are other optimisations possible }
  12690. Continue;
  12691. end;
  12692. { The super-registers are the same though.
  12693. Note that this change by itself doesn't improve
  12694. code speed, but it opens up other optimisations. }
  12695. {$ifdef x86_64}
  12696. { Convert 64-bit register to 32-bit }
  12697. case taicpu(hp1).opsize of
  12698. S_BQ:
  12699. begin
  12700. taicpu(hp1).opsize := S_BL;
  12701. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12702. end;
  12703. S_WQ:
  12704. begin
  12705. taicpu(hp1).opsize := S_WL;
  12706. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12707. end
  12708. else
  12709. ;
  12710. end;
  12711. {$endif x86_64}
  12712. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12713. taicpu(hp1).opcode := A_MOVZX;
  12714. { See if there are other optimisations possible }
  12715. Continue;
  12716. end;
  12717. end;
  12718. else
  12719. ;
  12720. end;
  12721. end
  12722. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12723. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12724. begin
  12725. {$ifdef x86_64}
  12726. if (taicpu(p).opsize = S_Q) then
  12727. begin
  12728. { Never necessary }
  12729. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12730. RemoveCurrentP(p, hp1);
  12731. Result := True;
  12732. Exit;
  12733. end;
  12734. {$endif x86_64}
  12735. { Forward check to determine necessity of and %reg,%reg }
  12736. TransferUsedRegs(TmpUsedRegs);
  12737. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12738. { Saves on a bunch of dereferences }
  12739. ActiveReg := taicpu(p).oper[1]^.reg;
  12740. case taicpu(hp1).opcode of
  12741. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12742. if (
  12743. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12744. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12745. ) and
  12746. (
  12747. (taicpu(hp1).opcode <> A_MOV) or
  12748. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12749. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12750. ) and
  12751. not (
  12752. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12753. (taicpu(hp1).opcode = A_MOV) and
  12754. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12755. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12756. ) and
  12757. (
  12758. (
  12759. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12760. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12761. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12762. ) or
  12763. (
  12764. {$ifdef x86_64}
  12765. (
  12766. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12767. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12768. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12769. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12770. ) and
  12771. {$endif x86_64}
  12772. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12773. )
  12774. ) then
  12775. begin
  12776. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12777. RemoveCurrentP(p, hp1);
  12778. Result := True;
  12779. Exit;
  12780. end;
  12781. A_ADD,
  12782. A_AND,
  12783. A_BSF,
  12784. A_BSR,
  12785. A_BTC,
  12786. A_BTR,
  12787. A_BTS,
  12788. A_OR,
  12789. A_SUB,
  12790. A_XOR:
  12791. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12792. if (
  12793. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12794. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12795. ) and
  12796. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12797. begin
  12798. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12799. RemoveCurrentP(p, hp1);
  12800. Result := True;
  12801. Exit;
  12802. end;
  12803. A_CMP,
  12804. A_TEST:
  12805. if (
  12806. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12807. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12808. ) and
  12809. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12810. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12811. begin
  12812. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12813. RemoveCurrentP(p, hp1);
  12814. Result := True;
  12815. Exit;
  12816. end;
  12817. A_BSWAP,
  12818. A_NEG,
  12819. A_NOT:
  12820. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12821. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12822. begin
  12823. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12824. RemoveCurrentP(p, hp1);
  12825. Result := True;
  12826. Exit;
  12827. end;
  12828. else
  12829. ;
  12830. end;
  12831. end;
  12832. if (taicpu(hp1).is_jmp) and
  12833. (taicpu(hp1).opcode<>A_JMP) and
  12834. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12835. begin
  12836. { change
  12837. and x, reg
  12838. jxx
  12839. to
  12840. test x, reg
  12841. jxx
  12842. if reg is deallocated before the
  12843. jump, but only if it's a conditional jump (PFV)
  12844. }
  12845. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12846. taicpu(p).opcode := A_TEST;
  12847. Exit;
  12848. end;
  12849. Break;
  12850. end;
  12851. { Lone AND tests }
  12852. if (taicpu(p).oper[0]^.typ = top_const) then
  12853. begin
  12854. {
  12855. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12856. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12857. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12858. }
  12859. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12860. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12861. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12862. begin
  12863. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12864. if taicpu(p).opsize = S_L then
  12865. begin
  12866. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12867. Result := True;
  12868. end;
  12869. end;
  12870. end;
  12871. { Backward check to determine necessity of and %reg,%reg }
  12872. if (taicpu(p).oper[0]^.typ = top_reg) and
  12873. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12874. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12875. GetLastInstruction(p, hp2) and
  12876. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12877. { Check size of adjacent instruction to determine if the AND is
  12878. effectively a null operation }
  12879. (
  12880. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12881. { Note: Don't include S_Q }
  12882. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12883. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12884. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12885. ) then
  12886. begin
  12887. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12888. { If GetNextInstruction returned False, hp1 will be nil }
  12889. RemoveCurrentP(p, hp1);
  12890. Result := True;
  12891. Exit;
  12892. end;
  12893. end;
  12894. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12895. var
  12896. hp1, hp2: tai;
  12897. NewRef: TReference;
  12898. Distance: Cardinal;
  12899. TempTracking: TAllUsedRegs;
  12900. { This entire nested function is used in an if-statement below, but we
  12901. want to avoid all the used reg transfers and GetNextInstruction calls
  12902. until we really have to check }
  12903. function MemRegisterNotUsedLater: Boolean; inline;
  12904. var
  12905. hp2: tai;
  12906. begin
  12907. TransferUsedRegs(TmpUsedRegs);
  12908. hp2 := p;
  12909. repeat
  12910. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12911. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12912. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12913. end;
  12914. begin
  12915. Result := False;
  12916. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12917. (taicpu(p).oper[1]^.typ = top_reg) then
  12918. begin
  12919. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12920. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12921. (hp1.typ <> ait_instruction) or
  12922. not
  12923. (
  12924. (cs_opt_level3 in current_settings.optimizerswitches) or
  12925. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12926. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12927. ) then
  12928. Exit;
  12929. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12930. addq $x, %rax
  12931. movq %rax, %rdx
  12932. sarq $63, %rdx
  12933. (%rax still in use)
  12934. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12935. leaq $x(%rax),%rdx
  12936. addq $x, %rax
  12937. sarq $63, %rdx
  12938. ...which is okay since it breaks the dependency chain between
  12939. addq and movq, but if OptPass2MOV is called first:
  12940. addq $x, %rax
  12941. cqto
  12942. ...which is better in all ways, taking only 2 cycles to execute
  12943. and much smaller in code size.
  12944. }
  12945. { The extra register tracking is quite strenuous }
  12946. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12947. MatchInstruction(hp1, A_MOV, []) then
  12948. begin
  12949. { Update the register tracking to the MOV instruction }
  12950. CopyUsedRegs(TempTracking);
  12951. hp2 := p;
  12952. repeat
  12953. UpdateUsedRegs(tai(hp2.Next));
  12954. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12955. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12956. OptPass2ADD get called again }
  12957. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12958. begin
  12959. { Reset the tracking to the current instruction }
  12960. RestoreUsedRegs(TempTracking);
  12961. ReleaseUsedRegs(TempTracking);
  12962. Result := True;
  12963. Exit;
  12964. end;
  12965. { Reset the tracking to the current instruction }
  12966. RestoreUsedRegs(TempTracking);
  12967. ReleaseUsedRegs(TempTracking);
  12968. { If OptPass2MOV returned True, we don't need to set Result to
  12969. True if hp1 didn't change because the ADD instruction didn't
  12970. get modified and we'll be evaluating hp1 again when the
  12971. peephole optimizer reaches it }
  12972. end;
  12973. { Change:
  12974. add %reg2,%reg1
  12975. (%reg2 not modified in between)
  12976. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12977. To:
  12978. mov/s/z #(%reg1,%reg2),%reg1
  12979. }
  12980. if (taicpu(p).oper[0]^.typ = top_reg) and
  12981. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12982. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12983. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12984. (
  12985. (
  12986. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12987. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12988. { r/esp cannot be an index }
  12989. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12990. ) or (
  12991. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12992. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12993. )
  12994. ) and (
  12995. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12996. (
  12997. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12998. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12999. MemRegisterNotUsedLater
  13000. )
  13001. ) then
  13002. begin
  13003. if (
  13004. { Instructions are guaranteed to be adjacent on -O2 and under }
  13005. (cs_opt_level3 in current_settings.optimizerswitches) and
  13006. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13007. ) then
  13008. begin
  13009. { If the other register is used in between, move the MOV
  13010. instruction to right after the ADD instruction so a
  13011. saving can still be made }
  13012. Asml.Remove(hp1);
  13013. Asml.InsertAfter(hp1, p);
  13014. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13015. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13016. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13017. RemoveCurrentp(p, hp1);
  13018. end
  13019. else
  13020. begin
  13021. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13022. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13023. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13024. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13025. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13026. { hp1 may not be the immediate next instruction under -O3 }
  13027. RemoveCurrentp(p)
  13028. else
  13029. RemoveCurrentp(p, hp1);
  13030. end;
  13031. Result := True;
  13032. Exit;
  13033. end;
  13034. { Change:
  13035. addl/q $x,%reg1
  13036. movl/q %reg1,%reg2
  13037. To:
  13038. leal/q $x(%reg1),%reg2
  13039. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13040. Breaks the dependency chain.
  13041. }
  13042. if (taicpu(p).oper[0]^.typ = top_const) and
  13043. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13044. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13045. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13046. (
  13047. { Instructions are guaranteed to be adjacent on -O2 and under }
  13048. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13049. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13050. ) then
  13051. begin
  13052. TransferUsedRegs(TmpUsedRegs);
  13053. hp2 := p;
  13054. repeat
  13055. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13056. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13057. if (
  13058. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13059. not (cs_opt_size in current_settings.optimizerswitches) or
  13060. (
  13061. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13062. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13063. )
  13064. ) then
  13065. begin
  13066. { Change the MOV instruction to a LEA instruction, and update the
  13067. first operand }
  13068. reference_reset(NewRef, 1, []);
  13069. NewRef.base := taicpu(p).oper[1]^.reg;
  13070. NewRef.scalefactor := 1;
  13071. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13072. taicpu(hp1).opcode := A_LEA;
  13073. taicpu(hp1).loadref(0, NewRef);
  13074. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13075. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13076. begin
  13077. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13078. { Move what is now the LEA instruction to before the ADD instruction }
  13079. Asml.Remove(hp1);
  13080. Asml.InsertBefore(hp1, p);
  13081. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13082. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13083. p := hp1;
  13084. end
  13085. else
  13086. begin
  13087. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13088. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13089. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13090. { hp1 may not be the immediate next instruction under -O3 }
  13091. RemoveCurrentp(p)
  13092. else
  13093. RemoveCurrentp(p, hp1);
  13094. end;
  13095. Result := True;
  13096. end;
  13097. end;
  13098. end;
  13099. end;
  13100. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13101. var
  13102. SubReg: TSubRegister;
  13103. begin
  13104. Result:=false;
  13105. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13106. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13107. with taicpu(p).oper[0]^.ref^ do
  13108. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13109. begin
  13110. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13111. begin
  13112. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13113. taicpu(p).opcode := A_ADD;
  13114. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13115. Result := True;
  13116. end
  13117. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13118. begin
  13119. if (base <> NR_NO) then
  13120. begin
  13121. if (scalefactor <= 1) then
  13122. begin
  13123. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13124. taicpu(p).opcode := A_ADD;
  13125. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13126. Result := True;
  13127. end;
  13128. end
  13129. else
  13130. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13131. if (scalefactor in [2, 4, 8]) then
  13132. begin
  13133. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13134. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13135. taicpu(p).opcode := A_SHL;
  13136. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13137. Result := True;
  13138. end;
  13139. end;
  13140. end;
  13141. end;
  13142. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13143. var
  13144. hp1, hp2: tai;
  13145. NewRef: TReference;
  13146. Distance: Cardinal;
  13147. TempTracking: TAllUsedRegs;
  13148. begin
  13149. Result := False;
  13150. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13151. MatchOpType(taicpu(p),top_const,top_reg) then
  13152. begin
  13153. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13154. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13155. (hp1.typ <> ait_instruction) or
  13156. not
  13157. (
  13158. (cs_opt_level3 in current_settings.optimizerswitches) or
  13159. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13160. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13161. ) then
  13162. Exit;
  13163. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13164. subq $x, %rax
  13165. movq %rax, %rdx
  13166. sarq $63, %rdx
  13167. (%rax still in use)
  13168. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13169. leaq $-x(%rax),%rdx
  13170. movq $x, %rax
  13171. sarq $63, %rdx
  13172. ...which is okay since it breaks the dependency chain between
  13173. subq and movq, but if OptPass2MOV is called first:
  13174. subq $x, %rax
  13175. cqto
  13176. ...which is better in all ways, taking only 2 cycles to execute
  13177. and much smaller in code size.
  13178. }
  13179. { The extra register tracking is quite strenuous }
  13180. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13181. MatchInstruction(hp1, A_MOV, []) then
  13182. begin
  13183. { Update the register tracking to the MOV instruction }
  13184. CopyUsedRegs(TempTracking);
  13185. hp2 := p;
  13186. repeat
  13187. UpdateUsedRegs(tai(hp2.Next));
  13188. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13189. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13190. OptPass2SUB get called again }
  13191. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13192. begin
  13193. { Reset the tracking to the current instruction }
  13194. RestoreUsedRegs(TempTracking);
  13195. ReleaseUsedRegs(TempTracking);
  13196. Result := True;
  13197. Exit;
  13198. end;
  13199. { Reset the tracking to the current instruction }
  13200. RestoreUsedRegs(TempTracking);
  13201. ReleaseUsedRegs(TempTracking);
  13202. { If OptPass2MOV returned True, we don't need to set Result to
  13203. True if hp1 didn't change because the SUB instruction didn't
  13204. get modified and we'll be evaluating hp1 again when the
  13205. peephole optimizer reaches it }
  13206. end;
  13207. { Change:
  13208. subl/q $x,%reg1
  13209. movl/q %reg1,%reg2
  13210. To:
  13211. leal/q $-x(%reg1),%reg2
  13212. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13213. Breaks the dependency chain and potentially permits the removal of
  13214. a CMP instruction if one follows.
  13215. }
  13216. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13217. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13218. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13219. (
  13220. { Instructions are guaranteed to be adjacent on -O2 and under }
  13221. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13222. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13223. ) then
  13224. begin
  13225. TransferUsedRegs(TmpUsedRegs);
  13226. hp2 := p;
  13227. repeat
  13228. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13229. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13230. if (
  13231. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13232. not (cs_opt_size in current_settings.optimizerswitches) or
  13233. (
  13234. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13235. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13236. )
  13237. ) then
  13238. begin
  13239. { Change the MOV instruction to a LEA instruction, and update the
  13240. first operand }
  13241. reference_reset(NewRef, 1, []);
  13242. NewRef.base := taicpu(p).oper[1]^.reg;
  13243. NewRef.scalefactor := 1;
  13244. NewRef.offset := -taicpu(p).oper[0]^.val;
  13245. taicpu(hp1).opcode := A_LEA;
  13246. taicpu(hp1).loadref(0, NewRef);
  13247. TransferUsedRegs(TmpUsedRegs);
  13248. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13249. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13250. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13251. begin
  13252. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13253. { Move what is now the LEA instruction to before the SUB instruction }
  13254. Asml.Remove(hp1);
  13255. Asml.InsertBefore(hp1, p);
  13256. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13257. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13258. p := hp1;
  13259. end
  13260. else
  13261. begin
  13262. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13263. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13264. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13265. { hp1 may not be the immediate next instruction under -O3 }
  13266. RemoveCurrentp(p)
  13267. else
  13268. RemoveCurrentp(p, hp1);
  13269. end;
  13270. Result := True;
  13271. end;
  13272. end;
  13273. end;
  13274. end;
  13275. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13276. begin
  13277. { we can skip all instructions not messing with the stack pointer }
  13278. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13279. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13280. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13281. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13282. ({(taicpu(hp1).ops=0) or }
  13283. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13284. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13285. ) and }
  13286. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13287. )
  13288. ) do
  13289. GetNextInstruction(hp1,hp1);
  13290. Result:=assigned(hp1);
  13291. end;
  13292. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13293. var
  13294. hp1, hp2, hp3, hp4, hp5: tai;
  13295. begin
  13296. Result:=false;
  13297. hp5:=nil;
  13298. { replace
  13299. leal(q) x(<stackpointer>),<stackpointer>
  13300. call procname
  13301. leal(q) -x(<stackpointer>),<stackpointer>
  13302. ret
  13303. by
  13304. jmp procname
  13305. but do it only on level 4 because it destroys stack back traces
  13306. }
  13307. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13308. MatchOpType(taicpu(p),top_ref,top_reg) and
  13309. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13310. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13311. { the -8 or -24 are not required, but bail out early if possible,
  13312. higher values are unlikely }
  13313. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13314. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13315. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13316. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13317. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13318. GetNextInstruction(p, hp1) and
  13319. { Take a copy of hp1 }
  13320. SetAndTest(hp1, hp4) and
  13321. { trick to skip label }
  13322. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13323. SkipSimpleInstructions(hp1) and
  13324. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13325. GetNextInstruction(hp1, hp2) and
  13326. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13327. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13328. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13329. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13330. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13331. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13332. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13333. { Segment register will be NR_NO }
  13334. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13335. GetNextInstruction(hp2, hp3) and
  13336. { trick to skip label }
  13337. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13338. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13339. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13340. SetAndTest(hp3,hp5) and
  13341. GetNextInstruction(hp3,hp3) and
  13342. MatchInstruction(hp3,A_RET,[S_NO])
  13343. )
  13344. ) and
  13345. (taicpu(hp3).ops=0) then
  13346. begin
  13347. taicpu(hp1).opcode := A_JMP;
  13348. taicpu(hp1).is_jmp := true;
  13349. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13350. RemoveCurrentP(p, hp4);
  13351. RemoveInstruction(hp2);
  13352. RemoveInstruction(hp3);
  13353. if Assigned(hp5) then
  13354. begin
  13355. AsmL.Remove(hp5);
  13356. ASmL.InsertBefore(hp5,hp1)
  13357. end;
  13358. Result:=true;
  13359. end;
  13360. end;
  13361. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13362. {$ifdef x86_64}
  13363. var
  13364. hp1, hp2, hp3, hp4, hp5: tai;
  13365. {$endif x86_64}
  13366. begin
  13367. Result:=false;
  13368. {$ifdef x86_64}
  13369. hp5:=nil;
  13370. { replace
  13371. push %rax
  13372. call procname
  13373. pop %rcx
  13374. ret
  13375. by
  13376. jmp procname
  13377. but do it only on level 4 because it destroys stack back traces
  13378. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13379. for all supported calling conventions
  13380. }
  13381. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13382. MatchOpType(taicpu(p),top_reg) and
  13383. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13384. GetNextInstruction(p, hp1) and
  13385. { Take a copy of hp1 }
  13386. SetAndTest(hp1, hp4) and
  13387. { trick to skip label }
  13388. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13389. SkipSimpleInstructions(hp1) and
  13390. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13391. GetNextInstruction(hp1, hp2) and
  13392. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13393. MatchOpType(taicpu(hp2),top_reg) and
  13394. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13395. GetNextInstruction(hp2, hp3) and
  13396. { trick to skip label }
  13397. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13398. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13399. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13400. SetAndTest(hp3,hp5) and
  13401. GetNextInstruction(hp3,hp3) and
  13402. MatchInstruction(hp3,A_RET,[S_NO])
  13403. )
  13404. ) and
  13405. (taicpu(hp3).ops=0) then
  13406. begin
  13407. taicpu(hp1).opcode := A_JMP;
  13408. taicpu(hp1).is_jmp := true;
  13409. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13410. RemoveCurrentP(p, hp4);
  13411. RemoveInstruction(hp2);
  13412. RemoveInstruction(hp3);
  13413. if Assigned(hp5) then
  13414. begin
  13415. AsmL.Remove(hp5);
  13416. ASmL.InsertBefore(hp5,hp1)
  13417. end;
  13418. Result:=true;
  13419. end;
  13420. {$endif x86_64}
  13421. end;
  13422. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13423. var
  13424. Value, RegName: string;
  13425. begin
  13426. Result:=false;
  13427. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13428. begin
  13429. case taicpu(p).oper[0]^.val of
  13430. 0:
  13431. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13432. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13433. begin
  13434. { change "mov $0,%reg" into "xor %reg,%reg" }
  13435. taicpu(p).opcode := A_XOR;
  13436. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13437. Result := True;
  13438. {$ifdef x86_64}
  13439. end
  13440. else if (taicpu(p).opsize = S_Q) then
  13441. begin
  13442. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13443. { The actual optimization }
  13444. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13445. taicpu(p).changeopsize(S_L);
  13446. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13447. Result := True;
  13448. end;
  13449. $1..$FFFFFFFF:
  13450. begin
  13451. { Code size reduction by J. Gareth "Kit" Moreton }
  13452. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13453. case taicpu(p).opsize of
  13454. S_Q:
  13455. begin
  13456. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13457. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13458. { The actual optimization }
  13459. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13460. taicpu(p).changeopsize(S_L);
  13461. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13462. Result := True;
  13463. end;
  13464. else
  13465. { Do nothing };
  13466. end;
  13467. {$endif x86_64}
  13468. end;
  13469. -1:
  13470. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13471. if (cs_opt_size in current_settings.optimizerswitches) and
  13472. (taicpu(p).opsize <> S_B) and
  13473. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13474. begin
  13475. { change "mov $-1,%reg" into "or $-1,%reg" }
  13476. { NOTES:
  13477. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13478. - This operation creates a false dependency on the register, so only do it when optimising for size
  13479. - 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
  13480. }
  13481. taicpu(p).opcode := A_OR;
  13482. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13483. Result := True;
  13484. end;
  13485. else
  13486. { Do nothing };
  13487. end;
  13488. end;
  13489. end;
  13490. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13491. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13492. begin
  13493. Result := False;
  13494. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13495. Exit;
  13496. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13497. so don't bother optimising }
  13498. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13499. Exit;
  13500. if (taicpu(p).oper[0]^.typ <> top_const) or
  13501. { If the value can fit into an 8-bit signed integer, a smaller
  13502. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13503. falls within this range }
  13504. (
  13505. (taicpu(p).oper[0]^.val > -128) and
  13506. (taicpu(p).oper[0]^.val <= 127)
  13507. ) then
  13508. Exit;
  13509. { If we're optimising for size, this is acceptable }
  13510. if (cs_opt_size in current_settings.optimizerswitches) then
  13511. Exit(True);
  13512. if (taicpu(p).oper[1]^.typ = top_reg) and
  13513. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13514. Exit(True);
  13515. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13516. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13517. Exit(True);
  13518. end;
  13519. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13520. var
  13521. hp1: tai;
  13522. Value: TCGInt;
  13523. begin
  13524. Result := False;
  13525. if MatchOpType(taicpu(p), top_const, top_reg) then
  13526. begin
  13527. { Detect:
  13528. andw x, %ax (0 <= x < $8000)
  13529. ...
  13530. movzwl %ax,%eax
  13531. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13532. }
  13533. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13534. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13535. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13536. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13537. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13538. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13539. begin
  13540. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13541. taicpu(hp1).opcode := A_CWDE;
  13542. taicpu(hp1).clearop(0);
  13543. taicpu(hp1).clearop(1);
  13544. taicpu(hp1).ops := 0;
  13545. { A change was made, but not with p, so don't set Result, but
  13546. notify the compiler that a change was made }
  13547. Include(OptsToCheck, aoc_ForceNewIteration);
  13548. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13549. end;
  13550. end;
  13551. { If "not x" is a power of 2 (popcnt = 1), change:
  13552. and $x, %reg/ref
  13553. To:
  13554. btr lb(x), %reg/ref
  13555. }
  13556. if IsBTXAcceptable(p) and
  13557. (
  13558. { Make sure a TEST doesn't follow that plays with the register }
  13559. not GetNextInstruction(p, hp1) or
  13560. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13561. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13562. ) then
  13563. begin
  13564. {$push}{$R-}{$Q-}
  13565. { Value is a sign-extended 32-bit integer - just correct it
  13566. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13567. checks to see if this operand is an immediate. }
  13568. Value := not taicpu(p).oper[0]^.val;
  13569. {$pop}
  13570. {$ifdef x86_64}
  13571. if taicpu(p).opsize = S_L then
  13572. {$endif x86_64}
  13573. Value := Value and $FFFFFFFF;
  13574. if (PopCnt(QWord(Value)) = 1) then
  13575. begin
  13576. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13577. taicpu(p).opcode := A_BTR;
  13578. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13579. Result := True;
  13580. Exit;
  13581. end;
  13582. end;
  13583. end;
  13584. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13585. begin
  13586. Result := False;
  13587. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13588. Exit;
  13589. { Convert:
  13590. movswl %ax,%eax -> cwtl
  13591. movslq %eax,%rax -> cdqe
  13592. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13593. refer to the same opcode and depends only on the assembler's
  13594. current operand-size attribute. [Kit]
  13595. }
  13596. with taicpu(p) do
  13597. case opsize of
  13598. S_WL:
  13599. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13600. begin
  13601. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13602. opcode := A_CWDE;
  13603. clearop(0);
  13604. clearop(1);
  13605. ops := 0;
  13606. Result := True;
  13607. end;
  13608. {$ifdef x86_64}
  13609. S_LQ:
  13610. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13611. begin
  13612. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13613. opcode := A_CDQE;
  13614. clearop(0);
  13615. clearop(1);
  13616. ops := 0;
  13617. Result := True;
  13618. end;
  13619. {$endif x86_64}
  13620. else
  13621. ;
  13622. end;
  13623. end;
  13624. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13625. var
  13626. hp1, hp2: tai;
  13627. IdentityMask, Shift: TCGInt;
  13628. LimitSize: Topsize;
  13629. DoNotMerge: Boolean;
  13630. begin
  13631. Result := False;
  13632. { All these optimisations work on "shr const,%reg" }
  13633. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13634. Exit;
  13635. DoNotMerge := False;
  13636. Shift := taicpu(p).oper[0]^.val;
  13637. LimitSize := taicpu(p).opsize;
  13638. hp1 := p;
  13639. repeat
  13640. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13641. Break;
  13642. { Detect:
  13643. shr x, %reg
  13644. and y, %reg
  13645. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13646. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13647. }
  13648. case taicpu(hp1).opcode of
  13649. A_AND:
  13650. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13651. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13652. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13653. begin
  13654. { Make sure the FLAGS register isn't in use }
  13655. TransferUsedRegs(TmpUsedRegs);
  13656. hp2 := p;
  13657. repeat
  13658. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13659. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13660. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13661. begin
  13662. { Generate the identity mask }
  13663. case taicpu(p).opsize of
  13664. S_B:
  13665. IdentityMask := $FF shr Shift;
  13666. S_W:
  13667. IdentityMask := $FFFF shr Shift;
  13668. S_L:
  13669. IdentityMask := $FFFFFFFF shr Shift;
  13670. {$ifdef x86_64}
  13671. S_Q:
  13672. { We need to force the operands to be unsigned 64-bit
  13673. integers otherwise the wrong value is generated }
  13674. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13675. {$endif x86_64}
  13676. else
  13677. InternalError(2022081501);
  13678. end;
  13679. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13680. begin
  13681. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13682. { All the possible 1 bits are covered, so we can remove the AND }
  13683. hp2 := tai(hp1.Previous);
  13684. RemoveInstruction(hp1);
  13685. { p wasn't actually changed, so don't set Result to True,
  13686. but a change was nonetheless made elsewhere }
  13687. Include(OptsToCheck, aoc_ForceNewIteration);
  13688. { Do another pass in case other AND or MOVZX instructions
  13689. follow }
  13690. hp1 := hp2;
  13691. Continue;
  13692. end;
  13693. end;
  13694. end;
  13695. A_TEST, A_CMP, A_Jcc:
  13696. { Skip over conditional jumps and relevant comparisons }
  13697. Continue;
  13698. A_MOVZX:
  13699. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13700. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13701. begin
  13702. { Since the original register is being read as is, subsequent
  13703. SHRs must not be merged at this point }
  13704. DoNotMerge := True;
  13705. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13706. begin
  13707. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13708. begin
  13709. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13710. { All the possible 1 bits are covered, so we can remove the AND }
  13711. hp2 := tai(hp1.Previous);
  13712. RemoveInstruction(hp1);
  13713. hp1 := hp2;
  13714. end
  13715. else { Different register target }
  13716. begin
  13717. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13718. taicpu(hp1).opcode := A_MOV;
  13719. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13720. case taicpu(hp1).opsize of
  13721. S_BW:
  13722. taicpu(hp1).opsize := S_W;
  13723. S_BL, S_WL:
  13724. taicpu(hp1).opsize := S_L;
  13725. else
  13726. InternalError(2022081503);
  13727. end;
  13728. end;
  13729. end
  13730. else if (Shift > 0) and
  13731. (taicpu(p).opsize = S_W) and
  13732. (taicpu(hp1).opsize = S_WL) and
  13733. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13734. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13735. begin
  13736. { Detect:
  13737. shr x, %ax (x > 0)
  13738. ...
  13739. movzwl %ax,%eax
  13740. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13741. }
  13742. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13743. taicpu(hp1).opcode := A_CWDE;
  13744. taicpu(hp1).clearop(0);
  13745. taicpu(hp1).clearop(1);
  13746. taicpu(hp1).ops := 0;
  13747. end;
  13748. { Move onto the next instruction }
  13749. Continue;
  13750. end;
  13751. A_SHL, A_SAL, A_SHR:
  13752. if (taicpu(hp1).opsize <= LimitSize) and
  13753. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13754. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13755. begin
  13756. { Make sure the sizes don't exceed the register size limit
  13757. (measured by the shift value falling below the limit) }
  13758. if taicpu(hp1).opsize < LimitSize then
  13759. LimitSize := taicpu(hp1).opsize;
  13760. if taicpu(hp1).opcode = A_SHR then
  13761. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13762. else
  13763. begin
  13764. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13765. DoNotMerge := True;
  13766. end;
  13767. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13768. Break;
  13769. { Since we've established that the combined shift is within
  13770. limits, we can actually combine the adjacent SHR
  13771. instructions even if they're different sizes }
  13772. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13773. begin
  13774. hp2 := tai(hp1.Previous);
  13775. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13776. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13777. RemoveInstruction(hp1);
  13778. hp1 := hp2;
  13779. end;
  13780. { Move onto the next instruction }
  13781. Continue;
  13782. end;
  13783. else
  13784. ;
  13785. end;
  13786. Break;
  13787. until False;
  13788. { Detect the following (looking backwards):
  13789. shr %cl,%reg
  13790. shr x, %reg
  13791. Swap the two SHR instructions to minimise a pipeline stall.
  13792. }
  13793. if GetLastInstruction(p, hp1) and
  13794. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13795. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13796. { First operand will be %cl }
  13797. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13798. { Just to be sure }
  13799. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13800. begin
  13801. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13802. { Moving the entries this way ensures the register tracking remains correct }
  13803. Asml.Remove(p);
  13804. Asml.InsertBefore(p, hp1);
  13805. p := hp1;
  13806. { Don't set Result to True because the current instruction is now
  13807. "shr %cl,%reg" and there's nothing more we can do with it }
  13808. end;
  13809. end;
  13810. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13811. var
  13812. hp1, hp2: tai;
  13813. Opposite, SecondOpposite: TAsmOp;
  13814. NewCond: TAsmCond;
  13815. begin
  13816. Result := False;
  13817. { Change:
  13818. add/sub 128,(dest)
  13819. To:
  13820. sub/add -128,(dest)
  13821. This generaally takes fewer bytes to encode because -128 can be stored
  13822. in a signed byte, whereas +128 cannot.
  13823. }
  13824. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13825. begin
  13826. if taicpu(p).opcode = A_ADD then
  13827. Opposite := A_SUB
  13828. else
  13829. Opposite := A_ADD;
  13830. { Be careful if the flags are in use, because the CF flag inverts
  13831. when changing from ADD to SUB and vice versa }
  13832. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13833. GetNextInstruction(p, hp1) then
  13834. begin
  13835. TransferUsedRegs(TmpUsedRegs);
  13836. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13837. hp2 := hp1;
  13838. { Scan ahead to check if everything's safe }
  13839. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13840. begin
  13841. if (hp1.typ <> ait_instruction) then
  13842. { Probably unsafe since the flags are still in use }
  13843. Exit;
  13844. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13845. { Stop searching at an unconditional jump }
  13846. Break;
  13847. if not
  13848. (
  13849. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13850. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13851. ) and
  13852. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13853. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13854. Exit;
  13855. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13856. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13857. { Move to the next instruction }
  13858. GetNextInstruction(hp1, hp1);
  13859. end;
  13860. while Assigned(hp2) and (hp2 <> hp1) do
  13861. begin
  13862. NewCond := C_None;
  13863. case taicpu(hp2).condition of
  13864. C_A, C_NBE:
  13865. NewCond := C_BE;
  13866. C_B, C_C, C_NAE:
  13867. NewCond := C_AE;
  13868. C_AE, C_NB, C_NC:
  13869. NewCond := C_B;
  13870. C_BE, C_NA:
  13871. NewCond := C_A;
  13872. else
  13873. { No change needed };
  13874. end;
  13875. if NewCond <> C_None then
  13876. begin
  13877. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13878. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13879. taicpu(hp2).condition := NewCond;
  13880. end
  13881. else
  13882. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13883. begin
  13884. { Because of the flipping of the carry bit, to ensure
  13885. the operation remains equivalent, ADC becomes SBB
  13886. and vice versa, and the constant is not-inverted.
  13887. If multiple ADCs or SBBs appear in a row, each one
  13888. changed causes the carry bit to invert, so they all
  13889. need to be flipped }
  13890. if taicpu(hp2).opcode = A_ADC then
  13891. SecondOpposite := A_SBB
  13892. else
  13893. SecondOpposite := A_ADC;
  13894. if taicpu(hp2).oper[0]^.typ <> top_const then
  13895. { Should have broken out of this optimisation already }
  13896. InternalError(2021112901);
  13897. 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]^) + ' -> ' +
  13898. 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);
  13899. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13900. taicpu(hp2).opcode := SecondOpposite;
  13901. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13902. end;
  13903. { Move to the next instruction }
  13904. GetNextInstruction(hp2, hp2);
  13905. end;
  13906. if (hp2 <> hp1) then
  13907. InternalError(2021111501);
  13908. end;
  13909. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13910. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13911. taicpu(p).opcode := Opposite;
  13912. taicpu(p).oper[0]^.val := -128;
  13913. { No further optimisations can be made on this instruction, so move
  13914. onto the next one to save time }
  13915. p := tai(p.Next);
  13916. UpdateUsedRegs(p);
  13917. Result := True;
  13918. Exit;
  13919. end;
  13920. { Detect:
  13921. add/sub %reg2,(dest)
  13922. add/sub x, (dest)
  13923. (dest can be a register or a reference)
  13924. Swap the instructions to minimise a pipeline stall. This reverses the
  13925. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13926. optimisations could be made.
  13927. }
  13928. if (taicpu(p).oper[0]^.typ = top_reg) and
  13929. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13930. (
  13931. (
  13932. (taicpu(p).oper[1]^.typ = top_reg) and
  13933. { We can try searching further ahead if we're writing to a register }
  13934. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13935. ) or
  13936. (
  13937. (taicpu(p).oper[1]^.typ = top_ref) and
  13938. GetNextInstruction(p, hp1)
  13939. )
  13940. ) and
  13941. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13942. (taicpu(hp1).oper[0]^.typ = top_const) and
  13943. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13944. begin
  13945. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13946. TransferUsedRegs(TmpUsedRegs);
  13947. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13948. hp2 := p;
  13949. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13950. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13951. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13952. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13953. begin
  13954. asml.remove(hp1);
  13955. asml.InsertBefore(hp1, p);
  13956. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13957. Result := True;
  13958. end;
  13959. end;
  13960. end;
  13961. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13962. var
  13963. hp1: tai;
  13964. begin
  13965. Result:=false;
  13966. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13967. while GetNextInstruction(p, hp1) and
  13968. TrySwapMovCmp(p, hp1) do
  13969. begin
  13970. if MatchInstruction(hp1, A_MOV, []) then
  13971. begin
  13972. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13973. begin
  13974. { A little hacky, but since CMP doesn't read the flags, only
  13975. modify them, it's safe if they get scrambled by MOV -> XOR }
  13976. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13977. Result := PostPeepholeOptMov(hp1);
  13978. {$ifdef x86_64}
  13979. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13980. { Used to shrink instruction size }
  13981. PostPeepholeOptXor(hp1);
  13982. {$endif x86_64}
  13983. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13984. end
  13985. else
  13986. begin
  13987. Result := PostPeepholeOptMov(hp1);
  13988. {$ifdef x86_64}
  13989. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13990. { Used to shrink instruction size }
  13991. PostPeepholeOptXor(hp1);
  13992. {$endif x86_64}
  13993. end;
  13994. end;
  13995. { Enabling this flag is actually a null operation, but it marks
  13996. the code as 'modified' during this pass }
  13997. Include(OptsToCheck, aoc_ForceNewIteration);
  13998. end;
  13999. { change "cmp $0, %reg" to "test %reg, %reg" }
  14000. if MatchOpType(taicpu(p),top_const,top_reg) and
  14001. (taicpu(p).oper[0]^.val = 0) then
  14002. begin
  14003. taicpu(p).opcode := A_TEST;
  14004. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14005. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14006. Result:=true;
  14007. end;
  14008. end;
  14009. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14010. var
  14011. IsTestConstX, IsValid : Boolean;
  14012. hp1,hp2 : tai;
  14013. begin
  14014. Result:=false;
  14015. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14016. if (taicpu(p).opcode = A_TEST) then
  14017. while GetNextInstruction(p, hp1) and
  14018. TrySwapMovCmp(p, hp1) do
  14019. begin
  14020. if MatchInstruction(hp1, A_MOV, []) then
  14021. begin
  14022. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14023. begin
  14024. { A little hacky, but since TEST doesn't read the flags, only
  14025. modify them, it's safe if they get scrambled by MOV -> XOR }
  14026. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14027. Result := PostPeepholeOptMov(hp1);
  14028. {$ifdef x86_64}
  14029. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14030. { Used to shrink instruction size }
  14031. PostPeepholeOptXor(hp1);
  14032. {$endif x86_64}
  14033. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14034. end
  14035. else
  14036. begin
  14037. Result := PostPeepholeOptMov(hp1);
  14038. {$ifdef x86_64}
  14039. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14040. { Used to shrink instruction size }
  14041. PostPeepholeOptXor(hp1);
  14042. {$endif x86_64}
  14043. end;
  14044. end;
  14045. { Enabling this flag is actually a null operation, but it marks
  14046. the code as 'modified' during this pass }
  14047. Include(OptsToCheck, aoc_ForceNewIteration);
  14048. end;
  14049. { If x is a power of 2 (popcnt = 1), change:
  14050. or $x, %reg/ref
  14051. To:
  14052. bts lb(x), %reg/ref
  14053. }
  14054. if (taicpu(p).opcode = A_OR) and
  14055. IsBTXAcceptable(p) and
  14056. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14057. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14058. (
  14059. { Don't optimise if a test instruction follows }
  14060. not GetNextInstruction(p, hp1) or
  14061. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14062. ) then
  14063. begin
  14064. 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);
  14065. taicpu(p).opcode := A_BTS;
  14066. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14067. Result := True;
  14068. Exit;
  14069. end;
  14070. { If x is a power of 2 (popcnt = 1), change:
  14071. test $x, %reg/ref
  14072. je / sete / cmove (or jne / setne)
  14073. To:
  14074. bt lb(x), %reg/ref
  14075. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14076. }
  14077. if (taicpu(p).opcode = A_TEST) and
  14078. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14079. (taicpu(p).oper[0]^.typ = top_const) and
  14080. (
  14081. (cs_opt_size in current_settings.optimizerswitches) or
  14082. (
  14083. (taicpu(p).oper[1]^.typ = top_reg) and
  14084. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14085. ) or
  14086. (
  14087. (taicpu(p).oper[1]^.typ <> top_reg) and
  14088. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14089. )
  14090. ) and
  14091. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14092. { For sizes less than S_L, the byte size is equal or larger with BT,
  14093. so don't bother optimising }
  14094. (taicpu(p).opsize >= S_L) then
  14095. begin
  14096. IsValid := True;
  14097. { Check the next set of instructions, watching the FLAGS register
  14098. and the conditions used }
  14099. TransferUsedRegs(TmpUsedRegs);
  14100. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14101. hp1 := p;
  14102. hp2 := nil;
  14103. while GetNextInstruction(hp1, hp1) do
  14104. begin
  14105. if not Assigned(hp2) then
  14106. { The first instruction after TEST }
  14107. hp2 := hp1;
  14108. if (hp1.typ <> ait_instruction) then
  14109. begin
  14110. { If the flags are no longer in use, everything is fine }
  14111. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14112. IsValid := False;
  14113. Break;
  14114. end;
  14115. case taicpu(hp1).condition of
  14116. C_None:
  14117. begin
  14118. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14119. { Something is not quite normal, so play safe and don't change }
  14120. IsValid := False;
  14121. Break;
  14122. end;
  14123. C_E, C_Z, C_NE, C_NZ:
  14124. { This is fine };
  14125. else
  14126. begin
  14127. { Unsupported condition }
  14128. IsValid := False;
  14129. Break;
  14130. end;
  14131. end;
  14132. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14133. end;
  14134. if IsValid then
  14135. begin
  14136. while hp2 <> hp1 do
  14137. begin
  14138. case taicpu(hp2).condition of
  14139. C_Z, C_E:
  14140. taicpu(hp2).condition := C_NC;
  14141. C_NZ, C_NE:
  14142. taicpu(hp2).condition := C_C;
  14143. else
  14144. { Should not get this by this point }
  14145. InternalError(2022110701);
  14146. end;
  14147. GetNextInstruction(hp2, hp2);
  14148. end;
  14149. 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);
  14150. taicpu(p).opcode := A_BT;
  14151. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14152. Result := True;
  14153. Exit;
  14154. end;
  14155. end;
  14156. { removes the line marked with (x) from the sequence
  14157. and/or/xor/add/sub/... $x, %y
  14158. test/or %y, %y | test $-1, %y (x)
  14159. j(n)z _Label
  14160. as the first instruction already adjusts the ZF
  14161. %y operand may also be a reference }
  14162. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14163. MatchOperand(taicpu(p).oper[0]^,-1);
  14164. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14165. GetLastInstruction(p, hp1) and
  14166. (tai(hp1).typ = ait_instruction) and
  14167. GetNextInstruction(p,hp2) and
  14168. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14169. case taicpu(hp1).opcode Of
  14170. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14171. { These two instructions set the zero flag if the result is zero }
  14172. A_POPCNT, A_LZCNT:
  14173. begin
  14174. if (
  14175. { With POPCNT, an input of zero will set the zero flag
  14176. because the population count of zero is zero }
  14177. (taicpu(hp1).opcode = A_POPCNT) and
  14178. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14179. (
  14180. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14181. { Faster than going through the second half of the 'or'
  14182. condition below }
  14183. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14184. )
  14185. ) or (
  14186. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14187. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14188. { and in case of carry for A(E)/B(E)/C/NC }
  14189. (
  14190. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14191. (
  14192. (taicpu(hp1).opcode <> A_ADD) and
  14193. (taicpu(hp1).opcode <> A_SUB) and
  14194. (taicpu(hp1).opcode <> A_LZCNT)
  14195. )
  14196. )
  14197. ) then
  14198. begin
  14199. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14200. RemoveCurrentP(p, hp2);
  14201. Result:=true;
  14202. Exit;
  14203. end;
  14204. end;
  14205. A_SHL, A_SAL, A_SHR, A_SAR:
  14206. begin
  14207. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14208. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14209. { therefore, it's only safe to do this optimization for }
  14210. { shifts by a (nonzero) constant }
  14211. (taicpu(hp1).oper[0]^.typ = top_const) and
  14212. (taicpu(hp1).oper[0]^.val <> 0) and
  14213. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14214. { and in case of carry for A(E)/B(E)/C/NC }
  14215. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14216. begin
  14217. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14218. RemoveCurrentP(p, hp2);
  14219. Result:=true;
  14220. Exit;
  14221. end;
  14222. end;
  14223. A_DEC, A_INC, A_NEG:
  14224. begin
  14225. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14226. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14227. { and in case of carry for A(E)/B(E)/C/NC }
  14228. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14229. begin
  14230. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14231. RemoveCurrentP(p, hp2);
  14232. Result:=true;
  14233. Exit;
  14234. end;
  14235. end;
  14236. A_ANDN, A_BZHI:
  14237. begin
  14238. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14239. { Only the zero and sign flags are consistent with what the result is }
  14240. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14241. begin
  14242. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14243. RemoveCurrentP(p, hp2);
  14244. Result:=true;
  14245. Exit;
  14246. end;
  14247. end;
  14248. A_BEXTR:
  14249. begin
  14250. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14251. { Only the zero flag is set }
  14252. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14253. begin
  14254. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14255. RemoveCurrentP(p, hp2);
  14256. Result:=true;
  14257. Exit;
  14258. end;
  14259. end;
  14260. else
  14261. ;
  14262. end; { case }
  14263. { change "test $-1,%reg" into "test %reg,%reg" }
  14264. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14265. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14266. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14267. if MatchInstruction(p, A_OR, []) and
  14268. { Can only match if they're both registers }
  14269. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14270. begin
  14271. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14272. taicpu(p).opcode := A_TEST;
  14273. { No need to set Result to True, as we've done all the optimisations we can }
  14274. end;
  14275. end;
  14276. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14277. var
  14278. hp1,hp3 : tai;
  14279. {$ifndef x86_64}
  14280. hp2 : taicpu;
  14281. {$endif x86_64}
  14282. begin
  14283. Result:=false;
  14284. hp3:=nil;
  14285. {$ifndef x86_64}
  14286. { don't do this on modern CPUs, this really hurts them due to
  14287. broken call/ret pairing }
  14288. if (current_settings.optimizecputype < cpu_Pentium2) and
  14289. not(cs_create_pic in current_settings.moduleswitches) and
  14290. GetNextInstruction(p, hp1) and
  14291. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14292. MatchOpType(taicpu(hp1),top_ref) and
  14293. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14294. begin
  14295. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14296. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14297. InsertLLItem(p.previous, p, hp2);
  14298. taicpu(p).opcode := A_JMP;
  14299. taicpu(p).is_jmp := true;
  14300. RemoveInstruction(hp1);
  14301. Result:=true;
  14302. end
  14303. else
  14304. {$endif x86_64}
  14305. { replace
  14306. call procname
  14307. ret
  14308. by
  14309. jmp procname
  14310. but do it only on level 4 because it destroys stack back traces
  14311. else if the subroutine is marked as no return, remove the ret
  14312. }
  14313. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14314. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14315. GetNextInstruction(p, hp1) and
  14316. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14317. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14318. SetAndTest(hp1,hp3) and
  14319. GetNextInstruction(hp1,hp1) and
  14320. MatchInstruction(hp1,A_RET,[S_NO])
  14321. )
  14322. ) and
  14323. (taicpu(hp1).ops=0) then
  14324. begin
  14325. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14326. { we might destroy stack alignment here if we do not do a call }
  14327. (target_info.stackalign<=sizeof(SizeUInt)) then
  14328. begin
  14329. taicpu(p).opcode := A_JMP;
  14330. taicpu(p).is_jmp := true;
  14331. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14332. end
  14333. else
  14334. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14335. RemoveInstruction(hp1);
  14336. if Assigned(hp3) then
  14337. begin
  14338. AsmL.Remove(hp3);
  14339. AsmL.InsertBefore(hp3,p)
  14340. end;
  14341. Result:=true;
  14342. end;
  14343. end;
  14344. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14345. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14346. begin
  14347. case OpSize of
  14348. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14349. Result := (Val <= $FF) and (Val >= -128);
  14350. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14351. Result := (Val <= $FFFF) and (Val >= -32768);
  14352. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14353. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14354. else
  14355. Result := True;
  14356. end;
  14357. end;
  14358. var
  14359. hp1, hp2 : tai;
  14360. SizeChange: Boolean;
  14361. PreMessage: string;
  14362. begin
  14363. Result := False;
  14364. if (taicpu(p).oper[0]^.typ = top_reg) and
  14365. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14366. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14367. begin
  14368. { Change (using movzbl %al,%eax as an example):
  14369. movzbl %al, %eax movzbl %al, %eax
  14370. cmpl x, %eax testl %eax,%eax
  14371. To:
  14372. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14373. movzbl %al, %eax movzbl %al, %eax
  14374. Smaller instruction and minimises pipeline stall as the CPU
  14375. doesn't have to wait for the register to get zero-extended. [Kit]
  14376. Also allow if the smaller of the two registers is being checked,
  14377. as this still removes the false dependency.
  14378. }
  14379. if
  14380. (
  14381. (
  14382. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14383. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14384. ) or (
  14385. { If MatchOperand returns True, they must both be registers }
  14386. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14387. )
  14388. ) and
  14389. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14390. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14391. begin
  14392. 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);
  14393. asml.Remove(hp1);
  14394. asml.InsertBefore(hp1, p);
  14395. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14396. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14397. begin
  14398. taicpu(hp1).opcode := A_TEST;
  14399. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14400. end;
  14401. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14402. case taicpu(p).opsize of
  14403. S_BW, S_BL:
  14404. begin
  14405. SizeChange := taicpu(hp1).opsize <> S_B;
  14406. taicpu(hp1).changeopsize(S_B);
  14407. end;
  14408. S_WL:
  14409. begin
  14410. SizeChange := taicpu(hp1).opsize <> S_W;
  14411. taicpu(hp1).changeopsize(S_W);
  14412. end
  14413. else
  14414. InternalError(2020112701);
  14415. end;
  14416. UpdateUsedRegs(tai(p.Next));
  14417. { Check if the register is used aferwards - if not, we can
  14418. remove the movzx instruction completely }
  14419. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14420. begin
  14421. { Hp1 is a better position than p for debugging purposes }
  14422. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14423. RemoveCurrentp(p, hp1);
  14424. Result := True;
  14425. end;
  14426. if SizeChange then
  14427. DebugMsg(SPeepholeOptimization + PreMessage +
  14428. 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)
  14429. else
  14430. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14431. Exit;
  14432. end;
  14433. { Change (using movzwl %ax,%eax as an example):
  14434. movzwl %ax, %eax
  14435. movb %al, (dest) (Register is smaller than read register in movz)
  14436. To:
  14437. movb %al, (dest) (Move one back to avoid a false dependency)
  14438. movzwl %ax, %eax
  14439. }
  14440. if (taicpu(hp1).opcode = A_MOV) and
  14441. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14442. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14443. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14444. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14445. begin
  14446. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14447. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14448. asml.Remove(hp1);
  14449. asml.InsertBefore(hp1, p);
  14450. if taicpu(hp1).oper[1]^.typ = top_reg then
  14451. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14452. { Check if the register is used aferwards - if not, we can
  14453. remove the movzx instruction completely }
  14454. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14455. begin
  14456. { Hp1 is a better position than p for debugging purposes }
  14457. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14458. RemoveCurrentp(p, hp1);
  14459. Result := True;
  14460. end;
  14461. Exit;
  14462. end;
  14463. end;
  14464. end;
  14465. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14466. var
  14467. hp1: tai;
  14468. {$ifdef x86_64}
  14469. PreMessage, RegName: string;
  14470. {$endif x86_64}
  14471. begin
  14472. Result := False;
  14473. { If x is a power of 2 (popcnt = 1), change:
  14474. xor $x, %reg/ref
  14475. To:
  14476. btc lb(x), %reg/ref
  14477. }
  14478. if IsBTXAcceptable(p) and
  14479. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14480. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14481. (
  14482. { Don't optimise if a test instruction follows }
  14483. not GetNextInstruction(p, hp1) or
  14484. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14485. ) then
  14486. begin
  14487. 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);
  14488. taicpu(p).opcode := A_BTC;
  14489. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14490. Result := True;
  14491. Exit;
  14492. end;
  14493. {$ifdef x86_64}
  14494. { Code size reduction by J. Gareth "Kit" Moreton }
  14495. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14496. as this removes the REX prefix }
  14497. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14498. Exit;
  14499. if taicpu(p).oper[0]^.typ <> top_reg then
  14500. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14501. InternalError(2018011500);
  14502. case taicpu(p).opsize of
  14503. S_Q:
  14504. begin
  14505. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14506. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14507. { The actual optimization }
  14508. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14509. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14510. taicpu(p).changeopsize(S_L);
  14511. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14512. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14513. end;
  14514. else
  14515. ;
  14516. end;
  14517. {$endif x86_64}
  14518. end;
  14519. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14520. var
  14521. XReg: TRegister;
  14522. begin
  14523. Result := False;
  14524. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14525. Smaller encoding and slightly faster on some platforms (also works for
  14526. ZMM-sized registers) }
  14527. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14528. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14529. begin
  14530. XReg := taicpu(p).oper[0]^.reg;
  14531. if (taicpu(p).oper[1]^.reg = XReg) then
  14532. begin
  14533. taicpu(p).changeopsize(S_XMM);
  14534. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14535. if (cs_opt_size in current_settings.optimizerswitches) then
  14536. begin
  14537. { Change input registers to %xmm0 to reduce size. Note that
  14538. there's a risk of a false dependency doing this, so only
  14539. optimise for size here }
  14540. XReg := NR_XMM0;
  14541. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14542. end
  14543. else
  14544. begin
  14545. setsubreg(XReg, R_SUBMMX);
  14546. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14547. end;
  14548. taicpu(p).oper[0]^.reg := XReg;
  14549. taicpu(p).oper[1]^.reg := XReg;
  14550. Result := True;
  14551. end;
  14552. end;
  14553. end;
  14554. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14555. var
  14556. OperIdx: Integer;
  14557. begin
  14558. for OperIdx := 0 to p.ops - 1 do
  14559. if p.oper[OperIdx]^.typ = top_ref then
  14560. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14561. end;
  14562. end.