aoptx86.pas 698 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2037. (hp1.typ = ait_instruction) and
  2038. (
  2039. { Under -O2 and below, the instructions are always adjacent }
  2040. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2041. (taicpu(hp1).ops <= 1) or
  2042. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2043. { If reg1 = reg3, reg1 must not be modified in between }
  2044. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2045. ) then
  2046. begin
  2047. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2048. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2049. begin
  2050. { vmova* reg1,reg2
  2051. ...
  2052. vmova* reg2,reg3
  2053. dealloc reg2
  2054. =>
  2055. vmova* reg1,reg3 }
  2056. TransferUsedRegs(TmpUsedRegs);
  2057. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2058. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2059. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2060. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2061. begin
  2062. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2063. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2064. TransferUsedRegs(TmpUsedRegs);
  2065. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2066. RemoveInstruction(hp1);
  2067. result:=true;
  2068. exit;
  2069. end;
  2070. { special case:
  2071. vmova* reg1,<op>
  2072. ...
  2073. vmova* <op>,reg1
  2074. =>
  2075. vmova* reg1,<op> }
  2076. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2077. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2078. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2079. ) then
  2080. begin
  2081. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2082. RemoveInstruction(hp1);
  2083. result:=true;
  2084. exit;
  2085. end
  2086. end
  2087. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2088. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2089. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2090. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2091. ) and
  2092. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2093. begin
  2094. { vmova* reg1,reg2
  2095. ...
  2096. vmovs* reg2,<op>
  2097. dealloc reg2
  2098. =>
  2099. vmovs* reg1,<op> }
  2100. TransferUsedRegs(TmpUsedRegs);
  2101. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2102. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2105. taicpu(p).opcode:=taicpu(hp1).opcode;
  2106. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2107. TransferUsedRegs(TmpUsedRegs);
  2108. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2109. RemoveInstruction(hp1);
  2110. result:=true;
  2111. exit;
  2112. end
  2113. end;
  2114. if MatchInstruction(hp1,[A_VFMADDPD,
  2115. A_VFMADD132PD,
  2116. A_VFMADD132PS,
  2117. A_VFMADD132SD,
  2118. A_VFMADD132SS,
  2119. A_VFMADD213PD,
  2120. A_VFMADD213PS,
  2121. A_VFMADD213SD,
  2122. A_VFMADD213SS,
  2123. A_VFMADD231PD,
  2124. A_VFMADD231PS,
  2125. A_VFMADD231SD,
  2126. A_VFMADD231SS,
  2127. A_VFMADDSUB132PD,
  2128. A_VFMADDSUB132PS,
  2129. A_VFMADDSUB213PD,
  2130. A_VFMADDSUB213PS,
  2131. A_VFMADDSUB231PD,
  2132. A_VFMADDSUB231PS,
  2133. A_VFMSUB132PD,
  2134. A_VFMSUB132PS,
  2135. A_VFMSUB132SD,
  2136. A_VFMSUB132SS,
  2137. A_VFMSUB213PD,
  2138. A_VFMSUB213PS,
  2139. A_VFMSUB213SD,
  2140. A_VFMSUB213SS,
  2141. A_VFMSUB231PD,
  2142. A_VFMSUB231PS,
  2143. A_VFMSUB231SD,
  2144. A_VFMSUB231SS,
  2145. A_VFMSUBADD132PD,
  2146. A_VFMSUBADD132PS,
  2147. A_VFMSUBADD213PD,
  2148. A_VFMSUBADD213PS,
  2149. A_VFMSUBADD231PD,
  2150. A_VFMSUBADD231PS,
  2151. A_VFNMADD132PD,
  2152. A_VFNMADD132PS,
  2153. A_VFNMADD132SD,
  2154. A_VFNMADD132SS,
  2155. A_VFNMADD213PD,
  2156. A_VFNMADD213PS,
  2157. A_VFNMADD213SD,
  2158. A_VFNMADD213SS,
  2159. A_VFNMADD231PD,
  2160. A_VFNMADD231PS,
  2161. A_VFNMADD231SD,
  2162. A_VFNMADD231SS,
  2163. A_VFNMSUB132PD,
  2164. A_VFNMSUB132PS,
  2165. A_VFNMSUB132SD,
  2166. A_VFNMSUB132SS,
  2167. A_VFNMSUB213PD,
  2168. A_VFNMSUB213PS,
  2169. A_VFNMSUB213SD,
  2170. A_VFNMSUB213SS,
  2171. A_VFNMSUB231PD,
  2172. A_VFNMSUB231PS,
  2173. A_VFNMSUB231SD,
  2174. A_VFNMSUB231SS],[S_NO]) and
  2175. { we mix single and double opperations here because we assume that the compiler
  2176. generates vmovapd only after double operations and vmovaps only after single operations }
  2177. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2178. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2179. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2180. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2181. begin
  2182. TransferUsedRegs(TmpUsedRegs);
  2183. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2184. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2185. begin
  2186. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2187. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2188. RemoveCurrentP(p)
  2189. else
  2190. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2191. RemoveInstruction(hp2);
  2192. end;
  2193. end
  2194. else if (hp1.typ = ait_instruction) and
  2195. (((taicpu(p).opcode=A_MOVAPS) and
  2196. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2197. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2198. ((taicpu(p).opcode=A_MOVAPD) and
  2199. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2200. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2201. ) and
  2202. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2203. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2204. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2205. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2206. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2207. { change
  2208. movapX reg,reg2
  2209. addsX/subsX/... reg3, reg2
  2210. movapX reg2,reg
  2211. to
  2212. addsX/subsX/... reg3,reg
  2213. }
  2214. begin
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2217. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2218. begin
  2219. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2220. debug_op2str(taicpu(p).opcode)+' '+
  2221. debug_op2str(taicpu(hp1).opcode)+' '+
  2222. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2223. { we cannot eliminate the first move if
  2224. the operations uses the same register for source and dest }
  2225. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2226. { Remember that hp1 is not necessarily the immediate
  2227. next instruction }
  2228. RemoveCurrentP(p);
  2229. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2230. RemoveInstruction(hp2);
  2231. result:=true;
  2232. end;
  2233. end
  2234. else if (hp1.typ = ait_instruction) and
  2235. (((taicpu(p).opcode=A_VMOVAPD) and
  2236. (taicpu(hp1).opcode=A_VCOMISD)) or
  2237. ((taicpu(p).opcode=A_VMOVAPS) and
  2238. ((taicpu(hp1).opcode=A_VCOMISS))
  2239. )
  2240. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2241. { change
  2242. movapX reg,reg1
  2243. vcomisX reg1,reg1
  2244. to
  2245. vcomisX reg,reg
  2246. }
  2247. begin
  2248. TransferUsedRegs(TmpUsedRegs);
  2249. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2250. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2251. begin
  2252. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2253. debug_op2str(taicpu(p).opcode)+' '+
  2254. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2255. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2256. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2257. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2258. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2259. RemoveCurrentP(p);
  2260. result:=true;
  2261. exit;
  2262. end;
  2263. end
  2264. end;
  2265. end;
  2266. end;
  2267. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2268. var
  2269. hp1 : tai;
  2270. begin
  2271. result:=false;
  2272. { replace
  2273. V<Op>X %mreg1,%mreg2,%mreg3
  2274. VMovX %mreg3,%mreg4
  2275. dealloc %mreg3
  2276. by
  2277. V<Op>X %mreg1,%mreg2,%mreg4
  2278. ?
  2279. }
  2280. if GetNextInstruction(p,hp1) and
  2281. { we mix single and double operations here because we assume that the compiler
  2282. generates vmovapd only after double operations and vmovaps only after single operations }
  2283. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2284. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2285. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2286. begin
  2287. TransferUsedRegs(TmpUsedRegs);
  2288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2289. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2290. begin
  2291. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2292. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2293. RemoveInstruction(hp1);
  2294. result:=true;
  2295. end;
  2296. end;
  2297. end;
  2298. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2299. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2300. begin
  2301. Result := False;
  2302. { For safety reasons, only check for exact register matches }
  2303. { Check base register }
  2304. if (ref.base = AOldReg) then
  2305. begin
  2306. ref.base := ANewReg;
  2307. Result := True;
  2308. end;
  2309. { Check index register }
  2310. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2311. begin
  2312. ref.index := ANewReg;
  2313. Result := True;
  2314. end;
  2315. end;
  2316. { Replaces all references to AOldReg in an operand to ANewReg }
  2317. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2318. var
  2319. OldSupReg, NewSupReg: TSuperRegister;
  2320. OldSubReg, NewSubReg: TSubRegister;
  2321. OldRegType: TRegisterType;
  2322. ThisOper: POper;
  2323. begin
  2324. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2325. Result := False;
  2326. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2327. InternalError(2020011801);
  2328. OldSupReg := getsupreg(AOldReg);
  2329. OldSubReg := getsubreg(AOldReg);
  2330. OldRegType := getregtype(AOldReg);
  2331. NewSupReg := getsupreg(ANewReg);
  2332. NewSubReg := getsubreg(ANewReg);
  2333. if OldRegType <> getregtype(ANewReg) then
  2334. InternalError(2020011802);
  2335. if OldSubReg <> NewSubReg then
  2336. InternalError(2020011803);
  2337. case ThisOper^.typ of
  2338. top_reg:
  2339. if (
  2340. (ThisOper^.reg = AOldReg) or
  2341. (
  2342. (OldRegType = R_INTREGISTER) and
  2343. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2344. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2345. (
  2346. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2347. {$ifndef x86_64}
  2348. and (
  2349. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2350. don't have an 8-bit representation }
  2351. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2352. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2353. )
  2354. {$endif x86_64}
  2355. )
  2356. )
  2357. ) then
  2358. begin
  2359. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2360. Result := True;
  2361. end;
  2362. top_ref:
  2363. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2364. Result := True;
  2365. else
  2366. ;
  2367. end;
  2368. end;
  2369. { Replaces all references to AOldReg in an instruction to ANewReg }
  2370. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2371. const
  2372. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2373. var
  2374. OperIdx: Integer;
  2375. begin
  2376. Result := False;
  2377. for OperIdx := 0 to p.ops - 1 do
  2378. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2379. begin
  2380. { The shift and rotate instructions can only use CL }
  2381. if not (
  2382. (OperIdx = 0) and
  2383. { This second condition just helps to avoid unnecessarily
  2384. calling MatchInstruction for 10 different opcodes }
  2385. (p.oper[0]^.reg = NR_CL) and
  2386. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2387. ) then
  2388. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2389. end
  2390. else if p.oper[OperIdx]^.typ = top_ref then
  2391. { It's okay to replace registers in references that get written to }
  2392. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2393. end;
  2394. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2395. begin
  2396. Result :=
  2397. (ref^.index = NR_NO) and
  2398. (
  2399. {$ifdef x86_64}
  2400. (
  2401. (ref^.base = NR_RIP) and
  2402. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2403. ) or
  2404. {$endif x86_64}
  2405. (ref^.refaddr = addr_full) or
  2406. (ref^.base = NR_STACK_POINTER_REG) or
  2407. (ref^.base = current_procinfo.framepointer)
  2408. );
  2409. end;
  2410. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2411. var
  2412. l: asizeint;
  2413. begin
  2414. Result := False;
  2415. { Should have been checked previously }
  2416. if p.opcode <> A_LEA then
  2417. InternalError(2020072501);
  2418. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2419. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2420. not(cs_opt_size in current_settings.optimizerswitches) then
  2421. exit;
  2422. with p.oper[0]^.ref^ do
  2423. begin
  2424. if (base <> p.oper[1]^.reg) or
  2425. (index <> NR_NO) or
  2426. assigned(symbol) then
  2427. exit;
  2428. l:=offset;
  2429. if (l=1) and UseIncDec then
  2430. begin
  2431. p.opcode:=A_INC;
  2432. p.loadreg(0,p.oper[1]^.reg);
  2433. p.ops:=1;
  2434. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2435. end
  2436. else if (l=-1) and UseIncDec then
  2437. begin
  2438. p.opcode:=A_DEC;
  2439. p.loadreg(0,p.oper[1]^.reg);
  2440. p.ops:=1;
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2442. end
  2443. else
  2444. begin
  2445. if (l<0) and (l<>-2147483648) then
  2446. begin
  2447. p.opcode:=A_SUB;
  2448. p.loadConst(0,-l);
  2449. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2450. end
  2451. else
  2452. begin
  2453. p.opcode:=A_ADD;
  2454. p.loadConst(0,l);
  2455. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2456. end;
  2457. end;
  2458. end;
  2459. Result := True;
  2460. end;
  2461. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2462. var
  2463. CurrentReg, ReplaceReg: TRegister;
  2464. begin
  2465. Result := False;
  2466. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2467. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2468. case hp.opcode of
  2469. A_FSTSW, A_FNSTSW,
  2470. A_IN, A_INS, A_OUT, A_OUTS,
  2471. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2472. { These routines have explicit operands, but they are restricted in
  2473. what they can be (e.g. IN and OUT can only read from AL, AX or
  2474. EAX. }
  2475. Exit;
  2476. A_IMUL:
  2477. begin
  2478. { The 1-operand version writes to implicit registers
  2479. The 2-operand version reads from the first operator, and reads
  2480. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2481. the 3-operand version reads from a register that it doesn't write to
  2482. }
  2483. case hp.ops of
  2484. 1:
  2485. if (
  2486. (
  2487. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2488. ) or
  2489. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2490. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2491. begin
  2492. Result := True;
  2493. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2494. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2495. end;
  2496. 2:
  2497. { Only modify the first parameter }
  2498. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2499. begin
  2500. Result := True;
  2501. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2502. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2503. end;
  2504. 3:
  2505. { Only modify the second parameter }
  2506. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2507. begin
  2508. Result := True;
  2509. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2510. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2511. end;
  2512. else
  2513. InternalError(2020012901);
  2514. end;
  2515. end;
  2516. else
  2517. if (hp.ops > 0) and
  2518. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2519. begin
  2520. Result := True;
  2521. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2522. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2523. end;
  2524. end;
  2525. end;
  2526. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2527. var
  2528. hp2: tai;
  2529. p_SourceReg, p_TargetReg: TRegister;
  2530. begin
  2531. Result := False;
  2532. { Backward optimisation. If we have:
  2533. func. %reg1,%reg2
  2534. mov %reg2,%reg3
  2535. (dealloc %reg2)
  2536. Change to:
  2537. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2538. Perform similar optimisations with 1, 3 and 4-operand instructions
  2539. that only have one output.
  2540. }
  2541. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2542. begin
  2543. p_SourceReg := taicpu(p).oper[0]^.reg;
  2544. p_TargetReg := taicpu(p).oper[1]^.reg;
  2545. TransferUsedRegs(TmpUsedRegs);
  2546. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2547. GetLastInstruction(p, hp2) and
  2548. (hp2.typ = ait_instruction) and
  2549. { Have to make sure it's an instruction that only reads from
  2550. the first operands and only writes (not reads or modifies) to
  2551. the last one; in essence, a pure function such as BSR, POPCNT
  2552. or ANDN }
  2553. (
  2554. (
  2555. (taicpu(hp2).ops = 1) and
  2556. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2557. ) or
  2558. (
  2559. (taicpu(hp2).ops = 2) and
  2560. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2561. ) or
  2562. (
  2563. (taicpu(hp2).ops = 3) and
  2564. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2565. ) or
  2566. (
  2567. (taicpu(hp2).ops = 4) and
  2568. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2569. )
  2570. ) and
  2571. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2572. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2573. begin
  2574. case taicpu(hp2).opcode of
  2575. A_FSTSW, A_FNSTSW,
  2576. A_IN, A_INS, A_OUT, A_OUTS,
  2577. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2578. { These routines have explicit operands, but they are restricted in
  2579. what they can be (e.g. IN and OUT can only read from AL, AX or
  2580. EAX. }
  2581. ;
  2582. else
  2583. begin
  2584. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2585. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2586. if not RegInInstruction(p_TargetReg, hp2) then
  2587. begin
  2588. { Since we're allocating from an earlier point, we
  2589. need to remove the register from the tracking }
  2590. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2591. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2592. end;
  2593. RemoveCurrentp(p, hp1);
  2594. { If the Func was another MOV instruction, we might get
  2595. "mov %reg,%reg" that doesn't get removed in Pass 2
  2596. otherwise, so deal with it here (also do something
  2597. similar with lea (%reg),%reg}
  2598. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2599. begin
  2600. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2601. if p = hp2 then
  2602. RemoveCurrentp(p)
  2603. else
  2604. RemoveInstruction(hp2);
  2605. end;
  2606. Result := True;
  2607. Exit;
  2608. end;
  2609. end;
  2610. end;
  2611. end;
  2612. end;
  2613. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2614. var
  2615. hp1, hp2, hp3: tai;
  2616. DoOptimisation, TempBool: Boolean;
  2617. {$ifdef x86_64}
  2618. NewConst: TCGInt;
  2619. {$endif x86_64}
  2620. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2621. begin
  2622. if taicpu(hp1).opcode = signed_movop then
  2623. begin
  2624. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2625. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2626. end
  2627. else
  2628. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2629. end;
  2630. function TryConstMerge(var p1, p2: tai): Boolean;
  2631. var
  2632. ThisRef: TReference;
  2633. begin
  2634. Result := False;
  2635. ThisRef := taicpu(p2).oper[1]^.ref^;
  2636. { Only permit writes to the stack, since we can guarantee alignment with that }
  2637. if (ThisRef.index = NR_NO) and
  2638. (
  2639. (ThisRef.base = NR_STACK_POINTER_REG) or
  2640. (ThisRef.base = current_procinfo.framepointer)
  2641. ) then
  2642. begin
  2643. case taicpu(p).opsize of
  2644. S_B:
  2645. begin
  2646. { Word writes must be on a 2-byte boundary }
  2647. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2648. begin
  2649. { Reduce offset of second reference to see if it is sequential with the first }
  2650. Dec(ThisRef.offset, 1);
  2651. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2652. begin
  2653. { Make sure the constants aren't represented as a
  2654. negative number, as these won't merge properly }
  2655. taicpu(p1).opsize := S_W;
  2656. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2657. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2658. RemoveInstruction(p2);
  2659. Result := True;
  2660. end;
  2661. end;
  2662. end;
  2663. S_W:
  2664. begin
  2665. { Longword writes must be on a 4-byte boundary }
  2666. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2667. begin
  2668. { Reduce offset of second reference to see if it is sequential with the first }
  2669. Dec(ThisRef.offset, 2);
  2670. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2671. begin
  2672. { Make sure the constants aren't represented as a
  2673. negative number, as these won't merge properly }
  2674. taicpu(p1).opsize := S_L;
  2675. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2676. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2677. RemoveInstruction(p2);
  2678. Result := True;
  2679. end;
  2680. end;
  2681. end;
  2682. {$ifdef x86_64}
  2683. S_L:
  2684. begin
  2685. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2686. see if the constants can be encoded this way. }
  2687. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2688. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2689. { Quadword writes must be on an 8-byte boundary }
  2690. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2691. begin
  2692. { Reduce offset of second reference to see if it is sequential with the first }
  2693. Dec(ThisRef.offset, 4);
  2694. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2695. begin
  2696. { Make sure the constants aren't represented as a
  2697. negative number, as these won't merge properly }
  2698. taicpu(p1).opsize := S_Q;
  2699. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2700. taicpu(p1).oper[0]^.val := NewConst;
  2701. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2702. RemoveInstruction(p2);
  2703. Result := True;
  2704. end;
  2705. end;
  2706. end;
  2707. {$endif x86_64}
  2708. else
  2709. ;
  2710. end;
  2711. end;
  2712. end;
  2713. var
  2714. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2715. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2716. NewSize: topsize; NewOffset: asizeint;
  2717. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2718. SourceRef, TargetRef: TReference;
  2719. MovAligned, MovUnaligned: TAsmOp;
  2720. ThisRef: TReference;
  2721. JumpTracking: TLinkedList;
  2722. begin
  2723. Result:=false;
  2724. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2725. { remove mov reg1,reg1? }
  2726. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2727. then
  2728. begin
  2729. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2730. { take care of the register (de)allocs following p }
  2731. RemoveCurrentP(p, hp1);
  2732. Result:=true;
  2733. exit;
  2734. end;
  2735. { All the next optimisations require a next instruction }
  2736. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2737. Exit;
  2738. { Prevent compiler warnings }
  2739. p_TargetReg := NR_NO;
  2740. if taicpu(p).oper[1]^.typ = top_reg then
  2741. begin
  2742. { Saves on a large number of dereferences }
  2743. p_TargetReg := taicpu(p).oper[1]^.reg;
  2744. { Look for:
  2745. mov %reg1,%reg2
  2746. ??? %reg2,r/m
  2747. Change to:
  2748. mov %reg1,%reg2
  2749. ??? %reg1,r/m
  2750. }
  2751. if taicpu(p).oper[0]^.typ = top_reg then
  2752. begin
  2753. if RegReadByInstruction(p_TargetReg, hp1) and
  2754. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2755. begin
  2756. { A change has occurred, just not in p }
  2757. Result := True;
  2758. TransferUsedRegs(TmpUsedRegs);
  2759. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2760. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2761. { Just in case something didn't get modified (e.g. an
  2762. implicit register) }
  2763. not RegReadByInstruction(p_TargetReg, hp1) then
  2764. begin
  2765. { We can remove the original MOV }
  2766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2767. RemoveCurrentp(p, hp1);
  2768. { UsedRegs got updated by RemoveCurrentp }
  2769. Result := True;
  2770. Exit;
  2771. end;
  2772. { If we know a MOV instruction has become a null operation, we might as well
  2773. get rid of it now to save time. }
  2774. if (taicpu(hp1).opcode = A_MOV) and
  2775. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2776. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2777. { Just being a register is enough to confirm it's a null operation }
  2778. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2779. begin
  2780. Result := True;
  2781. { Speed-up to reduce a pipeline stall... if we had something like...
  2782. movl %eax,%edx
  2783. movw %dx,%ax
  2784. ... the second instruction would change to movw %ax,%ax, but
  2785. given that it is now %ax that's active rather than %eax,
  2786. penalties might occur due to a partial register write, so instead,
  2787. change it to a MOVZX instruction when optimising for speed.
  2788. }
  2789. if not (cs_opt_size in current_settings.optimizerswitches) and
  2790. IsMOVZXAcceptable and
  2791. (taicpu(hp1).opsize < taicpu(p).opsize)
  2792. {$ifdef x86_64}
  2793. { operations already implicitly set the upper 64 bits to zero }
  2794. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2795. {$endif x86_64}
  2796. then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2799. case taicpu(p).opsize of
  2800. S_W:
  2801. if taicpu(hp1).opsize = S_B then
  2802. taicpu(hp1).opsize := S_BL
  2803. else
  2804. InternalError(2020012911);
  2805. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2806. case taicpu(hp1).opsize of
  2807. S_B:
  2808. taicpu(hp1).opsize := S_BL;
  2809. S_W:
  2810. taicpu(hp1).opsize := S_WL;
  2811. else
  2812. InternalError(2020012912);
  2813. end;
  2814. else
  2815. InternalError(2020012910);
  2816. end;
  2817. taicpu(hp1).opcode := A_MOVZX;
  2818. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2819. end
  2820. else
  2821. begin
  2822. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2823. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2824. RemoveInstruction(hp1);
  2825. { The instruction after what was hp1 is now the immediate next instruction,
  2826. so we can continue to make optimisations if it's present }
  2827. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2828. Exit;
  2829. hp1 := hp2;
  2830. end;
  2831. end;
  2832. end;
  2833. end;
  2834. end;
  2835. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2836. overwrites the original destination register. e.g.
  2837. movl ###,%reg2d
  2838. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2839. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2840. }
  2841. if (taicpu(p).oper[1]^.typ = top_reg) and
  2842. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2843. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2844. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2845. begin
  2846. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2847. begin
  2848. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2849. case taicpu(p).oper[0]^.typ of
  2850. top_const:
  2851. { We have something like:
  2852. movb $x, %regb
  2853. movzbl %regb,%regd
  2854. Change to:
  2855. movl $x, %regd
  2856. }
  2857. begin
  2858. case taicpu(hp1).opsize of
  2859. S_BW:
  2860. begin
  2861. convert_mov_value(A_MOVSX, $FF);
  2862. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2863. taicpu(p).opsize := S_W;
  2864. end;
  2865. S_BL:
  2866. begin
  2867. convert_mov_value(A_MOVSX, $FF);
  2868. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2869. taicpu(p).opsize := S_L;
  2870. end;
  2871. S_WL:
  2872. begin
  2873. convert_mov_value(A_MOVSX, $FFFF);
  2874. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2875. taicpu(p).opsize := S_L;
  2876. end;
  2877. {$ifdef x86_64}
  2878. S_BQ:
  2879. begin
  2880. convert_mov_value(A_MOVSX, $FF);
  2881. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2882. taicpu(p).opsize := S_Q;
  2883. end;
  2884. S_WQ:
  2885. begin
  2886. convert_mov_value(A_MOVSX, $FFFF);
  2887. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2888. taicpu(p).opsize := S_Q;
  2889. end;
  2890. S_LQ:
  2891. begin
  2892. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2893. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2894. taicpu(p).opsize := S_Q;
  2895. end;
  2896. {$endif x86_64}
  2897. else
  2898. { If hp1 was a MOV instruction, it should have been
  2899. optimised already }
  2900. InternalError(2020021001);
  2901. end;
  2902. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2903. RemoveInstruction(hp1);
  2904. Result := True;
  2905. Exit;
  2906. end;
  2907. top_ref:
  2908. begin
  2909. { We have something like:
  2910. movb mem, %regb
  2911. movzbl %regb,%regd
  2912. Change to:
  2913. movzbl mem, %regd
  2914. }
  2915. ThisRef := taicpu(p).oper[0]^.ref^;
  2916. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2917. begin
  2918. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2919. taicpu(hp1).loadref(0, ThisRef);
  2920. { Make sure any registers in the references are properly tracked }
  2921. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2922. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2923. if (ThisRef.index <> NR_NO) then
  2924. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2925. RemoveCurrentP(p, hp1);
  2926. Result := True;
  2927. Exit;
  2928. end;
  2929. end;
  2930. else
  2931. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2932. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2933. Exit;
  2934. end;
  2935. end
  2936. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2937. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2938. optimised }
  2939. else
  2940. begin
  2941. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2942. RemoveCurrentP(p, hp1);
  2943. Result := True;
  2944. Exit;
  2945. end;
  2946. end;
  2947. if (taicpu(hp1).opcode = A_AND) and
  2948. (taicpu(p).oper[1]^.typ = top_reg) and
  2949. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2950. begin
  2951. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2952. begin
  2953. case taicpu(p).opsize of
  2954. S_L:
  2955. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2956. begin
  2957. { Optimize out:
  2958. mov x, %reg
  2959. and ffffffffh, %reg
  2960. }
  2961. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2962. RemoveInstruction(hp1);
  2963. Result:=true;
  2964. exit;
  2965. end;
  2966. S_Q: { TODO: Confirm if this is even possible }
  2967. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2968. begin
  2969. { Optimize out:
  2970. mov x, %reg
  2971. and ffffffffffffffffh, %reg
  2972. }
  2973. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2974. RemoveInstruction(hp1);
  2975. Result:=true;
  2976. exit;
  2977. end;
  2978. else
  2979. ;
  2980. end;
  2981. if (
  2982. (taicpu(p).oper[0]^.typ=top_reg) or
  2983. (
  2984. (taicpu(p).oper[0]^.typ=top_ref) and
  2985. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2986. )
  2987. ) and
  2988. GetNextInstruction(hp1,hp2) and
  2989. MatchInstruction(hp2,A_TEST,[]) and
  2990. (
  2991. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2992. (
  2993. { If the register being tested is smaller than the one
  2994. that received a bitwise AND, permit it if the constant
  2995. fits into the smaller size }
  2996. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2997. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2998. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2999. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3000. (
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3003. (taicpu(hp1).oper[0]^.val <= $FF)
  3004. ) or
  3005. (
  3006. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3007. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3008. {$ifdef x86_64}
  3009. ) or
  3010. (
  3011. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3012. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3013. {$endif x86_64}
  3014. )
  3015. )
  3016. )
  3017. ) and
  3018. (
  3019. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3020. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3021. ) and
  3022. GetNextInstruction(hp2,hp3) and
  3023. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3024. (taicpu(hp3).condition in [C_E,C_NE]) then
  3025. begin
  3026. TransferUsedRegs(TmpUsedRegs);
  3027. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3028. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3029. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3030. begin
  3031. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3032. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3033. taicpu(hp1).opcode:=A_TEST;
  3034. { Shrink the TEST instruction down to the smallest possible size }
  3035. case taicpu(hp1).oper[0]^.val of
  3036. 0..255:
  3037. if (taicpu(hp1).opsize <> S_B)
  3038. {$ifndef x86_64}
  3039. and (
  3040. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3041. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3042. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3043. )
  3044. {$endif x86_64}
  3045. then
  3046. begin
  3047. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3048. { Only print debug message if the TEST instruction
  3049. is a different size before and after }
  3050. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3051. taicpu(hp1).opsize := S_B;
  3052. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3053. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3054. end;
  3055. 256..65535:
  3056. if (taicpu(hp1).opsize <> S_W) then
  3057. begin
  3058. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3059. { Only print debug message if the TEST instruction
  3060. is a different size before and after }
  3061. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3062. taicpu(hp1).opsize := S_W;
  3063. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3064. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3065. end;
  3066. {$ifdef x86_64}
  3067. 65536..$7FFFFFFF:
  3068. if (taicpu(hp1).opsize <> S_L) then
  3069. begin
  3070. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3071. { Only print debug message if the TEST instruction
  3072. is a different size before and after }
  3073. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3074. taicpu(hp1).opsize := S_L;
  3075. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3076. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3077. end;
  3078. {$endif x86_64}
  3079. else
  3080. ;
  3081. end;
  3082. RemoveInstruction(hp2);
  3083. RemoveCurrentP(p, hp1);
  3084. Result:=true;
  3085. exit;
  3086. end;
  3087. end;
  3088. end
  3089. else if IsMOVZXAcceptable and
  3090. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3091. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3092. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3093. then
  3094. begin
  3095. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3096. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3097. case taicpu(p).opsize of
  3098. S_B:
  3099. if (taicpu(hp1).oper[0]^.val = $ff) then
  3100. begin
  3101. { Convert:
  3102. movb x, %regl movb x, %regl
  3103. andw ffh, %regw andl ffh, %regd
  3104. To:
  3105. movzbw x, %regd movzbl x, %regd
  3106. (Identical registers, just different sizes)
  3107. }
  3108. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3109. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3110. case taicpu(hp1).opsize of
  3111. S_W: NewSize := S_BW;
  3112. S_L: NewSize := S_BL;
  3113. {$ifdef x86_64}
  3114. S_Q: NewSize := S_BQ;
  3115. {$endif x86_64}
  3116. else
  3117. InternalError(2018011510);
  3118. end;
  3119. end
  3120. else
  3121. NewSize := S_NO;
  3122. S_W:
  3123. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3124. begin
  3125. { Convert:
  3126. movw x, %regw
  3127. andl ffffh, %regd
  3128. To:
  3129. movzwl x, %regd
  3130. (Identical registers, just different sizes)
  3131. }
  3132. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3133. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3134. case taicpu(hp1).opsize of
  3135. S_L: NewSize := S_WL;
  3136. {$ifdef x86_64}
  3137. S_Q: NewSize := S_WQ;
  3138. {$endif x86_64}
  3139. else
  3140. InternalError(2018011511);
  3141. end;
  3142. end
  3143. else
  3144. NewSize := S_NO;
  3145. else
  3146. NewSize := S_NO;
  3147. end;
  3148. if NewSize <> S_NO then
  3149. begin
  3150. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3151. { The actual optimization }
  3152. taicpu(p).opcode := A_MOVZX;
  3153. taicpu(p).changeopsize(NewSize);
  3154. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3155. { Safeguard if "and" is followed by a conditional command }
  3156. TransferUsedRegs(TmpUsedRegs);
  3157. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3158. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3159. begin
  3160. { At this point, the "and" command is effectively equivalent to
  3161. "test %reg,%reg". This will be handled separately by the
  3162. Peephole Optimizer. [Kit] }
  3163. DebugMsg(SPeepholeOptimization + PreMessage +
  3164. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3165. end
  3166. else
  3167. begin
  3168. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3169. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3170. RemoveInstruction(hp1);
  3171. end;
  3172. Result := True;
  3173. Exit;
  3174. end;
  3175. end;
  3176. end;
  3177. if (taicpu(hp1).opcode = A_OR) and
  3178. (taicpu(p).oper[1]^.typ = top_reg) and
  3179. MatchOperand(taicpu(p).oper[0]^, 0) and
  3180. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3181. begin
  3182. { mov 0, %reg
  3183. or ###,%reg
  3184. Change to (only if the flags are not used):
  3185. mov ###,%reg
  3186. }
  3187. TransferUsedRegs(TmpUsedRegs);
  3188. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3189. DoOptimisation := True;
  3190. { Even if the flags are used, we might be able to do the optimisation
  3191. if the conditions are predictable }
  3192. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3193. begin
  3194. { Only perform if ### = %reg (the same register) or equal to 0,
  3195. so %reg is guaranteed to still have a value of zero }
  3196. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3197. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3198. begin
  3199. hp2 := hp1;
  3200. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3201. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3202. GetNextInstruction(hp2, hp3) do
  3203. begin
  3204. { Don't continue modifying if the flags state is getting changed }
  3205. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3206. Break;
  3207. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3208. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3209. begin
  3210. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3211. begin
  3212. { Condition is always true }
  3213. case taicpu(hp3).opcode of
  3214. A_Jcc:
  3215. begin
  3216. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3217. { Check for jump shortcuts before we destroy the condition }
  3218. DoJumpOptimizations(hp3, TempBool);
  3219. MakeUnconditional(taicpu(hp3));
  3220. Result := True;
  3221. end;
  3222. A_CMOVcc:
  3223. begin
  3224. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3225. taicpu(hp3).opcode := A_MOV;
  3226. taicpu(hp3).condition := C_None;
  3227. Result := True;
  3228. end;
  3229. A_SETcc:
  3230. begin
  3231. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3232. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3233. taicpu(hp3).opcode := A_MOV;
  3234. taicpu(hp3).ops := 2;
  3235. taicpu(hp3).condition := C_None;
  3236. taicpu(hp3).opsize := S_B;
  3237. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3238. taicpu(hp3).loadconst(0, 1);
  3239. Result := True;
  3240. end;
  3241. else
  3242. InternalError(2021090701);
  3243. end;
  3244. end
  3245. 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
  3246. begin
  3247. { Condition is always false }
  3248. case taicpu(hp3).opcode of
  3249. A_Jcc:
  3250. begin
  3251. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3252. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3253. RemoveInstruction(hp3);
  3254. Result := True;
  3255. { Since hp3 was deleted, hp2 must not be updated }
  3256. Continue;
  3257. end;
  3258. A_CMOVcc:
  3259. begin
  3260. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3261. RemoveInstruction(hp3);
  3262. Result := True;
  3263. { Since hp3 was deleted, hp2 must not be updated }
  3264. Continue;
  3265. end;
  3266. A_SETcc:
  3267. begin
  3268. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3269. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3270. taicpu(hp3).opcode := A_MOV;
  3271. taicpu(hp3).ops := 2;
  3272. taicpu(hp3).condition := C_None;
  3273. taicpu(hp3).opsize := S_B;
  3274. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3275. taicpu(hp3).loadconst(0, 0);
  3276. Result := True;
  3277. end;
  3278. else
  3279. InternalError(2021090702);
  3280. end;
  3281. end
  3282. else
  3283. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3284. DoOptimisation := False;
  3285. end;
  3286. hp2 := hp3;
  3287. end;
  3288. { Flags are still in use - don't optimise }
  3289. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3290. DoOptimisation := False;
  3291. end
  3292. else
  3293. DoOptimisation := False;
  3294. end;
  3295. if DoOptimisation then
  3296. begin
  3297. {$ifdef x86_64}
  3298. { OR only supports 32-bit sign-extended constants for 64-bit
  3299. instructions, so compensate for this if the constant is
  3300. encoded as a value greater than or equal to 2^31 }
  3301. if (taicpu(hp1).opsize = S_Q) and
  3302. (taicpu(hp1).oper[0]^.typ = top_const) and
  3303. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3304. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3305. {$endif x86_64}
  3306. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3307. taicpu(hp1).opcode := A_MOV;
  3308. RemoveCurrentP(p, hp1);
  3309. Result := True;
  3310. Exit;
  3311. end;
  3312. end;
  3313. { Next instruction is also a MOV ? }
  3314. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3315. begin
  3316. if MatchOpType(taicpu(p), top_const, top_ref) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. TryConstMerge(p, hp1) then
  3319. begin
  3320. Result := True;
  3321. { In case we have four byte writes in a row, check for 2 more
  3322. right now so we don't have to wait for another iteration of
  3323. pass 1
  3324. }
  3325. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3326. case taicpu(p).opsize of
  3327. S_W:
  3328. begin
  3329. if GetNextInstruction(p, hp1) and
  3330. MatchInstruction(hp1, A_MOV, [S_B]) and
  3331. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3332. GetNextInstruction(hp1, hp2) and
  3333. MatchInstruction(hp2, A_MOV, [S_B]) and
  3334. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3335. { Try to merge the two bytes }
  3336. TryConstMerge(hp1, hp2) then
  3337. { Now try to merge the two words (hp2 will get deleted) }
  3338. TryConstMerge(p, hp1);
  3339. end;
  3340. S_L:
  3341. begin
  3342. { Though this only really benefits x86_64 and not i386, it
  3343. gets a potential optimisation done faster and hence
  3344. reduces the number of times OptPass1MOV is entered }
  3345. if GetNextInstruction(p, hp1) and
  3346. MatchInstruction(hp1, A_MOV, [S_W]) and
  3347. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3348. GetNextInstruction(hp1, hp2) and
  3349. MatchInstruction(hp2, A_MOV, [S_W]) and
  3350. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3351. { Try to merge the two words }
  3352. TryConstMerge(hp1, hp2) then
  3353. { This will always fail on i386, so don't bother
  3354. calling it unless we're doing x86_64 }
  3355. {$ifdef x86_64}
  3356. { Now try to merge the two longwords (hp2 will get deleted) }
  3357. TryConstMerge(p, hp1)
  3358. {$endif x86_64}
  3359. ;
  3360. end;
  3361. else
  3362. ;
  3363. end;
  3364. Exit;
  3365. end;
  3366. if (taicpu(p).oper[1]^.typ = top_reg) and
  3367. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3368. begin
  3369. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3370. TransferUsedRegs(TmpUsedRegs);
  3371. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3372. { we have
  3373. mov x, %treg
  3374. mov %treg, y
  3375. }
  3376. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3377. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3378. { we've got
  3379. mov x, %treg
  3380. mov %treg, y
  3381. with %treg is not used after }
  3382. case taicpu(p).oper[0]^.typ Of
  3383. { top_reg is covered by DeepMOVOpt }
  3384. top_const:
  3385. begin
  3386. { change
  3387. mov const, %treg
  3388. mov %treg, y
  3389. to
  3390. mov const, y
  3391. }
  3392. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3393. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3394. begin
  3395. if taicpu(hp1).oper[1]^.typ=top_reg then
  3396. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3397. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3398. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3399. RemoveInstruction(hp1);
  3400. Result:=true;
  3401. Exit;
  3402. end;
  3403. end;
  3404. top_ref:
  3405. case taicpu(hp1).oper[1]^.typ of
  3406. top_reg:
  3407. begin
  3408. { change
  3409. mov mem, %treg
  3410. mov %treg, %reg
  3411. to
  3412. mov mem, %reg"
  3413. }
  3414. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3415. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3416. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3417. RemoveInstruction(hp1);
  3418. Result:=true;
  3419. Exit;
  3420. end;
  3421. top_ref:
  3422. begin
  3423. {$ifdef x86_64}
  3424. { Look for the following to simplify:
  3425. mov x(mem1), %reg
  3426. mov %reg, y(mem2)
  3427. mov x+8(mem1), %reg
  3428. mov %reg, y+8(mem2)
  3429. Change to:
  3430. movdqu x(mem1), %xmmreg
  3431. movdqu %xmmreg, y(mem2)
  3432. ...but only as long as the memory blocks don't overlap
  3433. }
  3434. SourceRef := taicpu(p).oper[0]^.ref^;
  3435. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3436. if (taicpu(p).opsize = S_Q) and
  3437. GetNextInstruction(hp1, hp2) and
  3438. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3439. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3440. begin
  3441. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3442. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3443. Inc(SourceRef.offset, 8);
  3444. if UseAVX then
  3445. begin
  3446. MovAligned := A_VMOVDQA;
  3447. MovUnaligned := A_VMOVDQU;
  3448. end
  3449. else
  3450. begin
  3451. MovAligned := A_MOVDQA;
  3452. MovUnaligned := A_MOVDQU;
  3453. end;
  3454. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3455. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3456. begin
  3457. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3458. Inc(TargetRef.offset, 8);
  3459. if GetNextInstruction(hp2, hp3) and
  3460. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3461. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3462. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3463. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3464. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3465. begin
  3466. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3467. if NewMMReg <> NR_NO then
  3468. begin
  3469. { Remember that the offsets are 8 ahead }
  3470. if ((SourceRef.offset mod 16) = 8) and
  3471. (
  3472. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3473. (SourceRef.base = current_procinfo.framepointer) or
  3474. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3475. ) then
  3476. taicpu(p).opcode := MovAligned
  3477. else
  3478. taicpu(p).opcode := MovUnaligned;
  3479. taicpu(p).opsize := S_XMM;
  3480. taicpu(p).oper[1]^.reg := NewMMReg;
  3481. if ((TargetRef.offset mod 16) = 8) and
  3482. (
  3483. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3484. (TargetRef.base = current_procinfo.framepointer) or
  3485. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3486. ) then
  3487. taicpu(hp1).opcode := MovAligned
  3488. else
  3489. taicpu(hp1).opcode := MovUnaligned;
  3490. taicpu(hp1).opsize := S_XMM;
  3491. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3492. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3493. RemoveInstruction(hp2);
  3494. RemoveInstruction(hp3);
  3495. Result := True;
  3496. Exit;
  3497. end;
  3498. end;
  3499. end
  3500. else
  3501. begin
  3502. { See if the next references are 8 less rather than 8 greater }
  3503. Dec(SourceRef.offset, 16); { -8 the other way }
  3504. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3505. begin
  3506. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3507. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3508. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3509. GetNextInstruction(hp2, hp3) and
  3510. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3511. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3512. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3513. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3514. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3515. begin
  3516. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3517. if NewMMReg <> NR_NO then
  3518. begin
  3519. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3520. if ((SourceRef.offset mod 16) = 0) and
  3521. (
  3522. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3523. (SourceRef.base = current_procinfo.framepointer) or
  3524. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3525. ) then
  3526. taicpu(hp2).opcode := MovAligned
  3527. else
  3528. taicpu(hp2).opcode := MovUnaligned;
  3529. taicpu(hp2).opsize := S_XMM;
  3530. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3531. if ((TargetRef.offset mod 16) = 0) and
  3532. (
  3533. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3534. (TargetRef.base = current_procinfo.framepointer) or
  3535. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3536. ) then
  3537. taicpu(hp3).opcode := MovAligned
  3538. else
  3539. taicpu(hp3).opcode := MovUnaligned;
  3540. taicpu(hp3).opsize := S_XMM;
  3541. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3542. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3543. RemoveInstruction(hp1);
  3544. RemoveCurrentP(p, hp2);
  3545. Result := True;
  3546. Exit;
  3547. end;
  3548. end;
  3549. end;
  3550. end;
  3551. end;
  3552. {$endif x86_64}
  3553. end;
  3554. else
  3555. { The write target should be a reg or a ref }
  3556. InternalError(2021091601);
  3557. end;
  3558. else
  3559. ;
  3560. end
  3561. else
  3562. { %treg is used afterwards, but all eventualities
  3563. other than the first MOV instruction being a constant
  3564. are covered by DeepMOVOpt, so only check for that }
  3565. if (taicpu(p).oper[0]^.typ = top_const) and
  3566. (
  3567. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3568. not (cs_opt_size in current_settings.optimizerswitches) or
  3569. (taicpu(hp1).opsize = S_B)
  3570. ) and
  3571. (
  3572. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3573. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3574. ) then
  3575. begin
  3576. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3577. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3578. end;
  3579. end;
  3580. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3581. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3582. { mov reg1, mem1 or mov mem1, reg1
  3583. mov mem2, reg2 mov reg2, mem2}
  3584. begin
  3585. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3586. { mov reg1, mem1 or mov mem1, reg1
  3587. mov mem2, reg1 mov reg2, mem1}
  3588. begin
  3589. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3590. { Removes the second statement from
  3591. mov reg1, mem1/reg2
  3592. mov mem1/reg2, reg1 }
  3593. begin
  3594. if taicpu(p).oper[0]^.typ=top_reg then
  3595. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3596. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3597. RemoveInstruction(hp1);
  3598. Result:=true;
  3599. exit;
  3600. end
  3601. else
  3602. begin
  3603. TransferUsedRegs(TmpUsedRegs);
  3604. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3605. if (taicpu(p).oper[1]^.typ = top_ref) and
  3606. { mov reg1, mem1
  3607. mov mem2, reg1 }
  3608. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3609. GetNextInstruction(hp1, hp2) and
  3610. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3611. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3612. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3613. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3614. { change to
  3615. mov reg1, mem1 mov reg1, mem1
  3616. mov mem2, reg1 cmp reg1, mem2
  3617. cmp mem1, reg1
  3618. }
  3619. begin
  3620. RemoveInstruction(hp2);
  3621. taicpu(hp1).opcode := A_CMP;
  3622. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3623. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3624. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3625. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3626. end;
  3627. end;
  3628. end
  3629. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3630. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3631. begin
  3632. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3633. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3634. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3635. end
  3636. else
  3637. begin
  3638. TransferUsedRegs(TmpUsedRegs);
  3639. if GetNextInstruction(hp1, hp2) and
  3640. MatchOpType(taicpu(p),top_ref,top_reg) and
  3641. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3642. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3643. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3644. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3645. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3646. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3647. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3648. { mov mem1, %reg1
  3649. mov %reg1, mem2
  3650. mov mem2, reg2
  3651. to:
  3652. mov mem1, reg2
  3653. mov reg2, mem2}
  3654. begin
  3655. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3656. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3657. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3658. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3659. RemoveInstruction(hp2);
  3660. Result := True;
  3661. end
  3662. {$ifdef i386}
  3663. { this is enabled for i386 only, as the rules to create the reg sets below
  3664. are too complicated for x86-64, so this makes this code too error prone
  3665. on x86-64
  3666. }
  3667. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3668. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3669. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3670. { mov mem1, reg1 mov mem1, reg1
  3671. mov reg1, mem2 mov reg1, mem2
  3672. mov mem2, reg2 mov mem2, reg1
  3673. to: to:
  3674. mov mem1, reg1 mov mem1, reg1
  3675. mov mem1, reg2 mov reg1, mem2
  3676. mov reg1, mem2
  3677. or (if mem1 depends on reg1
  3678. and/or if mem2 depends on reg2)
  3679. to:
  3680. mov mem1, reg1
  3681. mov reg1, mem2
  3682. mov reg1, reg2
  3683. }
  3684. begin
  3685. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3686. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3687. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3688. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3689. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3690. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3691. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3692. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3693. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3694. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3695. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3696. end
  3697. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3698. begin
  3699. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3700. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3701. end
  3702. else
  3703. begin
  3704. RemoveInstruction(hp2);
  3705. end
  3706. {$endif i386}
  3707. ;
  3708. end;
  3709. end
  3710. { movl [mem1],reg1
  3711. movl [mem1],reg2
  3712. to
  3713. movl [mem1],reg1
  3714. movl reg1,reg2
  3715. }
  3716. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3717. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3718. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3719. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3720. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3721. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3722. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3723. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3724. begin
  3725. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3726. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3727. end;
  3728. { movl const1,[mem1]
  3729. movl [mem1],reg1
  3730. to
  3731. movl const1,reg1
  3732. movl reg1,[mem1]
  3733. }
  3734. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3735. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3736. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3737. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3738. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3739. begin
  3740. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3741. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3742. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3743. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3744. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3745. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3746. Result:=true;
  3747. exit;
  3748. end;
  3749. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3750. { Change:
  3751. movl %reg1,%reg2
  3752. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3753. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3754. To:
  3755. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3756. movl x(%reg1),%reg1
  3757. movl %reg1,%regX
  3758. }
  3759. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3760. begin
  3761. p_SourceReg := taicpu(p).oper[0]^.reg;
  3762. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3763. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3764. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3765. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3766. GetNextInstruction(hp1, hp2) and
  3767. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3768. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3769. begin
  3770. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3771. if RegInRef(p_TargetReg, SourceRef) and
  3772. { If %reg1 also appears in the second reference, then it will
  3773. not refer to the same memory block as the first reference }
  3774. not RegInRef(p_SourceReg, SourceRef) then
  3775. begin
  3776. { Check to see if the references match if %reg2 is changed to %reg1 }
  3777. if SourceRef.base = p_TargetReg then
  3778. SourceRef.base := p_SourceReg;
  3779. if SourceRef.index = p_TargetReg then
  3780. SourceRef.index := p_SourceReg;
  3781. { RefsEqual also checks to ensure both references are non-volatile }
  3782. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3783. begin
  3784. taicpu(hp2).loadreg(0, p_SourceReg);
  3785. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3786. Result := True;
  3787. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3788. begin
  3789. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3790. RemoveCurrentP(p, hp1);
  3791. Exit;
  3792. end
  3793. else
  3794. begin
  3795. { Check to see if %reg2 is no longer in use }
  3796. TransferUsedRegs(TmpUsedRegs);
  3797. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3798. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3799. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3800. begin
  3801. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3802. RemoveCurrentP(p, hp1);
  3803. Exit;
  3804. end;
  3805. end;
  3806. { If we reach this point, p and hp1 weren't actually modified,
  3807. so we can do a bit more work on this pass }
  3808. end;
  3809. end;
  3810. end;
  3811. end;
  3812. end;
  3813. {$ifdef x86_64}
  3814. { Change:
  3815. movl %reg1l,%reg2l
  3816. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3817. To:
  3818. movl %reg1l,%reg2l
  3819. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3820. If %reg1 = %reg3, convert to:
  3821. movl %reg1l,%reg2l
  3822. andl %reg1l,%reg1l
  3823. }
  3824. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3825. MatchOpType(taicpu(p), top_reg, top_reg) and
  3826. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3827. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3828. begin
  3829. TransferUsedRegs(TmpUsedRegs);
  3830. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3831. taicpu(hp1).opsize := S_L;
  3832. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3833. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3834. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3835. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3836. begin
  3837. { %reg1 = %reg3 }
  3838. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3839. taicpu(hp1).opcode := A_AND;
  3840. end
  3841. else
  3842. begin
  3843. { %reg1 <> %reg3 }
  3844. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3845. end;
  3846. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3847. begin
  3848. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3849. RemoveCurrentP(p, hp1);
  3850. Result := True;
  3851. Exit;
  3852. end
  3853. else
  3854. begin
  3855. { Initial instruction wasn't actually changed }
  3856. Include(OptsToCheck, aoc_ForceNewIteration);
  3857. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3858. appears below since %reg1 has technically changed }
  3859. if taicpu(hp1).opcode = A_AND then
  3860. Exit;
  3861. end;
  3862. end;
  3863. {$endif x86_64}
  3864. { search further than the next instruction for a mov (as long as it's not a jump) }
  3865. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3866. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3867. (taicpu(p).oper[1]^.typ = top_reg) and
  3868. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3869. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3870. begin
  3871. { we work with hp2 here, so hp1 can be still used later on when
  3872. checking for GetNextInstruction_p }
  3873. hp3 := hp1;
  3874. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3875. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3876. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3877. TransferUsedRegs(TmpUsedRegs);
  3878. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3879. if NotFirstIteration then
  3880. JumpTracking := TLinkedList.Create
  3881. else
  3882. JumpTracking := nil;
  3883. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3884. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3885. (hp2.typ=ait_instruction) do
  3886. begin
  3887. case taicpu(hp2).opcode of
  3888. A_POP:
  3889. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3890. begin
  3891. if not CrossJump and
  3892. not RegUsedBetween(p_TargetReg, p, hp2) then
  3893. begin
  3894. { We can remove the original MOV since the register
  3895. wasn't used between it and its popping from the stack }
  3896. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3897. RemoveCurrentp(p, hp1);
  3898. Result := True;
  3899. JumpTracking.Free;
  3900. Exit;
  3901. end;
  3902. { Can't go any further }
  3903. Break;
  3904. end;
  3905. A_MOV:
  3906. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3907. ((taicpu(p).oper[0]^.typ=top_const) or
  3908. ((taicpu(p).oper[0]^.typ=top_reg) and
  3909. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3910. )
  3911. ) then
  3912. begin
  3913. { we have
  3914. mov x, %treg
  3915. mov %treg, y
  3916. }
  3917. { We don't need to call UpdateUsedRegs for every instruction between
  3918. p and hp2 because the register we're concerned about will not
  3919. become deallocated (otherwise GetNextInstructionUsingReg would
  3920. have stopped at an earlier instruction). [Kit] }
  3921. TempRegUsed :=
  3922. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3923. RegReadByInstruction(p_TargetReg, hp3) or
  3924. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3925. case taicpu(p).oper[0]^.typ Of
  3926. top_reg:
  3927. begin
  3928. { change
  3929. mov %reg, %treg
  3930. mov %treg, y
  3931. to
  3932. mov %reg, y
  3933. }
  3934. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3935. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3936. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3937. begin
  3938. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3939. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3940. if TempRegUsed then
  3941. begin
  3942. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3943. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3944. { Set the start of the next GetNextInstructionUsingRegCond search
  3945. to start at the entry right before hp2 (which is about to be removed) }
  3946. hp3 := tai(hp2.Previous);
  3947. RemoveInstruction(hp2);
  3948. Include(OptsToCheck, aoc_ForceNewIteration);
  3949. { See if there's more we can optimise }
  3950. Continue;
  3951. end
  3952. else
  3953. begin
  3954. RemoveInstruction(hp2);
  3955. { We can remove the original MOV too }
  3956. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3957. RemoveCurrentP(p, hp1);
  3958. Result:=true;
  3959. JumpTracking.Free;
  3960. Exit;
  3961. end;
  3962. end
  3963. else
  3964. begin
  3965. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3966. taicpu(hp2).loadReg(0, p_SourceReg);
  3967. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3968. { Check to see if the register also appears in the reference }
  3969. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3970. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3971. { Don't remove the first instruction if the temporary register is in use }
  3972. if not TempRegUsed and
  3973. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3974. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3975. begin
  3976. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3977. RemoveCurrentP(p, hp1);
  3978. Result:=true;
  3979. JumpTracking.Free;
  3980. Exit;
  3981. end;
  3982. { No need to set Result to True here. If there's another instruction later
  3983. on that can be optimised, it will be detected when the main Pass 1 loop
  3984. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3985. end;
  3986. end;
  3987. top_const:
  3988. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3989. begin
  3990. { change
  3991. mov const, %treg
  3992. mov %treg, y
  3993. to
  3994. mov const, y
  3995. }
  3996. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3997. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3998. begin
  3999. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4000. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4001. if TempRegUsed then
  4002. begin
  4003. { Don't remove the first instruction if the temporary register is in use }
  4004. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4005. { No need to set Result to True. If there's another instruction later on
  4006. that can be optimised, it will be detected when the main Pass 1 loop
  4007. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4008. end
  4009. else
  4010. begin
  4011. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4012. RemoveCurrentP(p, hp1);
  4013. Result:=true;
  4014. Exit;
  4015. end;
  4016. end;
  4017. end;
  4018. else
  4019. Internalerror(2019103001);
  4020. end;
  4021. end
  4022. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4023. begin
  4024. if not CrossJump and
  4025. not RegUsedBetween(p_TargetReg, p, hp2) and
  4026. not RegReadByInstruction(p_TargetReg, hp2) then
  4027. begin
  4028. { Register is not used before it is overwritten }
  4029. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4030. RemoveCurrentp(p, hp1);
  4031. Result := True;
  4032. Exit;
  4033. end;
  4034. if (taicpu(p).oper[0]^.typ = top_const) and
  4035. (taicpu(hp2).oper[0]^.typ = top_const) then
  4036. begin
  4037. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4038. begin
  4039. { Same value - register hasn't changed }
  4040. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4041. RemoveInstruction(hp2);
  4042. Include(OptsToCheck, aoc_ForceNewIteration);
  4043. { See if there's more we can optimise }
  4044. Continue;
  4045. end;
  4046. end;
  4047. {$ifdef x86_64}
  4048. end
  4049. { Change:
  4050. movl %reg1l,%reg2l
  4051. ...
  4052. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4053. To:
  4054. movl %reg1l,%reg2l
  4055. ...
  4056. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4057. If %reg1 = %reg3, convert to:
  4058. movl %reg1l,%reg2l
  4059. ...
  4060. andl %reg1l,%reg1l
  4061. }
  4062. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4063. (taicpu(p).oper[0]^.typ = top_reg) and
  4064. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4065. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4066. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4067. begin
  4068. TempRegUsed :=
  4069. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4070. RegReadByInstruction(p_TargetReg, hp3) or
  4071. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4072. taicpu(hp2).opsize := S_L;
  4073. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4074. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4075. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4076. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4077. begin
  4078. { %reg1 = %reg3 }
  4079. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4080. taicpu(hp2).opcode := A_AND;
  4081. end
  4082. else
  4083. begin
  4084. { %reg1 <> %reg3 }
  4085. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4086. end;
  4087. if not TempRegUsed then
  4088. begin
  4089. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4090. RemoveCurrentP(p, hp1);
  4091. Result := True;
  4092. Exit;
  4093. end
  4094. else
  4095. begin
  4096. { Initial instruction wasn't actually changed }
  4097. Include(OptsToCheck, aoc_ForceNewIteration);
  4098. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4099. appears below since %reg1 has technically changed }
  4100. if taicpu(hp2).opcode = A_AND then
  4101. Break;
  4102. end;
  4103. {$endif x86_64}
  4104. end;
  4105. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4106. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4107. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4108. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4109. begin
  4110. {
  4111. Change from:
  4112. mov ###, %reg
  4113. ...
  4114. movs/z %reg,%reg (Same register, just different sizes)
  4115. To:
  4116. movs/z ###, %reg (Longer version)
  4117. ...
  4118. (remove)
  4119. }
  4120. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4121. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4122. { Keep the first instruction as mov if ### is a constant }
  4123. if taicpu(p).oper[0]^.typ = top_const then
  4124. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4125. else
  4126. begin
  4127. taicpu(p).opcode := taicpu(hp2).opcode;
  4128. taicpu(p).opsize := taicpu(hp2).opsize;
  4129. end;
  4130. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4131. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4132. RemoveInstruction(hp2);
  4133. Result := True;
  4134. JumpTracking.Free;
  4135. Exit;
  4136. end;
  4137. else
  4138. { Move down to the if-block below };
  4139. end;
  4140. { Also catches MOV/S/Z instructions that aren't modified }
  4141. if taicpu(p).oper[0]^.typ = top_reg then
  4142. begin
  4143. p_SourceReg := taicpu(p).oper[0]^.reg;
  4144. if
  4145. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4146. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4147. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4148. begin
  4149. Result := True;
  4150. { Just in case something didn't get modified (e.g. an
  4151. implicit register). Also, if it does read from this
  4152. register, then there's no longer an advantage to
  4153. changing the register on subsequent instructions.}
  4154. if not RegReadByInstruction(p_TargetReg, hp2) then
  4155. begin
  4156. { If a conditional jump was crossed, do not delete
  4157. the original MOV no matter what }
  4158. if not CrossJump and
  4159. { RegEndOfLife returns True if the register is
  4160. deallocated before the next instruction or has
  4161. been loaded with a new value }
  4162. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4163. begin
  4164. { We can remove the original MOV }
  4165. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4166. RemoveCurrentp(p, hp1);
  4167. JumpTracking.Free;
  4168. Result := True;
  4169. Exit;
  4170. end;
  4171. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4172. begin
  4173. { See if there's more we can optimise }
  4174. hp3 := hp2;
  4175. Continue;
  4176. end;
  4177. end;
  4178. end;
  4179. end;
  4180. { Break out of the while loop under normal circumstances }
  4181. Break;
  4182. end;
  4183. JumpTracking.Free;
  4184. end;
  4185. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4186. (taicpu(p).oper[1]^.typ = top_reg) and
  4187. (taicpu(p).opsize = S_L) and
  4188. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4189. (hp2.typ = ait_instruction) and
  4190. (taicpu(hp2).opcode = A_AND) and
  4191. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4192. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4193. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4194. ) then
  4195. begin
  4196. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4197. begin
  4198. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4199. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4200. begin
  4201. { Optimize out:
  4202. mov x, %reg
  4203. and ffffffffh, %reg
  4204. }
  4205. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4206. RemoveInstruction(hp2);
  4207. Result:=true;
  4208. exit;
  4209. end;
  4210. end;
  4211. end;
  4212. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4213. x >= RetOffset) as it doesn't do anything (it writes either to a
  4214. parameter or to the temporary storage room for the function
  4215. result)
  4216. }
  4217. if IsExitCode(hp1) and
  4218. (taicpu(p).oper[1]^.typ = top_ref) and
  4219. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4220. (
  4221. (
  4222. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4223. not (
  4224. assigned(current_procinfo.procdef.funcretsym) and
  4225. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4226. )
  4227. ) or
  4228. { Also discard writes to the stack that are below the base pointer,
  4229. as this is temporary storage rather than a function result on the
  4230. stack, say. }
  4231. (
  4232. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4233. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4234. )
  4235. ) then
  4236. begin
  4237. RemoveCurrentp(p, hp1);
  4238. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4239. RemoveLastDeallocForFuncRes(p);
  4240. Result:=true;
  4241. exit;
  4242. end;
  4243. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4244. begin
  4245. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4246. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4247. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4248. begin
  4249. { change
  4250. mov reg1, mem1
  4251. test/cmp x, mem1
  4252. to
  4253. mov reg1, mem1
  4254. test/cmp x, reg1
  4255. }
  4256. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4257. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4258. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4259. Result := True;
  4260. Exit;
  4261. end;
  4262. if DoMovCmpMemOpt(p, hp1) then
  4263. begin
  4264. Result := True;
  4265. Exit;
  4266. end;
  4267. end;
  4268. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4269. { If the flags register is in use, don't change the instruction to an
  4270. ADD otherwise this will scramble the flags. [Kit] }
  4271. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4272. begin
  4273. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4274. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4275. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4276. ) or
  4277. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4278. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4279. )
  4280. ) then
  4281. { mov reg1,ref
  4282. lea reg2,[reg1,reg2]
  4283. to
  4284. add reg2,ref}
  4285. begin
  4286. TransferUsedRegs(TmpUsedRegs);
  4287. { reg1 may not be used afterwards }
  4288. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4289. begin
  4290. Taicpu(hp1).opcode:=A_ADD;
  4291. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4292. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4293. RemoveCurrentp(p, hp1);
  4294. result:=true;
  4295. exit;
  4296. end;
  4297. end;
  4298. { If the LEA instruction can be converted into an arithmetic instruction,
  4299. it may be possible to then fold it in the next optimisation, otherwise
  4300. there's nothing more that can be optimised here. }
  4301. if not ConvertLEA(taicpu(hp1)) then
  4302. Exit;
  4303. end;
  4304. if (taicpu(p).oper[1]^.typ = top_reg) and
  4305. (hp1.typ = ait_instruction) and
  4306. GetNextInstruction(hp1, hp2) and
  4307. MatchInstruction(hp2,A_MOV,[]) and
  4308. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4309. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4310. (
  4311. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4312. {$ifdef x86_64}
  4313. or
  4314. (
  4315. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4316. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4317. )
  4318. {$endif x86_64}
  4319. ) then
  4320. begin
  4321. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4322. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4323. { change movsX/movzX reg/ref, reg2
  4324. add/sub/or/... reg3/$const, reg2
  4325. mov reg2 reg/ref
  4326. dealloc reg2
  4327. to
  4328. add/sub/or/... reg3/$const, reg/ref }
  4329. begin
  4330. TransferUsedRegs(TmpUsedRegs);
  4331. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4332. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4333. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4334. begin
  4335. { by example:
  4336. movswl %si,%eax movswl %si,%eax p
  4337. decl %eax addl %edx,%eax hp1
  4338. movw %ax,%si movw %ax,%si hp2
  4339. ->
  4340. movswl %si,%eax movswl %si,%eax p
  4341. decw %eax addw %edx,%eax hp1
  4342. movw %ax,%si movw %ax,%si hp2
  4343. }
  4344. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4345. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4346. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4347. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4348. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4349. {
  4350. ->
  4351. movswl %si,%eax movswl %si,%eax p
  4352. decw %si addw %dx,%si hp1
  4353. movw %ax,%si movw %ax,%si hp2
  4354. }
  4355. case taicpu(hp1).ops of
  4356. 1:
  4357. begin
  4358. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4359. if taicpu(hp1).oper[0]^.typ=top_reg then
  4360. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4361. end;
  4362. 2:
  4363. begin
  4364. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4365. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4366. (taicpu(hp1).opcode<>A_SHL) and
  4367. (taicpu(hp1).opcode<>A_SHR) and
  4368. (taicpu(hp1).opcode<>A_SAR) then
  4369. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4370. end;
  4371. else
  4372. internalerror(2008042701);
  4373. end;
  4374. {
  4375. ->
  4376. decw %si addw %dx,%si p
  4377. }
  4378. RemoveInstruction(hp2);
  4379. RemoveCurrentP(p, hp1);
  4380. Result:=True;
  4381. Exit;
  4382. end;
  4383. end;
  4384. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4385. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4386. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4387. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4388. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4389. )
  4390. {$ifdef i386}
  4391. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4392. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4393. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4394. {$endif i386}
  4395. then
  4396. { change movsX/movzX reg/ref, reg2
  4397. add/sub/or/... regX/$const, reg2
  4398. mov reg2, reg3
  4399. dealloc reg2
  4400. to
  4401. movsX/movzX reg/ref, reg3
  4402. add/sub/or/... reg3/$const, reg3
  4403. }
  4404. begin
  4405. TransferUsedRegs(TmpUsedRegs);
  4406. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4407. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4408. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4409. begin
  4410. { by example:
  4411. movswl %si,%eax movswl %si,%eax p
  4412. decl %eax addl %edx,%eax hp1
  4413. movw %ax,%si movw %ax,%si hp2
  4414. ->
  4415. movswl %si,%eax movswl %si,%eax p
  4416. decw %eax addw %edx,%eax hp1
  4417. movw %ax,%si movw %ax,%si hp2
  4418. }
  4419. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4420. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4421. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4422. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4423. { limit size of constants as well to avoid assembler errors, but
  4424. check opsize to avoid overflow when left shifting the 1 }
  4425. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4426. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4427. {$ifdef x86_64}
  4428. { Be careful of, for example:
  4429. movl %reg1,%reg2
  4430. addl %reg3,%reg2
  4431. movq %reg2,%reg4
  4432. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4433. }
  4434. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4435. begin
  4436. taicpu(hp2).changeopsize(S_L);
  4437. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4438. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4439. end;
  4440. {$endif x86_64}
  4441. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4442. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4443. if taicpu(p).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4446. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4447. {
  4448. ->
  4449. movswl %si,%eax movswl %si,%eax p
  4450. decw %si addw %dx,%si hp1
  4451. movw %ax,%si movw %ax,%si hp2
  4452. }
  4453. case taicpu(hp1).ops of
  4454. 1:
  4455. begin
  4456. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4457. if taicpu(hp1).oper[0]^.typ=top_reg then
  4458. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4459. end;
  4460. 2:
  4461. begin
  4462. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4463. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4464. (taicpu(hp1).opcode<>A_SHL) and
  4465. (taicpu(hp1).opcode<>A_SHR) and
  4466. (taicpu(hp1).opcode<>A_SAR) then
  4467. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4468. end;
  4469. else
  4470. internalerror(2018111801);
  4471. end;
  4472. {
  4473. ->
  4474. decw %si addw %dx,%si p
  4475. }
  4476. RemoveInstruction(hp2);
  4477. end;
  4478. end;
  4479. end;
  4480. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4481. GetNextInstruction(hp1, hp2) and
  4482. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4483. MatchOperand(Taicpu(p).oper[0]^,0) and
  4484. (Taicpu(p).oper[1]^.typ = top_reg) and
  4485. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4487. { mov reg1,0
  4488. bts reg1,operand1 --> mov reg1,operand2
  4489. or reg1,operand2 bts reg1,operand1}
  4490. begin
  4491. Taicpu(hp2).opcode:=A_MOV;
  4492. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4493. asml.remove(hp1);
  4494. insertllitem(hp2,hp2.next,hp1);
  4495. RemoveCurrentp(p, hp1);
  4496. Result:=true;
  4497. exit;
  4498. end;
  4499. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4500. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4501. GetNextInstruction(hp1, hp2) and
  4502. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4503. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4504. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4505. { change
  4506. mov reg1,reg2
  4507. sub reg3,reg2
  4508. cmp reg3,reg1
  4509. into
  4510. mov reg1,reg2
  4511. sub reg3,reg2
  4512. }
  4513. begin
  4514. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4515. RemoveInstruction(hp2);
  4516. Result:=true;
  4517. exit;
  4518. end;
  4519. {
  4520. mov ref,reg0
  4521. <op> reg0,reg1
  4522. dealloc reg0
  4523. to
  4524. <op> ref,reg1
  4525. }
  4526. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4527. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4528. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4529. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4530. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4531. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4532. begin
  4533. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4534. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4535. RemoveCurrentp(p, hp1);
  4536. Result:=true;
  4537. exit;
  4538. end;
  4539. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4540. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4541. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4542. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4543. begin
  4544. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4545. {$ifdef x86_64}
  4546. { Convert:
  4547. movq x(ref),%reg64
  4548. shrq y,%reg64
  4549. To:
  4550. movl x+4(ref),%reg32
  4551. shrl y-32,%reg32 (Remove if y = 32)
  4552. }
  4553. if (taicpu(p).opsize = S_Q) and
  4554. (taicpu(hp1).opcode = A_SHR) and
  4555. (taicpu(hp1).oper[0]^.val >= 32) then
  4556. begin
  4557. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4558. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4559. { Convert to 32-bit }
  4560. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4561. taicpu(p).opsize := S_L;
  4562. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4563. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4564. if (taicpu(hp1).oper[0]^.val = 32) then
  4565. begin
  4566. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4567. RemoveInstruction(hp1);
  4568. end
  4569. else
  4570. begin
  4571. { This will potentially open up more arithmetic operations since
  4572. the peephole optimizer now has a big hint that only the lower
  4573. 32 bits are currently in use (and opcodes are smaller in size) }
  4574. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4575. taicpu(hp1).opsize := S_L;
  4576. Dec(taicpu(hp1).oper[0]^.val, 32);
  4577. DebugMsg(SPeepholeOptimization + PreMessage +
  4578. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4579. end;
  4580. Result := True;
  4581. Exit;
  4582. end;
  4583. {$endif x86_64}
  4584. { Convert:
  4585. movl x(ref),%reg
  4586. shrl $24,%reg
  4587. To:
  4588. movzbl x+3(ref),%reg
  4589. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4590. Also accept sar instead of shr, but convert to movsx instead of movzx
  4591. }
  4592. if taicpu(hp1).opcode = A_SHR then
  4593. MovUnaligned := A_MOVZX
  4594. else
  4595. MovUnaligned := A_MOVSX;
  4596. NewSize := S_NO;
  4597. NewOffset := 0;
  4598. case taicpu(p).opsize of
  4599. S_B:
  4600. { No valid combinations };
  4601. S_W:
  4602. if (taicpu(hp1).oper[0]^.val = 8) then
  4603. begin
  4604. NewSize := S_BW;
  4605. NewOffset := 1;
  4606. end;
  4607. S_L:
  4608. case taicpu(hp1).oper[0]^.val of
  4609. 16:
  4610. begin
  4611. NewSize := S_WL;
  4612. NewOffset := 2;
  4613. end;
  4614. 24:
  4615. begin
  4616. NewSize := S_BL;
  4617. NewOffset := 3;
  4618. end;
  4619. else
  4620. ;
  4621. end;
  4622. {$ifdef x86_64}
  4623. S_Q:
  4624. case taicpu(hp1).oper[0]^.val of
  4625. 32:
  4626. begin
  4627. if taicpu(hp1).opcode = A_SAR then
  4628. begin
  4629. { 32-bit to 64-bit is a distinct instruction }
  4630. MovUnaligned := A_MOVSXD;
  4631. NewSize := S_LQ;
  4632. NewOffset := 4;
  4633. end
  4634. else
  4635. { Should have been handled by MovShr2Mov above }
  4636. InternalError(2022081811);
  4637. end;
  4638. 48:
  4639. begin
  4640. NewSize := S_WQ;
  4641. NewOffset := 6;
  4642. end;
  4643. 56:
  4644. begin
  4645. NewSize := S_BQ;
  4646. NewOffset := 7;
  4647. end;
  4648. else
  4649. ;
  4650. end;
  4651. {$endif x86_64}
  4652. else
  4653. InternalError(2022081810);
  4654. end;
  4655. if (NewSize <> S_NO) and
  4656. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4657. begin
  4658. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4659. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4660. debug_op2str(MovUnaligned);
  4661. {$ifdef x86_64}
  4662. if MovUnaligned <> A_MOVSXD then
  4663. { Don't add size suffix for MOVSXD }
  4664. {$endif x86_64}
  4665. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4666. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4667. taicpu(p).opcode := MovUnaligned;
  4668. taicpu(p).opsize := NewSize;
  4669. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4670. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4671. RemoveInstruction(hp1);
  4672. Result := True;
  4673. Exit;
  4674. end;
  4675. end;
  4676. { Backward optimisation shared with OptPass2MOV }
  4677. if FuncMov2Func(p, hp1) then
  4678. begin
  4679. Result := True;
  4680. Exit;
  4681. end;
  4682. end;
  4683. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4684. var
  4685. hp1 : tai;
  4686. begin
  4687. Result:=false;
  4688. if taicpu(p).ops <> 2 then
  4689. exit;
  4690. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4691. GetNextInstruction(p,hp1) then
  4692. begin
  4693. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4694. (taicpu(hp1).ops = 2) then
  4695. begin
  4696. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4697. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4698. { movXX reg1, mem1 or movXX mem1, reg1
  4699. movXX mem2, reg2 movXX reg2, mem2}
  4700. begin
  4701. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4702. { movXX reg1, mem1 or movXX mem1, reg1
  4703. movXX mem2, reg1 movXX reg2, mem1}
  4704. begin
  4705. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4706. begin
  4707. { Removes the second statement from
  4708. movXX reg1, mem1/reg2
  4709. movXX mem1/reg2, reg1
  4710. }
  4711. if taicpu(p).oper[0]^.typ=top_reg then
  4712. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4713. { Removes the second statement from
  4714. movXX mem1/reg1, reg2
  4715. movXX reg2, mem1/reg1
  4716. }
  4717. if (taicpu(p).oper[1]^.typ=top_reg) and
  4718. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4719. begin
  4720. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4721. RemoveInstruction(hp1);
  4722. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4723. Result:=true;
  4724. exit;
  4725. end
  4726. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4727. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4728. begin
  4729. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4730. RemoveInstruction(hp1);
  4731. Result:=true;
  4732. exit;
  4733. end;
  4734. end
  4735. end;
  4736. end;
  4737. end;
  4738. end;
  4739. end;
  4740. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4741. var
  4742. hp1 : tai;
  4743. begin
  4744. result:=false;
  4745. { replace
  4746. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4747. MovX %mreg2,%mreg1
  4748. dealloc %mreg2
  4749. by
  4750. <Op>X %mreg2,%mreg1
  4751. ?
  4752. }
  4753. if GetNextInstruction(p,hp1) and
  4754. { we mix single and double opperations here because we assume that the compiler
  4755. generates vmovapd only after double operations and vmovaps only after single operations }
  4756. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4757. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4758. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4759. (taicpu(p).oper[0]^.typ=top_reg) then
  4760. begin
  4761. TransferUsedRegs(TmpUsedRegs);
  4762. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4763. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4764. begin
  4765. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4766. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4767. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4768. RemoveInstruction(hp1);
  4769. result:=true;
  4770. end;
  4771. end;
  4772. end;
  4773. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4774. var
  4775. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4776. JumpLabel, JumpLabel_dist: TAsmLabel;
  4777. FirstValue, SecondValue: TCGInt;
  4778. TempBool: Boolean;
  4779. begin
  4780. Result := False;
  4781. if (taicpu(p).oper[0]^.typ = top_const) and
  4782. (taicpu(p).oper[0]^.val <> -1) then
  4783. begin
  4784. { Convert unsigned maximum constants to -1 to aid optimisation }
  4785. case taicpu(p).opsize of
  4786. S_B:
  4787. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. S_W:
  4794. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4795. begin
  4796. taicpu(p).oper[0]^.val := -1;
  4797. Result := True;
  4798. Exit;
  4799. end;
  4800. S_L:
  4801. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4802. begin
  4803. taicpu(p).oper[0]^.val := -1;
  4804. Result := True;
  4805. Exit;
  4806. end;
  4807. {$ifdef x86_64}
  4808. S_Q:
  4809. { Storing anything greater than $7FFFFFFF is not possible so do
  4810. nothing };
  4811. {$endif x86_64}
  4812. else
  4813. InternalError(2021121001);
  4814. end;
  4815. end;
  4816. if GetNextInstruction(p, hp1) and
  4817. TrySwapMovCmp(p, hp1) then
  4818. begin
  4819. Result := True;
  4820. Exit;
  4821. end;
  4822. if MatchInstruction(hp1, A_Jcc, []) then
  4823. begin
  4824. TempBool := True;
  4825. if DoJumpOptimizations(hp1, TempBool) or
  4826. not TempBool then
  4827. begin
  4828. Result := True;
  4829. if Assigned(hp1) then
  4830. begin
  4831. if (hp1.typ in [ait_align]) then
  4832. SkipAligns(hp1, hp1);
  4833. { CollapseZeroDistJump will be set to the label after the
  4834. jump if it optimises, whether or not it's live or dead }
  4835. if (hp1.typ in [ait_label]) and
  4836. not (tai_label(hp1).labsym.is_used) then
  4837. GetNextInstruction(hp1, hp1);
  4838. end;
  4839. TransferUsedRegs(TmpUsedRegs);
  4840. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4841. if not Assigned(hp1) or
  4842. (
  4843. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4844. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4845. ) then
  4846. begin
  4847. { No more conditional jumps; conditional statement is no longer required }
  4848. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4849. RemoveCurrentP(p);
  4850. end;
  4851. Exit;
  4852. end;
  4853. end;
  4854. { Search for:
  4855. test $x,(reg/ref)
  4856. jne @lbl1
  4857. test $y,(reg/ref) (same register or reference)
  4858. jne @lbl1
  4859. Change to:
  4860. test $(x or y),(reg/ref)
  4861. jne @lbl1
  4862. (Note, this doesn't work with je instead of jne)
  4863. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4864. Also search for:
  4865. test $x,(reg/ref)
  4866. je @lbl1
  4867. ...
  4868. test $y,(reg/ref)
  4869. je/jne @lbl2
  4870. If (x or y) = x, then the second jump is deterministic
  4871. }
  4872. if (
  4873. (
  4874. (taicpu(p).oper[0]^.typ = top_const) or
  4875. (
  4876. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4877. (taicpu(p).oper[0]^.typ = top_reg) and
  4878. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4879. )
  4880. ) and
  4881. MatchInstruction(hp1, A_JCC, [])
  4882. ) then
  4883. begin
  4884. if (taicpu(p).oper[0]^.typ = top_reg) and
  4885. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4886. FirstValue := -1
  4887. else
  4888. FirstValue := taicpu(p).oper[0]^.val;
  4889. { If we have several test/jne's in a row, it might be the case that
  4890. the second label doesn't go to the same location, but the one
  4891. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4892. so accommodate for this with a while loop.
  4893. }
  4894. hp1_last := hp1;
  4895. while (
  4896. (
  4897. (taicpu(p).oper[1]^.typ = top_reg) and
  4898. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4899. ) or GetNextInstruction(hp1_last, p_dist)
  4900. ) and (p_dist.typ = ait_instruction) do
  4901. begin
  4902. if (
  4903. (
  4904. (taicpu(p_dist).opcode = A_TEST) and
  4905. (
  4906. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4907. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4908. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4909. )
  4910. ) or
  4911. (
  4912. { cmp 0,%reg = test %reg,%reg }
  4913. (taicpu(p_dist).opcode = A_CMP) and
  4914. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4915. )
  4916. ) and
  4917. { Make sure the destination operands are actually the same }
  4918. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4919. GetNextInstruction(p_dist, hp1_dist) and
  4920. MatchInstruction(hp1_dist, A_JCC, []) then
  4921. begin
  4922. if
  4923. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4924. (
  4925. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4926. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4927. ) then
  4928. SecondValue := -1
  4929. else
  4930. SecondValue := taicpu(p_dist).oper[0]^.val;
  4931. { If both of the TEST constants are identical, delete the
  4932. second TEST that is unnecessary (be careful though, just
  4933. in case the flags are modified in between) }
  4934. if (FirstValue = SecondValue) then
  4935. begin
  4936. { We have to check the entire range }
  4937. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4938. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4939. begin
  4940. { Since the second jump's condition is a subset of the first, we
  4941. know it will never branch because the first jump dominates it.
  4942. Get it out of the way now rather than wait for the jump
  4943. optimisations for a speed boost. }
  4944. if IsJumpToLabel(taicpu(hp1_dist)) then
  4945. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4946. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4947. RemoveInstruction(hp1_dist);
  4948. Result := True;
  4949. end
  4950. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4951. begin
  4952. { If the inverse of the first condition is a subset of the second,
  4953. the second one will definitely branch if the first one doesn't }
  4954. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4955. { We can remove the TEST instruction too }
  4956. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4957. RemoveInstruction(p_dist);
  4958. MakeUnconditional(taicpu(hp1_dist));
  4959. RemoveDeadCodeAfterJump(hp1_dist);
  4960. { Since the jump is now unconditional, we can't
  4961. continue any further with this particular
  4962. optimisation. The original TEST is still intact
  4963. though, so there might be something else we can
  4964. do }
  4965. Include(OptsToCheck, aoc_ForceNewIteration);
  4966. Break;
  4967. end;
  4968. if Result or
  4969. { If a jump wasn't removed or made unconditional, only
  4970. remove the identical TEST instruction if the flags
  4971. weren't modified }
  4972. TempBool then
  4973. begin
  4974. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4975. RemoveInstruction(p_dist);
  4976. { If the jump was removed or made unconditional, we
  4977. don't need to allocate NR_DEFAULTFLAGS over the
  4978. entire range }
  4979. if not Result then
  4980. begin
  4981. { Mark the flags as 'in use' over the entire range }
  4982. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4983. { Speed gain - continue search from the Jcc instruction }
  4984. hp1_last := hp1_dist;
  4985. { Only the TEST instruction was removed, and the
  4986. original was unchanged, so we can safely do
  4987. another iteration of the while loop }
  4988. Include(OptsToCheck, aoc_ForceNewIteration);
  4989. Continue;
  4990. end;
  4991. Exit;
  4992. end;
  4993. end;
  4994. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4995. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4996. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4997. then the second jump will never branch, so it can also be
  4998. removed regardless of where it goes }
  4999. (
  5000. (FirstValue = -1) or
  5001. (SecondValue = -1) or
  5002. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5003. ) and
  5004. (
  5005. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5006. { Always adjacent under -O2 and under }
  5007. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5008. (
  5009. GetNextInstruction(hp1, hp1_last) and
  5010. (hp1_last = p_dist)
  5011. )
  5012. ) then
  5013. begin
  5014. { Same jump location... can be a register since nothing's changed }
  5015. { If any of the entries are equivalent to test %reg,%reg, then the
  5016. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5017. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5018. if IsJumpToLabel(taicpu(hp1_dist)) then
  5019. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5020. { Only remove the second test if no jumps or other conditional instructions follow }
  5021. TransferUsedRegs(TmpUsedRegs);
  5022. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5023. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5024. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5025. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5026. begin
  5027. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5028. RemoveInstruction(p_dist);
  5029. { Remove the first jump, not the second, to keep
  5030. any register deallocations between the second
  5031. TEST/JNE pair in the same place. Aids future
  5032. optimisation. }
  5033. RemoveInstruction(hp1);
  5034. end
  5035. else
  5036. begin
  5037. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5038. { Remove second jump in this instance }
  5039. RemoveInstruction(hp1_dist);
  5040. end;
  5041. Result := True;
  5042. Exit;
  5043. end;
  5044. end;
  5045. if { If -O2 and under, it may stop on any old instruction }
  5046. (cs_opt_level3 in current_settings.optimizerswitches) and
  5047. (taicpu(p).oper[1]^.typ = top_reg) and
  5048. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5049. begin
  5050. hp1_last := p_dist;
  5051. Continue;
  5052. end;
  5053. Break;
  5054. end;
  5055. end;
  5056. { Search for:
  5057. test %reg,%reg
  5058. j(c1) @lbl1
  5059. ...
  5060. @lbl:
  5061. test %reg,%reg (same register)
  5062. j(c2) @lbl2
  5063. If c2 is a subset of c1, change to:
  5064. test %reg,%reg
  5065. j(c1) @lbl2
  5066. (@lbl1 may become a dead label as a result)
  5067. }
  5068. if (taicpu(p).oper[1]^.typ = top_reg) and
  5069. (taicpu(p).oper[0]^.typ = top_reg) and
  5070. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5071. MatchInstruction(hp1, A_JCC, []) and
  5072. IsJumpToLabel(taicpu(hp1)) then
  5073. begin
  5074. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5075. p_label := nil;
  5076. if Assigned(JumpLabel) then
  5077. p_label := getlabelwithsym(JumpLabel);
  5078. if Assigned(p_label) and
  5079. GetNextInstruction(p_label, p_dist) and
  5080. MatchInstruction(p_dist, A_TEST, []) and
  5081. { It's fine if the second test uses smaller sub-registers }
  5082. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5083. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5084. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5085. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5086. GetNextInstruction(p_dist, hp1_dist) and
  5087. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5088. begin
  5089. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5090. if JumpLabel = JumpLabel_dist then
  5091. { This is an infinite loop }
  5092. Exit;
  5093. { Best optimisation when the first condition is a subset (or equal) of the second }
  5094. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5095. begin
  5096. { Any registers used here will already be allocated }
  5097. if Assigned(JumpLabel) then
  5098. JumpLabel.DecRefs;
  5099. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5100. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5101. Result := True;
  5102. Exit;
  5103. end;
  5104. end;
  5105. end;
  5106. end;
  5107. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5108. var
  5109. hp1, hp2: tai;
  5110. ActiveReg: TRegister;
  5111. OldOffset: asizeint;
  5112. ThisConst: TCGInt;
  5113. function RegDeallocated: Boolean;
  5114. begin
  5115. TransferUsedRegs(TmpUsedRegs);
  5116. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5117. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5118. end;
  5119. begin
  5120. result:=false;
  5121. hp1 := nil;
  5122. { replace
  5123. addX const,%reg1
  5124. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5125. dealloc %reg1
  5126. by
  5127. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5128. }
  5129. if MatchOpType(taicpu(p),top_const,top_reg) then
  5130. begin
  5131. ActiveReg := taicpu(p).oper[1]^.reg;
  5132. { Ensures the entire register was updated }
  5133. if (taicpu(p).opsize >= S_L) and
  5134. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5135. MatchInstruction(hp1,A_LEA,[]) and
  5136. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5137. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5138. (
  5139. { Cover the case where the register in the reference is also the destination register }
  5140. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5141. (
  5142. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5143. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5144. RegDeallocated
  5145. )
  5146. ) then
  5147. begin
  5148. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5149. {$push}
  5150. {$R-}{$Q-}
  5151. { Explicitly disable overflow checking for these offset calculation
  5152. as those do not matter for the final result }
  5153. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5154. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5155. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5156. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5157. {$pop}
  5158. {$ifdef x86_64}
  5159. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5160. begin
  5161. { Overflow; abort }
  5162. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5163. end
  5164. else
  5165. {$endif x86_64}
  5166. begin
  5167. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5168. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5169. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5170. RemoveCurrentP(p, hp1)
  5171. else
  5172. RemoveCurrentP(p);
  5173. result:=true;
  5174. Exit;
  5175. end;
  5176. end;
  5177. if (
  5178. { Save calling GetNextInstructionUsingReg again }
  5179. Assigned(hp1) or
  5180. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5181. ) and
  5182. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5183. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5184. begin
  5185. if taicpu(hp1).oper[0]^.typ = top_const then
  5186. begin
  5187. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5188. if taicpu(hp1).opcode = A_ADD then
  5189. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5190. else
  5191. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5192. Result := True;
  5193. { Handle any overflows }
  5194. case taicpu(p).opsize of
  5195. S_B:
  5196. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5197. S_W:
  5198. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5199. S_L:
  5200. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5201. {$ifdef x86_64}
  5202. S_Q:
  5203. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5204. { Overflow; abort }
  5205. Result := False
  5206. else
  5207. taicpu(p).oper[0]^.val := ThisConst;
  5208. {$endif x86_64}
  5209. else
  5210. InternalError(2021102610);
  5211. end;
  5212. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5213. if Result then
  5214. begin
  5215. if (taicpu(p).oper[0]^.val < 0) and
  5216. (
  5217. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5218. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5219. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5220. ) then
  5221. begin
  5222. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5223. taicpu(p).opcode := A_SUB;
  5224. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5225. end
  5226. else
  5227. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5228. RemoveInstruction(hp1);
  5229. end;
  5230. end
  5231. else
  5232. begin
  5233. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5234. TransferUsedRegs(TmpUsedRegs);
  5235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5236. hp2 := p;
  5237. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5238. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5239. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5240. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5241. begin
  5242. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5243. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5244. Asml.Remove(p);
  5245. Asml.InsertAfter(p, hp1);
  5246. p := hp1;
  5247. Result := True;
  5248. Exit;
  5249. end;
  5250. end;
  5251. end;
  5252. if DoArithCombineOpt(p) then
  5253. Result:=true;
  5254. end;
  5255. end;
  5256. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5257. var
  5258. hp1, hp2: tai;
  5259. ref: Integer;
  5260. saveref: treference;
  5261. offsetcalc: Int64;
  5262. TempReg: TRegister;
  5263. Multiple: TCGInt;
  5264. Adjacent, IntermediateRegDiscarded: Boolean;
  5265. begin
  5266. Result:=false;
  5267. { play save and throw an error if LEA uses a seg register prefix,
  5268. this is most likely an error somewhere else }
  5269. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5270. internalerror(2022022001);
  5271. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5272. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5273. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5274. (
  5275. { do not mess with leas accessing the stack pointer
  5276. unless it's a null operation }
  5277. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5278. (
  5279. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5280. (taicpu(p).oper[0]^.ref^.offset = 0)
  5281. )
  5282. ) and
  5283. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5284. begin
  5285. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5286. begin
  5287. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5288. begin
  5289. taicpu(p).opcode := A_MOV;
  5290. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5291. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5292. end
  5293. else
  5294. begin
  5295. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5296. RemoveCurrentP(p);
  5297. end;
  5298. Result:=true;
  5299. exit;
  5300. end
  5301. else if (
  5302. { continue to use lea to adjust the stack pointer,
  5303. it is the recommended way, but only if not optimizing for size }
  5304. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5305. (cs_opt_size in current_settings.optimizerswitches)
  5306. ) and
  5307. { If the flags register is in use, don't change the instruction
  5308. to an ADD otherwise this will scramble the flags. [Kit] }
  5309. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5310. ConvertLEA(taicpu(p)) then
  5311. begin
  5312. Result:=true;
  5313. exit;
  5314. end;
  5315. end;
  5316. { Don't optimise if the stack or frame pointer is the destination register }
  5317. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5318. Exit;
  5319. if GetNextInstruction(p,hp1) and
  5320. (hp1.typ=ait_instruction) then
  5321. begin
  5322. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5323. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5324. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5325. begin
  5326. TransferUsedRegs(TmpUsedRegs);
  5327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5328. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5329. begin
  5330. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5331. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5332. RemoveInstruction(hp1);
  5333. result:=true;
  5334. exit;
  5335. end;
  5336. end;
  5337. { changes
  5338. lea <ref1>, reg1
  5339. <op> ...,<ref. with reg1>,...
  5340. to
  5341. <op> ...,<ref1>,... }
  5342. { find a reference which uses reg1 }
  5343. 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
  5344. ref:=0
  5345. 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
  5346. ref:=1
  5347. else
  5348. ref:=-1;
  5349. if (ref<>-1) and
  5350. { reg1 must be either the base or the index }
  5351. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5352. begin
  5353. { reg1 can be removed from the reference }
  5354. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5355. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5356. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5357. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5358. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5359. else
  5360. Internalerror(2019111201);
  5361. { check if the can insert all data of the lea into the second instruction }
  5362. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5363. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5364. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5365. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5366. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5367. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5368. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5369. {$ifdef x86_64}
  5370. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5371. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5372. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5373. )
  5374. {$endif x86_64}
  5375. then
  5376. begin
  5377. { reg1 might not used by the second instruction after it is remove from the reference }
  5378. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5379. begin
  5380. TransferUsedRegs(TmpUsedRegs);
  5381. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5382. { reg1 is not updated so it might not be used afterwards }
  5383. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5384. begin
  5385. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5386. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5387. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5388. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5389. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5390. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5391. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5392. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5393. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5394. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5395. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5396. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5397. RemoveCurrentP(p, hp1);
  5398. result:=true;
  5399. exit;
  5400. end
  5401. end;
  5402. end;
  5403. { recover }
  5404. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5405. end;
  5406. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5407. if Adjacent or
  5408. { Check further ahead (up to 2 instructions ahead for -O2) }
  5409. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5410. begin
  5411. { Check common LEA/LEA conditions }
  5412. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5413. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5414. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5415. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5416. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5417. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5418. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5419. (
  5420. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5421. calling it (since it calls GetNextInstruction) }
  5422. Adjacent or
  5423. (
  5424. (
  5425. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5426. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5427. ) and (
  5428. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5429. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5430. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5431. )
  5432. )
  5433. ) then
  5434. begin
  5435. TransferUsedRegs(TmpUsedRegs);
  5436. hp2 := p;
  5437. repeat
  5438. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5439. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5440. IntermediateRegDiscarded :=
  5441. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5442. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5443. { changes
  5444. lea offset1(regX,scale), reg1
  5445. lea offset2(reg1,reg1), reg2
  5446. to
  5447. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5448. and
  5449. lea offset1(regX,scale1), reg1
  5450. lea offset2(reg1,scale2), reg2
  5451. to
  5452. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5453. and
  5454. lea offset1(regX,scale1), reg1
  5455. lea offset2(reg3,reg1,scale2), reg2
  5456. to
  5457. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5458. ... so long as the final scale does not exceed 8
  5459. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5460. }
  5461. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5462. (
  5463. { Don't optimise if size is a concern and the intermediate register remains in use }
  5464. IntermediateRegDiscarded or
  5465. not (cs_opt_size in current_settings.optimizerswitches)
  5466. ) and
  5467. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5468. (
  5469. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5470. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5471. ) and (
  5472. (
  5473. { lea (reg1,scale2), reg2 variant }
  5474. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5475. (
  5476. Adjacent or
  5477. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5478. ) and
  5479. (
  5480. (
  5481. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5482. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5483. ) or (
  5484. { lea (regX,regX), reg1 variant }
  5485. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5486. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5487. )
  5488. )
  5489. ) or (
  5490. { lea (reg1,reg1), reg1 variant }
  5491. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5492. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5493. )
  5494. ) then
  5495. begin
  5496. { Make everything homogeneous to make calculations easier }
  5497. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5498. begin
  5499. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5500. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5501. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5502. else
  5503. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5504. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5505. end;
  5506. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5507. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5508. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5509. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5510. begin
  5511. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5512. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5513. begin
  5514. { Put the register to change in the index register }
  5515. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5516. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5517. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5518. end;
  5519. if (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5520. begin
  5521. { Just to prevent miscalculations }
  5522. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5523. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5524. else
  5525. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5526. end
  5527. else
  5528. begin
  5529. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5530. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5531. end;
  5532. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5533. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(p).oper[0]^.ref^.scalefactor, 1));
  5534. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5535. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5536. if IntermediateRegDiscarded then
  5537. begin
  5538. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5539. RemoveCurrentP(p);
  5540. end
  5541. else
  5542. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5543. result:=true;
  5544. exit;
  5545. end;
  5546. end;
  5547. { changes
  5548. lea offset1(regX), reg1
  5549. lea offset2(reg1), reg2
  5550. to
  5551. lea offset1+offset2(regX), reg2 }
  5552. if (
  5553. { Don't optimise if size is a concern and the intermediate register remains in use }
  5554. IntermediateRegDiscarded or
  5555. not (cs_opt_size in current_settings.optimizerswitches)
  5556. ) and
  5557. (
  5558. (
  5559. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5560. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5561. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5562. ) or (
  5563. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5564. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5565. (
  5566. (
  5567. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5568. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5569. ) or (
  5570. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5571. (
  5572. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5573. (
  5574. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5575. (
  5576. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5577. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5578. )
  5579. )
  5580. )
  5581. )
  5582. )
  5583. )
  5584. ) then
  5585. begin
  5586. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5587. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5588. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5589. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5590. begin
  5591. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5592. begin
  5593. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5594. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5595. { if the register is used as index and base, we have to increase for base as well
  5596. and adapt base }
  5597. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5598. begin
  5599. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5600. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5601. end;
  5602. end
  5603. else
  5604. begin
  5605. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5606. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5607. end;
  5608. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5609. begin
  5610. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5611. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5612. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5613. end;
  5614. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5615. if IntermediateRegDiscarded then
  5616. begin
  5617. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5618. RemoveCurrentP(p);
  5619. end
  5620. else
  5621. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5622. result:=true;
  5623. exit;
  5624. end;
  5625. end;
  5626. end;
  5627. { Change:
  5628. leal/q $x(%reg1),%reg2
  5629. ...
  5630. shll/q $y,%reg2
  5631. To:
  5632. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5633. }
  5634. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5635. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5636. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5637. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5638. (taicpu(hp1).oper[0]^.val <= 3) then
  5639. begin
  5640. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5641. TransferUsedRegs(TmpUsedRegs);
  5642. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5643. if
  5644. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5645. (this works even if scalefactor is zero) }
  5646. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5647. { Ensure offset doesn't go out of bounds }
  5648. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5649. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5650. (
  5651. (
  5652. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5653. (
  5654. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5655. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5656. (
  5657. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5658. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5659. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5660. )
  5661. )
  5662. ) or (
  5663. (
  5664. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5665. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5666. ) and
  5667. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5668. )
  5669. ) then
  5670. begin
  5671. repeat
  5672. with taicpu(p).oper[0]^.ref^ do
  5673. begin
  5674. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5675. if index = base then
  5676. begin
  5677. if Multiple > 4 then
  5678. { Optimisation will no longer work because resultant
  5679. scale factor will exceed 8 }
  5680. Break;
  5681. base := NR_NO;
  5682. scalefactor := 2;
  5683. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5684. end
  5685. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5686. begin
  5687. { Scale factor only works on the index register }
  5688. index := base;
  5689. base := NR_NO;
  5690. end;
  5691. { For safety }
  5692. if scalefactor <= 1 then
  5693. begin
  5694. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5695. scalefactor := Multiple;
  5696. end
  5697. else
  5698. begin
  5699. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5700. scalefactor := scalefactor * Multiple;
  5701. end;
  5702. offset := offset * Multiple;
  5703. end;
  5704. RemoveInstruction(hp1);
  5705. Result := True;
  5706. Exit;
  5707. { This repeat..until loop exists for the benefit of Break }
  5708. until True;
  5709. end;
  5710. end;
  5711. end;
  5712. end;
  5713. end;
  5714. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5715. var
  5716. hp1 : tai;
  5717. SubInstr: Boolean;
  5718. ThisConst: TCGInt;
  5719. const
  5720. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5721. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5722. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5723. begin
  5724. Result := False;
  5725. if taicpu(p).oper[0]^.typ <> top_const then
  5726. { Should have been confirmed before calling }
  5727. InternalError(2021102601);
  5728. SubInstr := (taicpu(p).opcode = A_SUB);
  5729. if GetLastInstruction(p, hp1) and
  5730. (hp1.typ = ait_instruction) and
  5731. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5732. begin
  5733. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5734. { Bad size }
  5735. InternalError(2022042001);
  5736. case taicpu(hp1).opcode Of
  5737. A_INC:
  5738. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5739. begin
  5740. if SubInstr then
  5741. ThisConst := taicpu(p).oper[0]^.val - 1
  5742. else
  5743. ThisConst := taicpu(p).oper[0]^.val + 1;
  5744. end
  5745. else
  5746. Exit;
  5747. A_DEC:
  5748. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5749. begin
  5750. if SubInstr then
  5751. ThisConst := taicpu(p).oper[0]^.val + 1
  5752. else
  5753. ThisConst := taicpu(p).oper[0]^.val - 1;
  5754. end
  5755. else
  5756. Exit;
  5757. A_SUB:
  5758. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5759. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5760. begin
  5761. if SubInstr then
  5762. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5763. else
  5764. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5765. end
  5766. else
  5767. Exit;
  5768. A_ADD:
  5769. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5770. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5771. begin
  5772. if SubInstr then
  5773. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5774. else
  5775. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5776. end
  5777. else
  5778. Exit;
  5779. else
  5780. Exit;
  5781. end;
  5782. { Check that the values are in range }
  5783. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5784. { Overflow; abort }
  5785. Exit;
  5786. if (ThisConst = 0) then
  5787. begin
  5788. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5789. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5790. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5791. RemoveInstruction(hp1);
  5792. hp1 := tai(p.next);
  5793. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5794. if not GetLastInstruction(hp1, p) then
  5795. p := hp1;
  5796. end
  5797. else
  5798. begin
  5799. if taicpu(hp1).opercnt=1 then
  5800. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5801. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5802. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5803. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5804. else
  5805. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5806. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5807. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5808. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5809. RemoveInstruction(hp1);
  5810. taicpu(p).loadconst(0, ThisConst);
  5811. end;
  5812. Result := True;
  5813. end;
  5814. end;
  5815. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5816. begin
  5817. Result := False;
  5818. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5819. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5820. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5821. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5822. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5823. (
  5824. (
  5825. (taicpu(hp1).opcode = A_TEST)
  5826. ) or (
  5827. (taicpu(hp1).opcode = A_CMP) and
  5828. { A sanity check more than anything }
  5829. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5830. )
  5831. ) then
  5832. begin
  5833. { change
  5834. mov mem, %reg
  5835. ...
  5836. cmp/test x, %reg / test %reg,%reg
  5837. (reg deallocated)
  5838. to
  5839. cmp/test x, mem / cmp 0, mem
  5840. }
  5841. TransferUsedRegs(TmpUsedRegs);
  5842. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5843. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5844. begin
  5845. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5846. if (taicpu(hp1).opcode = A_TEST) and
  5847. (
  5848. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5849. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5850. ) then
  5851. begin
  5852. taicpu(hp1).opcode := A_CMP;
  5853. taicpu(hp1).loadconst(0, 0);
  5854. end;
  5855. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5856. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5857. RemoveCurrentP(p);
  5858. if (p <> hp1) then
  5859. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5860. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5861. { Make sure the flags are allocated across the CMP instruction }
  5862. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5863. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5864. Result := True;
  5865. Exit;
  5866. end;
  5867. end;
  5868. end;
  5869. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5870. var
  5871. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5872. ThisReg, SecondReg: TRegister;
  5873. JumpLoc: TAsmLabel;
  5874. NewSize: TOpSize;
  5875. begin
  5876. Result := False;
  5877. {
  5878. Convert:
  5879. j<c> .L1
  5880. .L2:
  5881. mov 1,reg
  5882. jmp .L3 (or ret, although it might not be a RET yet)
  5883. .L1:
  5884. mov 0,reg
  5885. jmp .L3 (or ret)
  5886. ( As long as .L3 <> .L1 or .L2)
  5887. To:
  5888. mov 0,reg
  5889. set<not(c)> reg
  5890. jmp .L3 (or ret)
  5891. .L2:
  5892. mov 1,reg
  5893. jmp .L3 (or ret)
  5894. .L1:
  5895. mov 0,reg
  5896. jmp .L3 (or ret)
  5897. }
  5898. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5899. Exit;
  5900. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5901. if GetNextInstruction(hp_label, hp2) and
  5902. MatchInstruction(hp2,A_MOV,[]) and
  5903. (taicpu(hp2).oper[0]^.typ = top_const) and
  5904. (
  5905. (
  5906. (taicpu(hp2).oper[1]^.typ = top_reg)
  5907. {$ifdef i386}
  5908. { Under i386, ESI, EDI, EBP and ESP
  5909. don't have an 8-bit representation }
  5910. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5911. {$endif i386}
  5912. ) or (
  5913. {$ifdef i386}
  5914. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5915. {$endif i386}
  5916. (taicpu(hp2).opsize = S_B)
  5917. )
  5918. ) and
  5919. GetNextInstruction(hp2, hp3) and
  5920. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5921. (
  5922. (taicpu(hp3).opcode=A_RET) or
  5923. (
  5924. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5925. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5926. )
  5927. ) and
  5928. GetNextInstruction(hp3, hp4) and
  5929. SkipAligns(hp4, hp4) and
  5930. (hp4.typ=ait_label) and
  5931. (tai_label(hp4).labsym=JumpLoc) and
  5932. (
  5933. not (cs_opt_size in current_settings.optimizerswitches) or
  5934. { If the initial jump is the label's only reference, then it will
  5935. become a dead label if the other conditions are met and hence
  5936. remove at least 2 instructions, including a jump }
  5937. (JumpLoc.getrefs = 1)
  5938. ) and
  5939. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5940. that will be optimised out }
  5941. GetNextInstruction(hp4, hp5) and
  5942. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5943. (taicpu(hp5).oper[0]^.typ = top_const) and
  5944. (
  5945. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5946. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5947. ) and
  5948. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5949. GetNextInstruction(hp5,hp6) and
  5950. (
  5951. (hp6.typ<>ait_label) or
  5952. SkipLabels(hp6, hp6)
  5953. ) and
  5954. (hp6.typ=ait_instruction) then
  5955. begin
  5956. { First, let's look at the two jumps that are hp3 and hp6 }
  5957. if not
  5958. (
  5959. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5960. (
  5961. (taicpu(hp6).opcode=A_RET) or
  5962. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5963. )
  5964. ) then
  5965. { If condition is False, then the JMP/RET instructions matched conventionally }
  5966. begin
  5967. { See if one of the jumps can be instantly converted into a RET }
  5968. if (taicpu(hp3).opcode=A_JMP) then
  5969. begin
  5970. { Reuse hp5 }
  5971. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5972. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5973. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5974. Exit;
  5975. if MatchInstruction(hp5, A_RET, []) then
  5976. begin
  5977. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5978. ConvertJumpToRET(hp3, hp5);
  5979. Result := True;
  5980. end
  5981. else
  5982. Exit;
  5983. end;
  5984. if (taicpu(hp6).opcode=A_JMP) then
  5985. begin
  5986. { Reuse hp5 }
  5987. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5988. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5989. Exit;
  5990. if MatchInstruction(hp5, A_RET, []) then
  5991. begin
  5992. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5993. ConvertJumpToRET(hp6, hp5);
  5994. Result := True;
  5995. end
  5996. else
  5997. Exit;
  5998. end;
  5999. if not
  6000. (
  6001. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6002. (
  6003. (taicpu(hp6).opcode=A_RET) or
  6004. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6005. )
  6006. ) then
  6007. { Still doesn't match }
  6008. Exit;
  6009. end;
  6010. if (taicpu(hp2).oper[0]^.val = 1) then
  6011. begin
  6012. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6013. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6014. end
  6015. else
  6016. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6017. if taicpu(hp2).opsize=S_B then
  6018. begin
  6019. if taicpu(hp2).oper[1]^.typ = top_reg then
  6020. begin
  6021. SecondReg := taicpu(hp2).oper[1]^.reg;
  6022. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6023. end
  6024. else
  6025. begin
  6026. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6027. SecondReg := NR_NO;
  6028. end;
  6029. hp_pos := p;
  6030. hp_allocstart := hp4;
  6031. end
  6032. else
  6033. begin
  6034. { Will be a register because the size can't be S_B otherwise }
  6035. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6036. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6037. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6038. if (cs_opt_size in current_settings.optimizerswitches) then
  6039. begin
  6040. { Favour using MOVZX when optimising for size }
  6041. case taicpu(hp2).opsize of
  6042. S_W:
  6043. NewSize := S_BW;
  6044. S_L:
  6045. NewSize := S_BL;
  6046. {$ifdef x86_64}
  6047. S_Q:
  6048. begin
  6049. NewSize := S_BL;
  6050. { Will implicitly zero-extend to 64-bit }
  6051. setsubreg(SecondReg, R_SUBD);
  6052. end;
  6053. {$endif x86_64}
  6054. else
  6055. InternalError(2022101301);
  6056. end;
  6057. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6058. { Inserting it right before p will guarantee that the flags are also tracked }
  6059. Asml.InsertBefore(hp5, p);
  6060. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6061. hp_pos := hp5;
  6062. hp_allocstart := hp4;
  6063. end
  6064. else
  6065. begin
  6066. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6067. { Inserting it right before p will guarantee that the flags are also tracked }
  6068. Asml.InsertBefore(hp5, p);
  6069. hp_pos := p;
  6070. hp_allocstart := hp5;
  6071. end;
  6072. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6073. end;
  6074. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6075. taicpu(hp4).condition := taicpu(p).condition;
  6076. asml.InsertBefore(hp4, hp_pos);
  6077. if taicpu(hp3).is_jmp then
  6078. begin
  6079. JumpLoc.decrefs;
  6080. MakeUnconditional(taicpu(p));
  6081. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6082. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6083. end
  6084. else
  6085. ConvertJumpToRET(p, hp3);
  6086. if SecondReg <> NR_NO then
  6087. { Ensure the destination register is allocated over this region }
  6088. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6089. if (JumpLoc.getrefs = 0) then
  6090. RemoveDeadCodeAfterJump(hp3);
  6091. Result:=true;
  6092. exit;
  6093. end;
  6094. end;
  6095. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6096. var
  6097. hp1, hp2: tai;
  6098. ActiveReg: TRegister;
  6099. OldOffset: asizeint;
  6100. ThisConst: TCGInt;
  6101. function RegDeallocated: Boolean;
  6102. begin
  6103. TransferUsedRegs(TmpUsedRegs);
  6104. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6105. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6106. end;
  6107. begin
  6108. Result:=false;
  6109. hp1 := nil;
  6110. { replace
  6111. subX const,%reg1
  6112. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6113. dealloc %reg1
  6114. by
  6115. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6116. }
  6117. if MatchOpType(taicpu(p),top_const,top_reg) then
  6118. begin
  6119. ActiveReg := taicpu(p).oper[1]^.reg;
  6120. { Ensures the entire register was updated }
  6121. if (taicpu(p).opsize >= S_L) and
  6122. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6123. MatchInstruction(hp1,A_LEA,[]) and
  6124. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6125. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6126. (
  6127. { Cover the case where the register in the reference is also the destination register }
  6128. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6129. (
  6130. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6131. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6132. RegDeallocated
  6133. )
  6134. ) then
  6135. begin
  6136. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6137. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6138. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6139. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6140. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6141. {$ifdef x86_64}
  6142. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6143. begin
  6144. { Overflow; abort }
  6145. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6146. end
  6147. else
  6148. {$endif x86_64}
  6149. begin
  6150. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6151. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6152. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6153. RemoveCurrentP(p, hp1)
  6154. else
  6155. RemoveCurrentP(p);
  6156. result:=true;
  6157. Exit;
  6158. end;
  6159. end;
  6160. if (
  6161. { Save calling GetNextInstructionUsingReg again }
  6162. Assigned(hp1) or
  6163. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6164. ) and
  6165. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6166. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6167. begin
  6168. if taicpu(hp1).oper[0]^.typ = top_const then
  6169. begin
  6170. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6171. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6172. Result := True;
  6173. { Handle any overflows }
  6174. case taicpu(p).opsize of
  6175. S_B:
  6176. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6177. S_W:
  6178. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6179. S_L:
  6180. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6181. {$ifdef x86_64}
  6182. S_Q:
  6183. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6184. { Overflow; abort }
  6185. Result := False
  6186. else
  6187. taicpu(p).oper[0]^.val := ThisConst;
  6188. {$endif x86_64}
  6189. else
  6190. InternalError(2021102611);
  6191. end;
  6192. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6193. if Result then
  6194. begin
  6195. if (taicpu(p).oper[0]^.val < 0) and
  6196. (
  6197. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6198. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6199. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6200. ) then
  6201. begin
  6202. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6203. taicpu(p).opcode := A_SUB;
  6204. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6205. end
  6206. else
  6207. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6208. RemoveInstruction(hp1);
  6209. end;
  6210. end
  6211. else
  6212. begin
  6213. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6214. TransferUsedRegs(TmpUsedRegs);
  6215. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6216. hp2 := p;
  6217. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6218. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6219. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6220. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6221. begin
  6222. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6223. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6224. Asml.Remove(p);
  6225. Asml.InsertAfter(p, hp1);
  6226. p := hp1;
  6227. Result := True;
  6228. Exit;
  6229. end;
  6230. end;
  6231. end;
  6232. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6233. { * change "sub/add const1, reg" or "dec reg" followed by
  6234. "sub const2, reg" to one "sub ..., reg" }
  6235. {$ifdef i386}
  6236. if (taicpu(p).oper[0]^.val = 2) and
  6237. (ActiveReg = NR_ESP) and
  6238. { Don't do the sub/push optimization if the sub }
  6239. { comes from setting up the stack frame (JM) }
  6240. (not(GetLastInstruction(p,hp1)) or
  6241. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6242. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6243. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6244. begin
  6245. hp1 := tai(p.next);
  6246. while Assigned(hp1) and
  6247. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6248. not RegReadByInstruction(NR_ESP,hp1) and
  6249. not RegModifiedByInstruction(NR_ESP,hp1) do
  6250. hp1 := tai(hp1.next);
  6251. if Assigned(hp1) and
  6252. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6253. begin
  6254. taicpu(hp1).changeopsize(S_L);
  6255. if taicpu(hp1).oper[0]^.typ=top_reg then
  6256. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6257. hp1 := tai(p.next);
  6258. RemoveCurrentp(p, hp1);
  6259. Result:=true;
  6260. exit;
  6261. end;
  6262. end;
  6263. {$endif i386}
  6264. if DoArithCombineOpt(p) then
  6265. Result:=true;
  6266. end;
  6267. end;
  6268. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6269. var
  6270. TmpBool1,TmpBool2 : Boolean;
  6271. tmpref : treference;
  6272. hp1,hp2: tai;
  6273. mask, shiftval: tcgint;
  6274. begin
  6275. Result:=false;
  6276. { All these optimisations work on "shl/sal const,%reg" }
  6277. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6278. Exit;
  6279. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6280. (taicpu(p).oper[0]^.val <= 3) then
  6281. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6282. begin
  6283. { should we check the next instruction? }
  6284. TmpBool1 := True;
  6285. { have we found an add/sub which could be
  6286. integrated in the lea? }
  6287. TmpBool2 := False;
  6288. reference_reset(tmpref,2,[]);
  6289. TmpRef.index := taicpu(p).oper[1]^.reg;
  6290. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6291. while TmpBool1 and
  6292. GetNextInstruction(p, hp1) and
  6293. (tai(hp1).typ = ait_instruction) and
  6294. ((((taicpu(hp1).opcode = A_ADD) or
  6295. (taicpu(hp1).opcode = A_SUB)) and
  6296. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6297. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6298. (((taicpu(hp1).opcode = A_INC) or
  6299. (taicpu(hp1).opcode = A_DEC)) and
  6300. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6301. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6302. ((taicpu(hp1).opcode = A_LEA) and
  6303. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6304. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6305. (not GetNextInstruction(hp1,hp2) or
  6306. not instrReadsFlags(hp2)) Do
  6307. begin
  6308. TmpBool1 := False;
  6309. if taicpu(hp1).opcode=A_LEA then
  6310. begin
  6311. if (TmpRef.base = NR_NO) and
  6312. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6313. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6314. { Segment register isn't a concern here }
  6315. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6316. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6317. begin
  6318. TmpBool1 := True;
  6319. TmpBool2 := True;
  6320. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6321. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6322. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6323. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6324. RemoveInstruction(hp1);
  6325. end
  6326. end
  6327. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6328. begin
  6329. TmpBool1 := True;
  6330. TmpBool2 := True;
  6331. case taicpu(hp1).opcode of
  6332. A_ADD:
  6333. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6334. A_SUB:
  6335. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6336. else
  6337. internalerror(2019050536);
  6338. end;
  6339. RemoveInstruction(hp1);
  6340. end
  6341. else
  6342. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6343. (((taicpu(hp1).opcode = A_ADD) and
  6344. (TmpRef.base = NR_NO)) or
  6345. (taicpu(hp1).opcode = A_INC) or
  6346. (taicpu(hp1).opcode = A_DEC)) then
  6347. begin
  6348. TmpBool1 := True;
  6349. TmpBool2 := True;
  6350. case taicpu(hp1).opcode of
  6351. A_ADD:
  6352. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6353. A_INC:
  6354. inc(TmpRef.offset);
  6355. A_DEC:
  6356. dec(TmpRef.offset);
  6357. else
  6358. internalerror(2019050535);
  6359. end;
  6360. RemoveInstruction(hp1);
  6361. end;
  6362. end;
  6363. if TmpBool2
  6364. {$ifndef x86_64}
  6365. or
  6366. ((current_settings.optimizecputype < cpu_Pentium2) and
  6367. (taicpu(p).oper[0]^.val <= 3) and
  6368. not(cs_opt_size in current_settings.optimizerswitches))
  6369. {$endif x86_64}
  6370. then
  6371. begin
  6372. if not(TmpBool2) and
  6373. (taicpu(p).oper[0]^.val=1) then
  6374. begin
  6375. taicpu(p).opcode := A_ADD;
  6376. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6377. end
  6378. else
  6379. begin
  6380. taicpu(p).opcode := A_LEA;
  6381. taicpu(p).loadref(0, TmpRef);
  6382. end;
  6383. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6384. Result := True;
  6385. end;
  6386. end
  6387. {$ifndef x86_64}
  6388. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6389. begin
  6390. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6391. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6392. (unlike shl, which is only Tairable in the U pipe) }
  6393. if taicpu(p).oper[0]^.val=1 then
  6394. begin
  6395. taicpu(p).opcode := A_ADD;
  6396. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6397. Result := True;
  6398. end
  6399. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6400. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6401. else if (taicpu(p).opsize = S_L) and
  6402. (taicpu(p).oper[0]^.val<= 3) then
  6403. begin
  6404. reference_reset(tmpref,2,[]);
  6405. TmpRef.index := taicpu(p).oper[1]^.reg;
  6406. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6407. taicpu(p).opcode := A_LEA;
  6408. taicpu(p).loadref(0, TmpRef);
  6409. Result := True;
  6410. end;
  6411. end
  6412. {$endif x86_64}
  6413. else if
  6414. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6415. (
  6416. (
  6417. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6418. SetAndTest(hp1, hp2)
  6419. {$ifdef x86_64}
  6420. ) or
  6421. (
  6422. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6423. GetNextInstruction(hp1, hp2) and
  6424. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6425. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6426. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6427. {$endif x86_64}
  6428. )
  6429. ) and
  6430. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6431. begin
  6432. { Change:
  6433. shl x, %reg1
  6434. mov -(1<<x), %reg2
  6435. and %reg2, %reg1
  6436. Or:
  6437. shl x, %reg1
  6438. and -(1<<x), %reg1
  6439. To just:
  6440. shl x, %reg1
  6441. Since the and operation only zeroes bits that are already zero from the shl operation
  6442. }
  6443. case taicpu(p).oper[0]^.val of
  6444. 8:
  6445. mask:=$FFFFFFFFFFFFFF00;
  6446. 16:
  6447. mask:=$FFFFFFFFFFFF0000;
  6448. 32:
  6449. mask:=$FFFFFFFF00000000;
  6450. 63:
  6451. { Constant pre-calculated to prevent overflow errors with Int64 }
  6452. mask:=$8000000000000000;
  6453. else
  6454. begin
  6455. if taicpu(p).oper[0]^.val >= 64 then
  6456. { Shouldn't happen realistically, since the register
  6457. is guaranteed to be set to zero at this point }
  6458. mask := 0
  6459. else
  6460. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6461. end;
  6462. end;
  6463. if taicpu(hp1).oper[0]^.val = mask then
  6464. begin
  6465. { Everything checks out, perform the optimisation, as long as
  6466. the FLAGS register isn't being used}
  6467. TransferUsedRegs(TmpUsedRegs);
  6468. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6469. {$ifdef x86_64}
  6470. if (hp1 <> hp2) then
  6471. begin
  6472. { "shl/mov/and" version }
  6473. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6474. { Don't do the optimisation if the FLAGS register is in use }
  6475. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6476. begin
  6477. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6478. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6479. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6480. begin
  6481. RemoveInstruction(hp1);
  6482. Result := True;
  6483. end;
  6484. { Only set Result to True if the 'mov' instruction was removed }
  6485. RemoveInstruction(hp2);
  6486. end;
  6487. end
  6488. else
  6489. {$endif x86_64}
  6490. begin
  6491. { "shl/and" version }
  6492. { Don't do the optimisation if the FLAGS register is in use }
  6493. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6494. begin
  6495. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6496. RemoveInstruction(hp1);
  6497. Result := True;
  6498. end;
  6499. end;
  6500. Exit;
  6501. end
  6502. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6503. begin
  6504. { Even if the mask doesn't allow for its removal, we might be
  6505. able to optimise the mask for the "shl/and" version, which
  6506. may permit other peephole optimisations }
  6507. {$ifdef DEBUG_AOPTCPU}
  6508. mask := taicpu(hp1).oper[0]^.val and mask;
  6509. if taicpu(hp1).oper[0]^.val <> mask then
  6510. begin
  6511. DebugMsg(
  6512. SPeepholeOptimization +
  6513. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6514. ' to $' + debug_tostr(mask) +
  6515. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6516. taicpu(hp1).oper[0]^.val := mask;
  6517. end;
  6518. {$else DEBUG_AOPTCPU}
  6519. { If debugging is off, just set the operand even if it's the same }
  6520. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6521. {$endif DEBUG_AOPTCPU}
  6522. end;
  6523. end;
  6524. {
  6525. change
  6526. shl/sal const,reg
  6527. <op> ...(...,reg,1),...
  6528. into
  6529. <op> ...(...,reg,1 shl const),...
  6530. if const in 1..3
  6531. }
  6532. if MatchOpType(taicpu(p), top_const, top_reg) and
  6533. (taicpu(p).oper[0]^.val in [1..3]) and
  6534. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6535. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6536. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6537. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6538. MatchOpType(taicpu(hp1),top_ref))
  6539. ) and
  6540. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6541. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6542. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6543. begin
  6544. TransferUsedRegs(TmpUsedRegs);
  6545. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6546. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6547. begin
  6548. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6549. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6550. RemoveCurrentP(p);
  6551. Result:=true;
  6552. exit;
  6553. end;
  6554. end;
  6555. if MatchOpType(taicpu(p), top_const, top_reg) and
  6556. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6557. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6558. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6559. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6560. begin
  6561. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6562. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6563. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6564. {$ifdef x86_64}
  6565. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6566. {$endif x86_64}
  6567. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6568. begin
  6569. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6570. taicpu(hp1).opcode:=A_MOV;
  6571. taicpu(hp1).oper[0]^.val:=0;
  6572. end
  6573. else
  6574. begin
  6575. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6576. taicpu(hp1).oper[0]^.val:=shiftval;
  6577. end;
  6578. RemoveCurrentP(p);
  6579. Result:=true;
  6580. exit;
  6581. end;
  6582. end;
  6583. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6584. begin
  6585. case shr_size of
  6586. S_B:
  6587. { No valid combinations }
  6588. Result := False;
  6589. S_W:
  6590. Result := (Shift >= 8) and (movz_size = S_BW);
  6591. S_L:
  6592. Result :=
  6593. (Shift >= 24) { Any opsize is valid for this shift } or
  6594. ((Shift >= 16) and (movz_size = S_WL));
  6595. {$ifdef x86_64}
  6596. S_Q:
  6597. Result :=
  6598. (Shift >= 56) { Any opsize is valid for this shift } or
  6599. ((Shift >= 48) and (movz_size = S_WL));
  6600. {$endif x86_64}
  6601. else
  6602. InternalError(2022081510);
  6603. end;
  6604. end;
  6605. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6606. var
  6607. hp1, hp2: tai;
  6608. Shift: TCGInt;
  6609. LimitSize: Topsize;
  6610. DoNotMerge: Boolean;
  6611. begin
  6612. Result := False;
  6613. { All these optimisations work on "shr const,%reg" }
  6614. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6615. Exit;
  6616. DoNotMerge := False;
  6617. Shift := taicpu(p).oper[0]^.val;
  6618. LimitSize := taicpu(p).opsize;
  6619. hp1 := p;
  6620. repeat
  6621. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6622. Exit;
  6623. case taicpu(hp1).opcode of
  6624. A_TEST, A_CMP, A_Jcc:
  6625. { Skip over conditional jumps and relevant comparisons }
  6626. Continue;
  6627. A_MOVZX:
  6628. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6629. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6630. begin
  6631. { Since the original register is being read as is, subsequent
  6632. SHRs must not be merged at this point }
  6633. DoNotMerge := True;
  6634. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6635. begin
  6636. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6637. begin
  6638. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6639. taicpu(hp1).opcode := A_MOV;
  6640. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6641. case taicpu(hp1).opsize of
  6642. S_BW:
  6643. taicpu(hp1).opsize := S_W;
  6644. S_BL, S_WL:
  6645. taicpu(hp1).opsize := S_L;
  6646. else
  6647. InternalError(2022081503);
  6648. end;
  6649. { p itself hasn't changed, so no need to set Result to True }
  6650. Include(OptsToCheck, aoc_ForceNewIteration);
  6651. { See if there's anything afterwards that can be
  6652. optimised, since the input register hasn't changed }
  6653. Continue;
  6654. end;
  6655. { NOTE: If the MOVZX instruction reads and writes the same
  6656. register, defer this to the post-peephole optimisation stage }
  6657. Exit;
  6658. end;
  6659. end;
  6660. A_SHL, A_SAL, A_SHR:
  6661. if (taicpu(hp1).opsize <= LimitSize) and
  6662. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6663. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6664. begin
  6665. { Make sure the sizes don't exceed the register size limit
  6666. (measured by the shift value falling below the limit) }
  6667. if taicpu(hp1).opsize < LimitSize then
  6668. LimitSize := taicpu(hp1).opsize;
  6669. if taicpu(hp1).opcode = A_SHR then
  6670. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6671. else
  6672. begin
  6673. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6674. DoNotMerge := True;
  6675. end;
  6676. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6677. Exit;
  6678. { Since we've established that the combined shift is within
  6679. limits, we can actually combine the adjacent SHR
  6680. instructions even if they're different sizes }
  6681. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6682. begin
  6683. hp2 := tai(hp1.Previous);
  6684. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6685. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6686. RemoveInstruction(hp1);
  6687. hp1 := hp2;
  6688. { Though p has changed, only the constant has, and its
  6689. effects can still be detected on the next iteration of
  6690. the repeat..until loop }
  6691. Include(OptsToCheck, aoc_ForceNewIteration);
  6692. end;
  6693. { Move onto the next instruction }
  6694. Continue;
  6695. end;
  6696. else
  6697. ;
  6698. end;
  6699. Break;
  6700. until False;
  6701. end;
  6702. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6703. var
  6704. CurrentRef: TReference;
  6705. FullReg: TRegister;
  6706. hp1, hp2: tai;
  6707. begin
  6708. Result := False;
  6709. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6710. Exit;
  6711. { We assume you've checked if the operand is actually a reference by
  6712. this point. If it isn't, you'll most likely get an access violation }
  6713. CurrentRef := first_mov.oper[1]^.ref^;
  6714. { Memory must be aligned }
  6715. if (CurrentRef.offset mod 4) <> 0 then
  6716. Exit;
  6717. Inc(CurrentRef.offset);
  6718. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6719. if MatchOperand(second_mov.oper[0]^, 0) and
  6720. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6721. GetNextInstruction(second_mov, hp1) and
  6722. (hp1.typ = ait_instruction) and
  6723. (taicpu(hp1).opcode = A_MOV) and
  6724. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6725. (taicpu(hp1).oper[0]^.val = 0) then
  6726. begin
  6727. Inc(CurrentRef.offset);
  6728. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6729. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6730. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6731. begin
  6732. case taicpu(hp1).opsize of
  6733. S_B:
  6734. if GetNextInstruction(hp1, hp2) and
  6735. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6736. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6737. (taicpu(hp2).oper[0]^.val = 0) then
  6738. begin
  6739. Inc(CurrentRef.offset);
  6740. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6741. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6742. (taicpu(hp2).opsize = S_B) then
  6743. begin
  6744. RemoveInstruction(hp1);
  6745. RemoveInstruction(hp2);
  6746. first_mov.opsize := S_L;
  6747. if first_mov.oper[0]^.typ = top_reg then
  6748. begin
  6749. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6750. { Reuse second_mov as a MOVZX instruction }
  6751. second_mov.opcode := A_MOVZX;
  6752. second_mov.opsize := S_BL;
  6753. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6754. second_mov.loadreg(1, FullReg);
  6755. first_mov.oper[0]^.reg := FullReg;
  6756. asml.Remove(second_mov);
  6757. asml.InsertBefore(second_mov, first_mov);
  6758. end
  6759. else
  6760. { It's a value }
  6761. begin
  6762. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6763. RemoveInstruction(second_mov);
  6764. end;
  6765. Result := True;
  6766. Exit;
  6767. end;
  6768. end;
  6769. S_W:
  6770. begin
  6771. RemoveInstruction(hp1);
  6772. first_mov.opsize := S_L;
  6773. if first_mov.oper[0]^.typ = top_reg then
  6774. begin
  6775. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6776. { Reuse second_mov as a MOVZX instruction }
  6777. second_mov.opcode := A_MOVZX;
  6778. second_mov.opsize := S_BL;
  6779. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6780. second_mov.loadreg(1, FullReg);
  6781. first_mov.oper[0]^.reg := FullReg;
  6782. asml.Remove(second_mov);
  6783. asml.InsertBefore(second_mov, first_mov);
  6784. end
  6785. else
  6786. { It's a value }
  6787. begin
  6788. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6789. RemoveInstruction(second_mov);
  6790. end;
  6791. Result := True;
  6792. Exit;
  6793. end;
  6794. else
  6795. ;
  6796. end;
  6797. end;
  6798. end;
  6799. end;
  6800. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6801. { returns true if a "continue" should be done after this optimization }
  6802. var
  6803. hp1, hp2, hp3: tai;
  6804. begin
  6805. Result := false;
  6806. hp3 := nil;
  6807. if MatchOpType(taicpu(p),top_ref) and
  6808. GetNextInstruction(p, hp1) and
  6809. (hp1.typ = ait_instruction) and
  6810. (((taicpu(hp1).opcode = A_FLD) and
  6811. (taicpu(p).opcode = A_FSTP)) or
  6812. ((taicpu(p).opcode = A_FISTP) and
  6813. (taicpu(hp1).opcode = A_FILD))) and
  6814. MatchOpType(taicpu(hp1),top_ref) and
  6815. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6816. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6817. begin
  6818. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6819. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6820. GetNextInstruction(hp1, hp2) and
  6821. (((hp2.typ = ait_instruction) and
  6822. IsExitCode(hp2) and
  6823. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6824. not(assigned(current_procinfo.procdef.funcretsym) and
  6825. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6826. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6827. { fstp <temp>
  6828. fld <temp>
  6829. <dealloc> <temp>
  6830. }
  6831. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6832. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6833. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6834. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6835. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6836. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6837. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6838. )
  6839. )
  6840. ) then
  6841. begin
  6842. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6843. RemoveInstruction(hp1);
  6844. RemoveCurrentP(p, hp2);
  6845. { first case: exit code }
  6846. if hp2.typ = ait_instruction then
  6847. RemoveLastDeallocForFuncRes(p);
  6848. Result := true;
  6849. end
  6850. else
  6851. { we can do this only in fast math mode as fstp is rounding ...
  6852. ... still disabled as it breaks the compiler and/or rtl }
  6853. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6854. { ... or if another fstp equal to the first one follows }
  6855. GetNextInstruction(hp1,hp2) and
  6856. (hp2.typ = ait_instruction) and
  6857. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6858. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6859. begin
  6860. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6861. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6862. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6863. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6864. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6865. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6866. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6867. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6868. ) then
  6869. begin
  6870. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6871. RemoveCurrentP(p,hp2);
  6872. RemoveInstruction(hp1);
  6873. Result := true;
  6874. end
  6875. else if { fst can't store an extended/comp value }
  6876. (taicpu(p).opsize <> S_FX) and
  6877. (taicpu(p).opsize <> S_IQ) then
  6878. begin
  6879. if (taicpu(p).opcode = A_FSTP) then
  6880. taicpu(p).opcode := A_FST
  6881. else
  6882. taicpu(p).opcode := A_FIST;
  6883. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6884. RemoveInstruction(hp1);
  6885. Result := true;
  6886. end;
  6887. end;
  6888. end;
  6889. end;
  6890. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6891. var
  6892. hp1, hp2, hp3: tai;
  6893. begin
  6894. result:=false;
  6895. if MatchOpType(taicpu(p),top_reg) and
  6896. GetNextInstruction(p, hp1) and
  6897. (hp1.typ = Ait_Instruction) and
  6898. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6899. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6900. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6901. { change to
  6902. fld reg fxxx reg,st
  6903. fxxxp st, st1 (hp1)
  6904. Remark: non commutative operations must be reversed!
  6905. }
  6906. begin
  6907. case taicpu(hp1).opcode Of
  6908. A_FMULP,A_FADDP,
  6909. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6910. begin
  6911. case taicpu(hp1).opcode Of
  6912. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6913. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6914. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6915. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6916. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6917. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6918. else
  6919. internalerror(2019050534);
  6920. end;
  6921. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6922. taicpu(hp1).oper[1]^.reg := NR_ST;
  6923. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6924. RemoveCurrentP(p, hp1);
  6925. Result:=true;
  6926. exit;
  6927. end;
  6928. else
  6929. ;
  6930. end;
  6931. end
  6932. else
  6933. if MatchOpType(taicpu(p),top_ref) and
  6934. GetNextInstruction(p, hp2) and
  6935. (hp2.typ = Ait_Instruction) and
  6936. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6937. (taicpu(p).opsize in [S_FS, S_FL]) and
  6938. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6939. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6940. if GetLastInstruction(p, hp1) and
  6941. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6942. MatchOpType(taicpu(hp1),top_ref) and
  6943. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6944. if ((taicpu(hp2).opcode = A_FMULP) or
  6945. (taicpu(hp2).opcode = A_FADDP)) then
  6946. { change to
  6947. fld/fst mem1 (hp1) fld/fst mem1
  6948. fld mem1 (p) fadd/
  6949. faddp/ fmul st, st
  6950. fmulp st, st1 (hp2) }
  6951. begin
  6952. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6953. RemoveCurrentP(p, hp1);
  6954. if (taicpu(hp2).opcode = A_FADDP) then
  6955. taicpu(hp2).opcode := A_FADD
  6956. else
  6957. taicpu(hp2).opcode := A_FMUL;
  6958. taicpu(hp2).oper[1]^.reg := NR_ST;
  6959. end
  6960. else
  6961. { change to
  6962. fld/fst mem1 (hp1) fld/fst mem1
  6963. fld mem1 (p) fld st
  6964. }
  6965. begin
  6966. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6967. taicpu(p).changeopsize(S_FL);
  6968. taicpu(p).loadreg(0,NR_ST);
  6969. end
  6970. else
  6971. begin
  6972. case taicpu(hp2).opcode Of
  6973. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6974. { change to
  6975. fld/fst mem1 (hp1) fld/fst mem1
  6976. fld mem2 (p) fxxx mem2
  6977. fxxxp st, st1 (hp2) }
  6978. begin
  6979. case taicpu(hp2).opcode Of
  6980. A_FADDP: taicpu(p).opcode := A_FADD;
  6981. A_FMULP: taicpu(p).opcode := A_FMUL;
  6982. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6983. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6984. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6985. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6986. else
  6987. internalerror(2019050533);
  6988. end;
  6989. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6990. RemoveInstruction(hp2);
  6991. end
  6992. else
  6993. ;
  6994. end
  6995. end
  6996. end;
  6997. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6998. begin
  6999. Result := condition_in(cond1, cond2) or
  7000. { Not strictly subsets due to the actual flags checked, but because we're
  7001. comparing integers, E is a subset of AE and GE and their aliases }
  7002. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7003. end;
  7004. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7005. var
  7006. v: TCGInt;
  7007. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7008. FirstMatch, TempBool: Boolean;
  7009. NewReg: TRegister;
  7010. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7011. begin
  7012. Result:=false;
  7013. { All these optimisations need a next instruction }
  7014. if not GetNextInstruction(p, hp1) then
  7015. Exit;
  7016. { Search for:
  7017. cmp ###,###
  7018. j(c1) @lbl1
  7019. ...
  7020. @lbl:
  7021. cmp ###,### (same comparison as above)
  7022. j(c2) @lbl2
  7023. If c1 is a subset of c2, change to:
  7024. cmp ###,###
  7025. j(c1) @lbl2
  7026. (@lbl1 may become a dead label as a result)
  7027. }
  7028. { Also handle cases where there are multiple jumps in a row }
  7029. p_jump := hp1;
  7030. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7031. begin
  7032. if IsJumpToLabel(taicpu(p_jump)) then
  7033. begin
  7034. { Do jump optimisations first in case the condition becomes
  7035. unnecessary }
  7036. TempBool := True;
  7037. if DoJumpOptimizations(p_jump, TempBool) or
  7038. not TempBool then
  7039. begin
  7040. if Assigned(p_jump) then
  7041. begin
  7042. hp1 := p_jump;
  7043. if (p_jump.typ in [ait_align]) then
  7044. SkipAligns(p_jump, p_jump);
  7045. { CollapseZeroDistJump will be set to the label after the
  7046. jump if it optimises, whether or not it's live or dead }
  7047. if (p_jump.typ in [ait_label]) and
  7048. not (tai_label(p_jump).labsym.is_used) then
  7049. GetNextInstruction(p_jump, p_jump);
  7050. end;
  7051. TransferUsedRegs(TmpUsedRegs);
  7052. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7053. if not Assigned(p_jump) or
  7054. (
  7055. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7056. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7057. ) then
  7058. begin
  7059. { No more conditional jumps; conditional statement is no longer required }
  7060. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7061. RemoveCurrentP(p);
  7062. Result := True;
  7063. Exit;
  7064. end;
  7065. hp1 := p_jump;
  7066. Include(OptsToCheck, aoc_ForceNewIteration);
  7067. Continue;
  7068. end;
  7069. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7070. if GetNextInstruction(p_jump, hp2) and
  7071. (
  7072. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7073. not TempBool
  7074. ) then
  7075. begin
  7076. hp1 := p_jump;
  7077. Include(OptsToCheck, aoc_ForceNewIteration);
  7078. Continue;
  7079. end;
  7080. p_label := nil;
  7081. if Assigned(JumpLabel) then
  7082. p_label := getlabelwithsym(JumpLabel);
  7083. if Assigned(p_label) and
  7084. GetNextInstruction(p_label, p_dist) and
  7085. MatchInstruction(p_dist, A_CMP, []) and
  7086. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7087. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7088. GetNextInstruction(p_dist, hp1_dist) and
  7089. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7090. begin
  7091. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7092. if JumpLabel = JumpLabel_dist then
  7093. { This is an infinite loop }
  7094. Exit;
  7095. { Best optimisation when the first condition is a subset (or equal) of the second }
  7096. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7097. begin
  7098. { Any registers used here will already be allocated }
  7099. if Assigned(JumpLabel) then
  7100. JumpLabel.DecRefs;
  7101. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7102. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7103. Result := True;
  7104. { Don't exit yet. Since p and p_jump haven't actually been
  7105. removed, we can check for more on this iteration }
  7106. end
  7107. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7108. GetNextInstruction(hp1_dist, hp1_label) and
  7109. SkipAligns(hp1_label, hp1_label) and
  7110. (hp1_label.typ = ait_label) then
  7111. begin
  7112. JumpLabel_far := tai_label(hp1_label).labsym;
  7113. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7114. { This is an infinite loop }
  7115. Exit;
  7116. if Assigned(JumpLabel_far) then
  7117. begin
  7118. { In this situation, if the first jump branches, the second one will never,
  7119. branch so change the destination label to after the second jump }
  7120. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7121. if Assigned(JumpLabel) then
  7122. JumpLabel.DecRefs;
  7123. JumpLabel_far.IncRefs;
  7124. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7125. Result := True;
  7126. { Don't exit yet. Since p and p_jump haven't actually been
  7127. removed, we can check for more on this iteration }
  7128. Continue;
  7129. end;
  7130. end;
  7131. end;
  7132. end;
  7133. { Search for:
  7134. cmp ###,###
  7135. j(c1) @lbl1
  7136. cmp ###,### (same as first)
  7137. Remove second cmp
  7138. }
  7139. if GetNextInstruction(p_jump, hp2) and
  7140. (
  7141. (
  7142. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7143. (
  7144. (
  7145. MatchOpType(taicpu(p), top_const, top_reg) and
  7146. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7147. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7148. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7149. ) or (
  7150. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7151. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7152. )
  7153. )
  7154. ) or (
  7155. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7156. MatchOperand(taicpu(p).oper[0]^, 0) and
  7157. (taicpu(p).oper[1]^.typ = top_reg) and
  7158. MatchInstruction(hp2, A_TEST, []) and
  7159. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7160. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7161. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7162. )
  7163. ) then
  7164. begin
  7165. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7166. RemoveInstruction(hp2);
  7167. Result := True;
  7168. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7169. end;
  7170. GetNextInstruction(p_jump, p_jump);
  7171. end;
  7172. if (
  7173. { Don't call GetNextInstruction again if we already have it }
  7174. (hp1 = p_jump) or
  7175. GetNextInstruction(p, hp1)
  7176. ) and
  7177. MatchInstruction(hp1, A_Jcc, []) and
  7178. IsJumpToLabel(taicpu(hp1)) and
  7179. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7180. GetNextInstruction(hp1, hp2) then
  7181. begin
  7182. {
  7183. cmp x, y (or "cmp y, x")
  7184. je @lbl
  7185. mov x, y
  7186. @lbl:
  7187. (x and y can be constants, registers or references)
  7188. Change to:
  7189. mov x, y (x and y will always be equal in the end)
  7190. @lbl: (may beceome a dead label)
  7191. Also:
  7192. cmp x, y (or "cmp y, x")
  7193. jne @lbl
  7194. mov x, y
  7195. @lbl:
  7196. (x and y can be constants, registers or references)
  7197. Change to:
  7198. Absolutely nothing! (Except @lbl if it's still live)
  7199. }
  7200. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7201. (
  7202. (
  7203. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7204. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7205. ) or (
  7206. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7207. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7208. )
  7209. ) and
  7210. GetNextInstruction(hp2, hp1_label) and
  7211. SkipAligns(hp1_label, hp1_label) and
  7212. (hp1_label.typ = ait_label) and
  7213. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7214. begin
  7215. tai_label(hp1_label).labsym.DecRefs;
  7216. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7217. begin
  7218. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7219. RemoveInstruction(hp2);
  7220. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7221. end
  7222. else
  7223. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7224. RemoveInstruction(hp1);
  7225. RemoveCurrentp(p, hp2);
  7226. Result := True;
  7227. Exit;
  7228. end;
  7229. {
  7230. Try to optimise the following:
  7231. cmp $x,### ($x and $y can be registers or constants)
  7232. je @lbl1 (only reference)
  7233. cmp $y,### (### are identical)
  7234. @Lbl:
  7235. sete %reg1
  7236. Change to:
  7237. cmp $x,###
  7238. sete %reg2 (allocate new %reg2)
  7239. cmp $y,###
  7240. sete %reg1
  7241. orb %reg2,%reg1
  7242. (dealloc %reg2)
  7243. This adds an instruction (so don't perform under -Os), but it removes
  7244. a conditional branch.
  7245. }
  7246. if not (cs_opt_size in current_settings.optimizerswitches) and
  7247. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7248. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7249. { The first operand of CMP instructions can only be a register or
  7250. immediate anyway, so no need to check }
  7251. GetNextInstruction(hp2, p_label) and
  7252. (p_label.typ = ait_label) and
  7253. (tai_label(p_label).labsym.getrefs = 1) and
  7254. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7255. GetNextInstruction(p_label, p_dist) and
  7256. MatchInstruction(p_dist, A_SETcc, []) and
  7257. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7258. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7259. begin
  7260. TransferUsedRegs(TmpUsedRegs);
  7261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7262. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7263. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7264. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7265. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7266. { Get the instruction after the SETcc instruction so we can
  7267. allocate a new register over the entire range }
  7268. GetNextInstruction(p_dist, hp1_dist) then
  7269. begin
  7270. { Register can appear in p if it's not used afterwards, so only
  7271. allocate between hp1 and hp1_dist }
  7272. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7273. if NewReg <> NR_NO then
  7274. begin
  7275. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7276. { Change the jump instruction into a SETcc instruction }
  7277. taicpu(hp1).opcode := A_SETcc;
  7278. taicpu(hp1).opsize := S_B;
  7279. taicpu(hp1).loadreg(0, NewReg);
  7280. { This is now a dead label }
  7281. tai_label(p_label).labsym.decrefs;
  7282. { Prefer adding before the next instruction so the FLAGS
  7283. register is deallicated first }
  7284. AsmL.InsertBefore(
  7285. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7286. hp1_dist
  7287. );
  7288. Result := True;
  7289. { Don't exit yet, as p wasn't changed and hp1, while
  7290. modified, is still intact and might be optimised by the
  7291. SETcc optimisation below }
  7292. end;
  7293. end;
  7294. end;
  7295. end;
  7296. if taicpu(p).oper[0]^.typ = top_const then
  7297. begin
  7298. if (taicpu(p).oper[0]^.val = 0) and
  7299. (taicpu(p).oper[1]^.typ = top_reg) and
  7300. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7301. begin
  7302. hp2 := p;
  7303. FirstMatch := True;
  7304. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7305. anything meaningful once it's converted to "test %reg,%reg";
  7306. additionally, some jumps will always (or never) branch, so
  7307. evaluate every jump immediately following the
  7308. comparison, optimising the conditions if possible.
  7309. Similarly with SETcc... those that are always set to 0 or 1
  7310. are changed to MOV instructions }
  7311. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7312. (
  7313. GetNextInstruction(hp2, hp1) and
  7314. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7315. ) do
  7316. begin
  7317. FirstMatch := False;
  7318. case taicpu(hp1).condition of
  7319. C_B, C_C, C_NAE, C_O:
  7320. { For B/NAE:
  7321. Will never branch since an unsigned integer can never be below zero
  7322. For C/O:
  7323. Result cannot overflow because 0 is being subtracted
  7324. }
  7325. begin
  7326. if taicpu(hp1).opcode = A_Jcc then
  7327. begin
  7328. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7329. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7330. RemoveInstruction(hp1);
  7331. { Since hp1 was deleted, hp2 must not be updated }
  7332. Continue;
  7333. end
  7334. else
  7335. begin
  7336. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7337. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7338. taicpu(hp1).opcode := A_MOV;
  7339. taicpu(hp1).ops := 2;
  7340. taicpu(hp1).condition := C_None;
  7341. taicpu(hp1).opsize := S_B;
  7342. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7343. taicpu(hp1).loadconst(0, 0);
  7344. end;
  7345. end;
  7346. C_BE, C_NA:
  7347. begin
  7348. { Will only branch if equal to zero }
  7349. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7350. taicpu(hp1).condition := C_E;
  7351. end;
  7352. C_A, C_NBE:
  7353. begin
  7354. { Will only branch if not equal to zero }
  7355. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7356. taicpu(hp1).condition := C_NE;
  7357. end;
  7358. C_AE, C_NB, C_NC, C_NO:
  7359. begin
  7360. { Will always branch }
  7361. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7362. if taicpu(hp1).opcode = A_Jcc then
  7363. begin
  7364. MakeUnconditional(taicpu(hp1));
  7365. { Any jumps/set that follow will now be dead code }
  7366. RemoveDeadCodeAfterJump(taicpu(hp1));
  7367. Break;
  7368. end
  7369. else
  7370. begin
  7371. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7372. taicpu(hp1).opcode := A_MOV;
  7373. taicpu(hp1).ops := 2;
  7374. taicpu(hp1).condition := C_None;
  7375. taicpu(hp1).opsize := S_B;
  7376. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7377. taicpu(hp1).loadconst(0, 1);
  7378. end;
  7379. end;
  7380. C_None:
  7381. InternalError(2020012201);
  7382. C_P, C_PE, C_NP, C_PO:
  7383. { We can't handle parity checks and they should never be generated
  7384. after a general-purpose CMP (it's used in some floating-point
  7385. comparisons that don't use CMP) }
  7386. InternalError(2020012202);
  7387. else
  7388. { Zero/Equality, Sign, their complements and all of the
  7389. signed comparisons do not need to be converted };
  7390. end;
  7391. hp2 := hp1;
  7392. end;
  7393. { Convert the instruction to a TEST }
  7394. taicpu(p).opcode := A_TEST;
  7395. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7396. Result := True;
  7397. Exit;
  7398. end
  7399. else if (taicpu(p).oper[0]^.val = 1) and
  7400. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7401. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7402. begin
  7403. { Convert; To:
  7404. cmp $1,r/m cmp $0,r/m
  7405. jl @lbl jle @lbl
  7406. (Also do inverted conditions)
  7407. }
  7408. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7409. taicpu(p).oper[0]^.val := 0;
  7410. if taicpu(hp1).condition in [C_L, C_NGE] then
  7411. taicpu(hp1).condition := C_LE
  7412. else
  7413. taicpu(hp1).condition := C_NLE;
  7414. { If the instruction is now "cmp $0,%reg", convert it to a
  7415. TEST (and effectively do the work of the "cmp $0,%reg" in
  7416. the block above)
  7417. }
  7418. if (taicpu(p).oper[1]^.typ = top_reg) then
  7419. begin
  7420. taicpu(p).opcode := A_TEST;
  7421. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7422. end;
  7423. Result := True;
  7424. Exit;
  7425. end
  7426. else if (taicpu(p).oper[1]^.typ = top_reg)
  7427. {$ifdef x86_64}
  7428. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7429. {$endif x86_64}
  7430. then
  7431. begin
  7432. { cmp register,$8000 neg register
  7433. je target --> jo target
  7434. .... only if register is deallocated before jump.}
  7435. case Taicpu(p).opsize of
  7436. S_B: v:=$80;
  7437. S_W: v:=$8000;
  7438. S_L: v:=qword($80000000);
  7439. else
  7440. internalerror(2013112905);
  7441. end;
  7442. if (taicpu(p).oper[0]^.val=v) and
  7443. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7444. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7445. begin
  7446. TransferUsedRegs(TmpUsedRegs);
  7447. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7448. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7449. begin
  7450. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7451. Taicpu(p).opcode:=A_NEG;
  7452. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7453. Taicpu(p).clearop(1);
  7454. Taicpu(p).ops:=1;
  7455. if Taicpu(hp1).condition=C_E then
  7456. Taicpu(hp1).condition:=C_O
  7457. else
  7458. Taicpu(hp1).condition:=C_NO;
  7459. Result:=true;
  7460. exit;
  7461. end;
  7462. end;
  7463. end;
  7464. end;
  7465. if TrySwapMovCmp(p, hp1) then
  7466. begin
  7467. Result := True;
  7468. Exit;
  7469. end;
  7470. end;
  7471. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7472. var
  7473. hp1: tai;
  7474. begin
  7475. {
  7476. remove the second (v)pxor from
  7477. pxor reg,reg
  7478. ...
  7479. pxor reg,reg
  7480. }
  7481. Result:=false;
  7482. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7483. MatchOpType(taicpu(p),top_reg,top_reg) and
  7484. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7485. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7486. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7487. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7488. begin
  7489. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7490. RemoveInstruction(hp1);
  7491. Result:=true;
  7492. Exit;
  7493. end
  7494. {
  7495. replace
  7496. pxor reg1,reg1
  7497. movapd/s reg1,reg2
  7498. dealloc reg1
  7499. by
  7500. pxor reg2,reg2
  7501. }
  7502. else if GetNextInstruction(p,hp1) and
  7503. { we mix single and double opperations here because we assume that the compiler
  7504. generates vmovapd only after double operations and vmovaps only after single operations }
  7505. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7506. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7507. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7508. (taicpu(p).oper[0]^.typ=top_reg) then
  7509. begin
  7510. TransferUsedRegs(TmpUsedRegs);
  7511. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7512. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7513. begin
  7514. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7515. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7516. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7517. RemoveInstruction(hp1);
  7518. result:=true;
  7519. end;
  7520. end;
  7521. end;
  7522. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7523. var
  7524. hp1: tai;
  7525. begin
  7526. {
  7527. remove the second (v)pxor from
  7528. (v)pxor reg,reg
  7529. ...
  7530. (v)pxor reg,reg
  7531. }
  7532. Result:=false;
  7533. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7534. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7535. begin
  7536. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7537. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7538. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7539. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7540. begin
  7541. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7542. RemoveInstruction(hp1);
  7543. Result:=true;
  7544. Exit;
  7545. end;
  7546. {$ifdef x86_64}
  7547. {
  7548. replace
  7549. vpxor reg1,reg1,reg1
  7550. vmov reg,mem
  7551. by
  7552. movq $0,mem
  7553. }
  7554. if GetNextInstruction(p,hp1) and
  7555. MatchInstruction(hp1,A_VMOVSD,[]) and
  7556. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7557. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7558. begin
  7559. TransferUsedRegs(TmpUsedRegs);
  7560. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7561. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7562. begin
  7563. taicpu(hp1).loadconst(0,0);
  7564. taicpu(hp1).opcode:=A_MOV;
  7565. taicpu(hp1).opsize:=S_Q;
  7566. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7567. RemoveCurrentP(p);
  7568. result:=true;
  7569. Exit;
  7570. end;
  7571. end;
  7572. {$endif x86_64}
  7573. end
  7574. {
  7575. replace
  7576. vpxor reg1,reg1,reg2
  7577. by
  7578. vpxor reg2,reg2,reg2
  7579. to avoid unncessary data dependencies
  7580. }
  7581. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7582. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7583. begin
  7584. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7585. { avoid unncessary data dependency }
  7586. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7587. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7588. result:=true;
  7589. exit;
  7590. end;
  7591. Result:=OptPass1VOP(p);
  7592. end;
  7593. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7594. var
  7595. hp1 : tai;
  7596. begin
  7597. result:=false;
  7598. { replace
  7599. IMul const,%mreg1,%mreg2
  7600. Mov %reg2,%mreg3
  7601. dealloc %mreg3
  7602. by
  7603. Imul const,%mreg1,%mreg23
  7604. }
  7605. if (taicpu(p).ops=3) and
  7606. GetNextInstruction(p,hp1) and
  7607. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7608. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7609. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7610. begin
  7611. TransferUsedRegs(TmpUsedRegs);
  7612. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7613. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7614. begin
  7615. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7616. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7617. RemoveInstruction(hp1);
  7618. result:=true;
  7619. end;
  7620. end;
  7621. end;
  7622. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7623. var
  7624. hp1 : tai;
  7625. begin
  7626. result:=false;
  7627. { replace
  7628. IMul %reg0,%reg1,%reg2
  7629. Mov %reg2,%reg3
  7630. dealloc %reg2
  7631. by
  7632. Imul %reg0,%reg1,%reg3
  7633. }
  7634. if GetNextInstruction(p,hp1) and
  7635. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7636. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7637. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7638. begin
  7639. TransferUsedRegs(TmpUsedRegs);
  7640. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7641. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7642. begin
  7643. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7644. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7645. RemoveInstruction(hp1);
  7646. result:=true;
  7647. end;
  7648. end;
  7649. end;
  7650. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7651. var
  7652. hp1: tai;
  7653. begin
  7654. Result:=false;
  7655. { get rid of
  7656. (v)cvtss2sd reg0,<reg1,>reg2
  7657. (v)cvtss2sd reg2,<reg2,>reg0
  7658. }
  7659. if GetNextInstruction(p,hp1) and
  7660. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7661. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7662. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7663. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7664. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7665. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7666. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7667. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7668. )
  7669. ) then
  7670. begin
  7671. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7672. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7673. begin
  7674. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7675. RemoveCurrentP(p);
  7676. RemoveInstruction(hp1);
  7677. end
  7678. else
  7679. begin
  7680. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7681. if taicpu(hp1).opcode=A_CVTSD2SS then
  7682. begin
  7683. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7684. taicpu(p).opcode:=A_MOVAPS;
  7685. end
  7686. else
  7687. begin
  7688. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7689. taicpu(p).opcode:=A_VMOVAPS;
  7690. end;
  7691. taicpu(p).ops:=2;
  7692. RemoveInstruction(hp1);
  7693. end;
  7694. Result:=true;
  7695. Exit;
  7696. end;
  7697. end;
  7698. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7699. var
  7700. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7701. ThisReg: TRegister;
  7702. begin
  7703. Result := False;
  7704. if not GetNextInstruction(p,hp1) then
  7705. Exit;
  7706. {
  7707. convert
  7708. j<c> .L1
  7709. mov 1,reg
  7710. jmp .L2
  7711. .L1
  7712. mov 0,reg
  7713. .L2
  7714. into
  7715. mov 0,reg
  7716. set<not(c)> reg
  7717. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7718. would destroy the flag contents
  7719. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7720. executed at the same time as a previous comparison.
  7721. set<not(c)> reg
  7722. movzx reg, reg
  7723. }
  7724. if MatchInstruction(hp1,A_MOV,[]) and
  7725. (taicpu(hp1).oper[0]^.typ = top_const) and
  7726. (
  7727. (
  7728. (taicpu(hp1).oper[1]^.typ = top_reg)
  7729. {$ifdef i386}
  7730. { Under i386, ESI, EDI, EBP and ESP
  7731. don't have an 8-bit representation }
  7732. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7733. {$endif i386}
  7734. ) or (
  7735. {$ifdef i386}
  7736. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7737. {$endif i386}
  7738. (taicpu(hp1).opsize = S_B)
  7739. )
  7740. ) and
  7741. GetNextInstruction(hp1,hp2) and
  7742. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7743. GetNextInstruction(hp2,hp3) and
  7744. SkipAligns(hp3, hp3) and
  7745. (hp3.typ=ait_label) and
  7746. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7747. GetNextInstruction(hp3,hp4) and
  7748. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7749. (taicpu(hp4).oper[0]^.typ = top_const) and
  7750. (
  7751. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7752. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7753. ) and
  7754. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7755. GetNextInstruction(hp4,hp5) and
  7756. SkipAligns(hp5, hp5) and
  7757. (hp5.typ=ait_label) and
  7758. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7759. begin
  7760. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7761. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7762. tai_label(hp3).labsym.DecRefs;
  7763. { If this isn't the only reference to the middle label, we can
  7764. still make a saving - only that the first jump and everything
  7765. that follows will remain. }
  7766. if (tai_label(hp3).labsym.getrefs = 0) then
  7767. begin
  7768. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7769. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7770. else
  7771. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7772. { remove jump, first label and second MOV (also catching any aligns) }
  7773. repeat
  7774. if not GetNextInstruction(hp2, hp3) then
  7775. InternalError(2021040810);
  7776. RemoveInstruction(hp2);
  7777. hp2 := hp3;
  7778. until hp2 = hp5;
  7779. { Don't decrement reference count before the removal loop
  7780. above, otherwise GetNextInstruction won't stop on the
  7781. the label }
  7782. tai_label(hp5).labsym.DecRefs;
  7783. end
  7784. else
  7785. begin
  7786. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7787. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7788. else
  7789. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7790. end;
  7791. taicpu(p).opcode:=A_SETcc;
  7792. taicpu(p).opsize:=S_B;
  7793. taicpu(p).is_jmp:=False;
  7794. if taicpu(hp1).opsize=S_B then
  7795. begin
  7796. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7797. if taicpu(hp1).oper[1]^.typ = top_reg then
  7798. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7799. RemoveInstruction(hp1);
  7800. end
  7801. else
  7802. begin
  7803. { Will be a register because the size can't be S_B otherwise }
  7804. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7805. taicpu(p).loadreg(0, ThisReg);
  7806. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7807. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7808. begin
  7809. case taicpu(hp1).opsize of
  7810. S_W:
  7811. taicpu(hp1).opsize := S_BW;
  7812. S_L:
  7813. taicpu(hp1).opsize := S_BL;
  7814. {$ifdef x86_64}
  7815. S_Q:
  7816. begin
  7817. taicpu(hp1).opsize := S_BL;
  7818. { Change the destination register to 32-bit }
  7819. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7820. end;
  7821. {$endif x86_64}
  7822. else
  7823. InternalError(2021040820);
  7824. end;
  7825. taicpu(hp1).opcode := A_MOVZX;
  7826. taicpu(hp1).loadreg(0, ThisReg);
  7827. end
  7828. else
  7829. begin
  7830. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7831. { hp1 is already a MOV instruction with the correct register }
  7832. taicpu(hp1).loadconst(0, 0);
  7833. { Inserting it right before p will guarantee that the flags are also tracked }
  7834. asml.Remove(hp1);
  7835. asml.InsertBefore(hp1, p);
  7836. end;
  7837. end;
  7838. Result:=true;
  7839. exit;
  7840. end
  7841. else if (hp1.typ = ait_label) then
  7842. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7843. end;
  7844. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7845. var
  7846. hp1, hp2, hp3: tai;
  7847. SourceRef, TargetRef: TReference;
  7848. CurrentReg: TRegister;
  7849. begin
  7850. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7851. if not UseAVX then
  7852. InternalError(2021100501);
  7853. Result := False;
  7854. { Look for the following to simplify:
  7855. vmovdqa/u x(mem1), %xmmreg
  7856. vmovdqa/u %xmmreg, y(mem2)
  7857. vmovdqa/u x+16(mem1), %xmmreg
  7858. vmovdqa/u %xmmreg, y+16(mem2)
  7859. Change to:
  7860. vmovdqa/u x(mem1), %ymmreg
  7861. vmovdqa/u %ymmreg, y(mem2)
  7862. vpxor %ymmreg, %ymmreg, %ymmreg
  7863. ( The VPXOR instruction is to zero the upper half, thus removing the
  7864. need to call the potentially expensive VZEROUPPER instruction. Other
  7865. peephole optimisations can remove VPXOR if it's unnecessary )
  7866. }
  7867. TransferUsedRegs(TmpUsedRegs);
  7868. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7869. { NOTE: In the optimisations below, if the references dictate that an
  7870. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7871. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7872. if (taicpu(p).opsize = S_XMM) and
  7873. MatchOpType(taicpu(p), top_ref, top_reg) and
  7874. GetNextInstruction(p, hp1) and
  7875. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7876. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7877. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7878. begin
  7879. SourceRef := taicpu(p).oper[0]^.ref^;
  7880. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7881. if GetNextInstruction(hp1, hp2) and
  7882. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7883. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7884. begin
  7885. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7886. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7887. Inc(SourceRef.offset, 16);
  7888. { Reuse the register in the first block move }
  7889. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7890. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7891. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7892. begin
  7893. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7894. Inc(TargetRef.offset, 16);
  7895. if GetNextInstruction(hp2, hp3) and
  7896. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7897. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7898. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7899. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7900. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7901. begin
  7902. { Update the register tracking to the new size }
  7903. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7904. { Remember that the offsets are 16 ahead }
  7905. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7906. if not (
  7907. ((SourceRef.offset mod 32) = 16) and
  7908. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7909. ) then
  7910. taicpu(p).opcode := A_VMOVDQU;
  7911. taicpu(p).opsize := S_YMM;
  7912. taicpu(p).oper[1]^.reg := CurrentReg;
  7913. if not (
  7914. ((TargetRef.offset mod 32) = 16) and
  7915. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7916. ) then
  7917. taicpu(hp1).opcode := A_VMOVDQU;
  7918. taicpu(hp1).opsize := S_YMM;
  7919. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7920. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7921. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7922. if (pi_uses_ymm in current_procinfo.flags) then
  7923. RemoveInstruction(hp2)
  7924. else
  7925. begin
  7926. taicpu(hp2).opcode := A_VPXOR;
  7927. taicpu(hp2).opsize := S_YMM;
  7928. taicpu(hp2).loadreg(0, CurrentReg);
  7929. taicpu(hp2).loadreg(1, CurrentReg);
  7930. taicpu(hp2).loadreg(2, CurrentReg);
  7931. taicpu(hp2).ops := 3;
  7932. end;
  7933. RemoveInstruction(hp3);
  7934. Result := True;
  7935. Exit;
  7936. end;
  7937. end
  7938. else
  7939. begin
  7940. { See if the next references are 16 less rather than 16 greater }
  7941. Dec(SourceRef.offset, 32); { -16 the other way }
  7942. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7943. begin
  7944. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7945. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7946. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7947. GetNextInstruction(hp2, hp3) and
  7948. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7949. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7950. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7951. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7952. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7953. begin
  7954. { Update the register tracking to the new size }
  7955. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7956. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7957. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7958. if not(
  7959. ((SourceRef.offset mod 32) = 0) and
  7960. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7961. ) then
  7962. taicpu(hp2).opcode := A_VMOVDQU;
  7963. taicpu(hp2).opsize := S_YMM;
  7964. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7965. if not (
  7966. ((TargetRef.offset mod 32) = 0) and
  7967. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7968. ) then
  7969. taicpu(hp3).opcode := A_VMOVDQU;
  7970. taicpu(hp3).opsize := S_YMM;
  7971. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7972. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7973. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7974. if (pi_uses_ymm in current_procinfo.flags) then
  7975. RemoveInstruction(hp1)
  7976. else
  7977. begin
  7978. taicpu(hp1).opcode := A_VPXOR;
  7979. taicpu(hp1).opsize := S_YMM;
  7980. taicpu(hp1).loadreg(0, CurrentReg);
  7981. taicpu(hp1).loadreg(1, CurrentReg);
  7982. taicpu(hp1).loadreg(2, CurrentReg);
  7983. taicpu(hp1).ops := 3;
  7984. Asml.Remove(hp1);
  7985. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7986. end;
  7987. RemoveCurrentP(p, hp2);
  7988. Result := True;
  7989. Exit;
  7990. end;
  7991. end;
  7992. end;
  7993. end;
  7994. end;
  7995. end;
  7996. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7997. var
  7998. hp2, hp3, first_assignment: tai;
  7999. IncCount, OperIdx: Integer;
  8000. OrigLabel: TAsmLabel;
  8001. begin
  8002. Count := 0;
  8003. Result := False;
  8004. first_assignment := nil;
  8005. if (LoopCount >= 20) then
  8006. begin
  8007. { Guard against infinite loops }
  8008. Exit;
  8009. end;
  8010. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8011. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8012. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8013. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8014. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8015. Exit;
  8016. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8017. {
  8018. change
  8019. jmp .L1
  8020. ...
  8021. .L1:
  8022. mov ##, ## ( multiple movs possible )
  8023. jmp/ret
  8024. into
  8025. mov ##, ##
  8026. jmp/ret
  8027. }
  8028. if not Assigned(hp1) then
  8029. begin
  8030. hp1 := GetLabelWithSym(OrigLabel);
  8031. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8032. Exit;
  8033. end;
  8034. hp2 := hp1;
  8035. while Assigned(hp2) do
  8036. begin
  8037. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8038. SkipLabels(hp2,hp2);
  8039. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8040. Break;
  8041. case taicpu(hp2).opcode of
  8042. A_MOVSD:
  8043. begin
  8044. if taicpu(hp2).ops = 0 then
  8045. { Wrong MOVSD }
  8046. Break;
  8047. Inc(Count);
  8048. if Count >= 5 then
  8049. { Too many to be worthwhile }
  8050. Break;
  8051. GetNextInstruction(hp2, hp2);
  8052. Continue;
  8053. end;
  8054. A_MOV,
  8055. A_MOVD,
  8056. A_MOVQ,
  8057. A_MOVSX,
  8058. {$ifdef x86_64}
  8059. A_MOVSXD,
  8060. {$endif x86_64}
  8061. A_MOVZX,
  8062. A_MOVAPS,
  8063. A_MOVUPS,
  8064. A_MOVSS,
  8065. A_MOVAPD,
  8066. A_MOVUPD,
  8067. A_MOVDQA,
  8068. A_MOVDQU,
  8069. A_VMOVSS,
  8070. A_VMOVAPS,
  8071. A_VMOVUPS,
  8072. A_VMOVSD,
  8073. A_VMOVAPD,
  8074. A_VMOVUPD,
  8075. A_VMOVDQA,
  8076. A_VMOVDQU:
  8077. begin
  8078. Inc(Count);
  8079. if Count >= 5 then
  8080. { Too many to be worthwhile }
  8081. Break;
  8082. GetNextInstruction(hp2, hp2);
  8083. Continue;
  8084. end;
  8085. A_JMP:
  8086. begin
  8087. { Guard against infinite loops }
  8088. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8089. Exit;
  8090. { Analyse this jump first in case it also duplicates assignments }
  8091. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8092. begin
  8093. { Something did change! }
  8094. Result := True;
  8095. Inc(Count, IncCount);
  8096. if Count >= 5 then
  8097. begin
  8098. { Too many to be worthwhile }
  8099. Exit;
  8100. end;
  8101. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8102. Break;
  8103. end;
  8104. Result := True;
  8105. Break;
  8106. end;
  8107. A_RET:
  8108. begin
  8109. Result := True;
  8110. Break;
  8111. end;
  8112. else
  8113. Break;
  8114. end;
  8115. end;
  8116. if Result then
  8117. begin
  8118. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8119. if Count = 0 then
  8120. begin
  8121. Result := False;
  8122. Exit;
  8123. end;
  8124. hp3 := p;
  8125. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8126. while True do
  8127. begin
  8128. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8129. SkipLabels(hp1,hp1);
  8130. if (hp1.typ <> ait_instruction) then
  8131. InternalError(2021040720);
  8132. case taicpu(hp1).opcode of
  8133. A_JMP:
  8134. begin
  8135. { Change the original jump to the new destination }
  8136. OrigLabel.decrefs;
  8137. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8138. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8139. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8140. if not Assigned(first_assignment) then
  8141. InternalError(2021040810)
  8142. else
  8143. p := first_assignment;
  8144. Exit;
  8145. end;
  8146. A_RET:
  8147. begin
  8148. { Now change the jump into a RET instruction }
  8149. ConvertJumpToRET(p, hp1);
  8150. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8151. if not Assigned(first_assignment) then
  8152. InternalError(2021040811)
  8153. else
  8154. p := first_assignment;
  8155. Exit;
  8156. end;
  8157. else
  8158. begin
  8159. { Duplicate the MOV instruction }
  8160. hp3:=tai(hp1.getcopy);
  8161. if first_assignment = nil then
  8162. first_assignment := hp3;
  8163. asml.InsertBefore(hp3, p);
  8164. { Make sure the compiler knows about any final registers written here }
  8165. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8166. with taicpu(hp3).oper[OperIdx]^ do
  8167. begin
  8168. case typ of
  8169. top_ref:
  8170. begin
  8171. if (ref^.base <> NR_NO) and
  8172. (getsupreg(ref^.base) <> RS_ESP) and
  8173. (getsupreg(ref^.base) <> RS_EBP)
  8174. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8175. then
  8176. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8177. if (ref^.index <> NR_NO) and
  8178. (getsupreg(ref^.index) <> RS_ESP) and
  8179. (getsupreg(ref^.index) <> RS_EBP)
  8180. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8181. (ref^.index <> ref^.base) then
  8182. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8183. end;
  8184. top_reg:
  8185. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8186. else
  8187. ;
  8188. end;
  8189. end;
  8190. end;
  8191. end;
  8192. if not GetNextInstruction(hp1, hp1) then
  8193. { Should have dropped out earlier }
  8194. InternalError(2021040710);
  8195. end;
  8196. end;
  8197. end;
  8198. const
  8199. WriteOp: array[0..3] of set of TInsChange = (
  8200. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8201. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8202. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8203. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8204. RegWriteFlags: array[0..7] of set of TInsChange = (
  8205. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8206. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8207. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8208. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8209. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8210. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8211. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8212. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8213. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8214. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8215. var
  8216. hp2: tai;
  8217. X: Integer;
  8218. begin
  8219. { If we have something like:
  8220. op ###,###
  8221. mov ###,###
  8222. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8223. interfere in regards to what they write to.
  8224. NOTE: p must be a 2-operand instruction
  8225. }
  8226. Result := False;
  8227. if (hp1.typ <> ait_instruction) or
  8228. taicpu(hp1).is_jmp or
  8229. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8230. Exit;
  8231. { NOP is a pipeline fence, likely marking the beginning of the function
  8232. epilogue, so drop out. Similarly, drop out if POP or RET are
  8233. encountered }
  8234. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8235. Exit;
  8236. if (taicpu(hp1).opcode = A_MOVSD) and
  8237. (taicpu(hp1).ops = 0) then
  8238. { Wrong MOVSD }
  8239. Exit;
  8240. { Check for writes to specific registers first }
  8241. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8242. for X := 0 to 7 do
  8243. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8244. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8245. Exit;
  8246. for X := 0 to taicpu(hp1).ops - 1 do
  8247. begin
  8248. { Check to see if this operand writes to something }
  8249. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8250. { And matches something in the CMP/TEST instruction }
  8251. (
  8252. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8253. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8254. (
  8255. { If it's a register, make sure the register written to doesn't
  8256. appear in the cmp instruction as part of a reference }
  8257. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8258. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8259. )
  8260. ) then
  8261. Exit;
  8262. end;
  8263. { Check p to make sure it doesn't write to something that affects hp1 }
  8264. { Check for writes to specific registers first }
  8265. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8266. for X := 0 to 7 do
  8267. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8268. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8269. Exit;
  8270. for X := 0 to taicpu(p).ops - 1 do
  8271. begin
  8272. { Check to see if this operand writes to something }
  8273. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8274. { And matches something in hp1 }
  8275. (taicpu(p).oper[X]^.typ = top_reg) and
  8276. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8277. Exit;
  8278. end;
  8279. { The instruction can be safely moved }
  8280. asml.Remove(hp1);
  8281. { Try to insert after the last instructions where the FLAGS register is not
  8282. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8283. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8284. asml.InsertBefore(hp1, hp2)
  8285. { Failing that, try to insert after the last instructions where the
  8286. FLAGS register is not yet in use }
  8287. else if GetLastInstruction(p, hp2) and
  8288. (
  8289. (hp2.typ <> ait_instruction) or
  8290. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8291. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8292. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8293. ) then
  8294. asml.InsertAfter(hp1, hp2)
  8295. else
  8296. { Note, if p.Previous is nil (even if it should logically never be the
  8297. case), FindRegAllocBackward immediately exits with False and so we
  8298. safely land here (we can't just pass p because FindRegAllocBackward
  8299. immediately exits on an instruction). [Kit] }
  8300. asml.InsertBefore(hp1, p);
  8301. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8302. { We can't trust UsedRegs because we're looking backwards, although we
  8303. know the registers are allocated after p at the very least, so manually
  8304. create tai_regalloc objects if needed }
  8305. for X := 0 to taicpu(hp1).ops - 1 do
  8306. case taicpu(hp1).oper[X]^.typ of
  8307. top_reg:
  8308. begin
  8309. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8310. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8311. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8312. end;
  8313. top_ref:
  8314. begin
  8315. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8316. begin
  8317. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8318. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8319. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8320. end;
  8321. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8322. begin
  8323. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8324. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8325. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8326. end;
  8327. end;
  8328. else
  8329. ;
  8330. end;
  8331. Result := True;
  8332. end;
  8333. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8334. var
  8335. hp2: tai;
  8336. X: Integer;
  8337. begin
  8338. { If we have something like:
  8339. cmp ###,%reg1
  8340. mov 0,%reg2
  8341. And no modified registers are shared, move the instruction to before
  8342. the comparison as this means it can be optimised without worrying
  8343. about the FLAGS register. (CMP/MOV is generated by
  8344. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8345. As long as the second instruction doesn't use the flags or one of the
  8346. registers used by CMP or TEST (also check any references that use the
  8347. registers), then it can be moved prior to the comparison.
  8348. }
  8349. Result := False;
  8350. if not TrySwapMovOp(p, hp1) then
  8351. Exit;
  8352. if taicpu(hp1).opcode = A_LEA then
  8353. { The flags will be overwritten by the CMP/TEST instruction }
  8354. ConvertLEA(taicpu(hp1));
  8355. Result := True;
  8356. { Can we move it one further back? }
  8357. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8358. { Check to see if CMP/TEST is a comparison against zero }
  8359. (
  8360. (
  8361. (taicpu(p).opcode = A_CMP) and
  8362. MatchOperand(taicpu(p).oper[0]^, 0)
  8363. ) or
  8364. (
  8365. (taicpu(p).opcode = A_TEST) and
  8366. (
  8367. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8368. MatchOperand(taicpu(p).oper[0]^, -1)
  8369. )
  8370. )
  8371. ) and
  8372. { These instructions set the zero flag if the result is zero }
  8373. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8374. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8375. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8376. TrySwapMovOp(hp2, hp1);
  8377. end;
  8378. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8379. function IsXCHGAcceptable: Boolean; inline;
  8380. begin
  8381. { Always accept if optimising for size }
  8382. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8383. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8384. than 3, so it becomes a saving compared to three MOVs with two of
  8385. them able to execute simultaneously. [Kit] }
  8386. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8387. end;
  8388. var
  8389. NewRef: TReference;
  8390. hp1, hp2, hp3, hp4: Tai;
  8391. {$ifndef x86_64}
  8392. OperIdx: Integer;
  8393. {$endif x86_64}
  8394. NewInstr : Taicpu;
  8395. NewAligh : Tai_align;
  8396. DestLabel: TAsmLabel;
  8397. TempTracking: TAllUsedRegs;
  8398. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8399. var
  8400. NextInstr: tai;
  8401. begin
  8402. Result := False;
  8403. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8404. if not GetNextInstruction(InputInstr, NextInstr) or
  8405. (
  8406. { The FLAGS register isn't always tracked properly, so do not
  8407. perform this optimisation if a conditional statement follows }
  8408. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8409. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8410. ) then
  8411. begin
  8412. reference_reset(NewRef, 1, []);
  8413. NewRef.base := taicpu(p).oper[0]^.reg;
  8414. NewRef.scalefactor := 1;
  8415. if taicpu(InputInstr).opcode = A_ADD then
  8416. begin
  8417. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8418. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8419. end
  8420. else
  8421. begin
  8422. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8423. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8424. end;
  8425. taicpu(p).opcode := A_LEA;
  8426. taicpu(p).loadref(0, NewRef);
  8427. RemoveInstruction(InputInstr);
  8428. Result := True;
  8429. end;
  8430. end;
  8431. begin
  8432. Result:=false;
  8433. { This optimisation adds an instruction, so only do it for speed }
  8434. if not (cs_opt_size in current_settings.optimizerswitches) and
  8435. MatchOpType(taicpu(p), top_const, top_reg) and
  8436. (taicpu(p).oper[0]^.val = 0) then
  8437. begin
  8438. { To avoid compiler warning }
  8439. DestLabel := nil;
  8440. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8441. InternalError(2021040750);
  8442. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8443. Exit;
  8444. case hp1.typ of
  8445. ait_align,
  8446. ait_label:
  8447. begin
  8448. { Change:
  8449. mov $0,%reg mov $0,%reg
  8450. @Lbl1: @Lbl1:
  8451. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8452. je @Lbl2 jne @Lbl2
  8453. To: To:
  8454. mov $0,%reg mov $0,%reg
  8455. jmp @Lbl2 jmp @Lbl3
  8456. (align) (align)
  8457. @Lbl1: @Lbl1:
  8458. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8459. je @Lbl2 je @Lbl2
  8460. @Lbl3: <-- Only if label exists
  8461. (Not if it's optimised for size)
  8462. }
  8463. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8464. Exit;
  8465. if (hp2.typ = ait_instruction) and
  8466. (
  8467. { Register sizes must exactly match }
  8468. (
  8469. (taicpu(hp2).opcode = A_CMP) and
  8470. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8471. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8472. ) or (
  8473. (taicpu(hp2).opcode = A_TEST) and
  8474. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8475. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8476. )
  8477. ) and GetNextInstruction(hp2, hp3) and
  8478. (hp3.typ = ait_instruction) and
  8479. (taicpu(hp3).opcode = A_JCC) and
  8480. (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
  8481. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8482. begin
  8483. { Check condition of jump }
  8484. { Always true? }
  8485. if condition_in(C_E, taicpu(hp3).condition) then
  8486. begin
  8487. { Copy label symbol and obtain matching label entry for the
  8488. conditional jump, as this will be our destination}
  8489. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8490. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8491. Result := True;
  8492. end
  8493. { Always false? }
  8494. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8495. begin
  8496. { This is only worth it if there's a jump to take }
  8497. case hp2.typ of
  8498. ait_instruction:
  8499. begin
  8500. if taicpu(hp2).opcode = A_JMP then
  8501. begin
  8502. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8503. { An unconditional jump follows the conditional jump which will always be false,
  8504. so use this jump's destination for the new jump }
  8505. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8506. Result := True;
  8507. end
  8508. else if taicpu(hp2).opcode = A_JCC then
  8509. begin
  8510. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8511. if condition_in(C_E, taicpu(hp2).condition) then
  8512. begin
  8513. { A second conditional jump follows the conditional jump which will always be false,
  8514. while the second jump is always True, so use this jump's destination for the new jump }
  8515. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8516. Result := True;
  8517. end;
  8518. { Don't risk it if the jump isn't always true (Result remains False) }
  8519. end;
  8520. end;
  8521. else
  8522. { If anything else don't optimise };
  8523. end;
  8524. end;
  8525. if Result then
  8526. begin
  8527. { Just so we have something to insert as a paremeter}
  8528. reference_reset(NewRef, 1, []);
  8529. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8530. { Now actually load the correct parameter (this also
  8531. increases the reference count) }
  8532. NewInstr.loadsymbol(0, DestLabel, 0);
  8533. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8534. begin
  8535. { Get instruction before original label (may not be p under -O3) }
  8536. if not GetLastInstruction(hp1, hp2) then
  8537. { Shouldn't fail here }
  8538. InternalError(2021040701);
  8539. { Before the aligns too }
  8540. while (hp2.typ = ait_align) do
  8541. if not GetLastInstruction(hp2, hp2) then
  8542. { Shouldn't fail here }
  8543. InternalError(2021040702);
  8544. end
  8545. else
  8546. hp2 := p;
  8547. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8548. AsmL.InsertAfter(NewInstr, hp2);
  8549. { Add new alignment field }
  8550. (* AsmL.InsertAfter(
  8551. cai_align.create_max(
  8552. current_settings.alignment.jumpalign,
  8553. current_settings.alignment.jumpalignskipmax
  8554. ),
  8555. NewInstr
  8556. ); *)
  8557. end;
  8558. Exit;
  8559. end;
  8560. end;
  8561. else
  8562. ;
  8563. end;
  8564. end;
  8565. if not GetNextInstruction(p, hp1) then
  8566. Exit;
  8567. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8568. and DoMovCmpMemOpt(p, hp1) then
  8569. begin
  8570. Result := True;
  8571. Exit;
  8572. end
  8573. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8574. begin
  8575. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8576. further, but we can't just put this jump optimisation in pass 1
  8577. because it tends to perform worse when conditional jumps are
  8578. nearby (e.g. when converting CMOV instructions). [Kit] }
  8579. CopyUsedRegs(TempTracking);
  8580. UpdateUsedRegs(tai(p.Next));
  8581. if OptPass2JMP(hp1) then
  8582. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8583. Result := OptPass1MOV(p);
  8584. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8585. returned True and the instruction is still a MOV, thus checking
  8586. the optimisations below }
  8587. { If OptPass2JMP returned False, no optimisations were done to
  8588. the jump and there are no further optimisations that can be done
  8589. to the MOV instruction on this pass }
  8590. { Restore register state }
  8591. RestoreUsedRegs(TempTracking);
  8592. ReleaseUsedRegs(TempTracking);
  8593. end
  8594. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8595. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8596. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8597. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8598. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8599. begin
  8600. { Change:
  8601. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8602. addl/q $x,%reg2 subl/q $x,%reg2
  8603. To:
  8604. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8605. }
  8606. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8607. { be lazy, checking separately for sub would be slightly better }
  8608. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8609. begin
  8610. TransferUsedRegs(TmpUsedRegs);
  8611. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8612. if TryMovArith2Lea(hp1) then
  8613. begin
  8614. Result := True;
  8615. Exit;
  8616. end
  8617. end
  8618. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8619. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8620. { Same as above, but also adds or subtracts to %reg2 in between.
  8621. It's still valid as long as the flags aren't in use }
  8622. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8623. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8624. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8625. { be lazy, checking separately for sub would be slightly better }
  8626. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8627. begin
  8628. TransferUsedRegs(TmpUsedRegs);
  8629. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8630. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8631. if TryMovArith2Lea(hp2) then
  8632. begin
  8633. Result := True;
  8634. Exit;
  8635. end;
  8636. end;
  8637. end
  8638. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8639. {$ifdef x86_64}
  8640. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8641. {$else x86_64}
  8642. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8643. {$endif x86_64}
  8644. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8645. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8646. { mov reg1, reg2 mov reg1, reg2
  8647. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8648. begin
  8649. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8650. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8651. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8652. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8653. TransferUsedRegs(TmpUsedRegs);
  8654. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8655. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8656. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8657. then
  8658. begin
  8659. RemoveCurrentP(p, hp1);
  8660. Result:=true;
  8661. end;
  8662. exit;
  8663. end
  8664. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8665. IsXCHGAcceptable and
  8666. { XCHG doesn't support 8-byte registers }
  8667. (taicpu(p).opsize <> S_B) and
  8668. MatchInstruction(hp1, A_MOV, []) and
  8669. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8670. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8671. GetNextInstruction(hp1, hp2) and
  8672. MatchInstruction(hp2, A_MOV, []) and
  8673. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8674. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8675. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8676. begin
  8677. { mov %reg1,%reg2
  8678. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8679. mov %reg2,%reg3
  8680. (%reg2 not used afterwards)
  8681. Note that xchg takes 3 cycles to execute, and generally mov's take
  8682. only one cycle apiece, but the first two mov's can be executed in
  8683. parallel, only taking 2 cycles overall. Older processors should
  8684. therefore only optimise for size. [Kit]
  8685. }
  8686. TransferUsedRegs(TmpUsedRegs);
  8687. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8688. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8689. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8690. begin
  8691. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8692. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8693. taicpu(hp1).opcode := A_XCHG;
  8694. RemoveCurrentP(p, hp1);
  8695. RemoveInstruction(hp2);
  8696. Result := True;
  8697. Exit;
  8698. end;
  8699. end
  8700. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8701. MatchInstruction(hp1, A_SAR, []) then
  8702. begin
  8703. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8704. begin
  8705. { the use of %edx also covers the opsize being S_L }
  8706. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8707. begin
  8708. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8709. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8710. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8711. begin
  8712. { Change:
  8713. movl %eax,%edx
  8714. sarl $31,%edx
  8715. To:
  8716. cltd
  8717. }
  8718. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8719. RemoveInstruction(hp1);
  8720. taicpu(p).opcode := A_CDQ;
  8721. taicpu(p).opsize := S_NO;
  8722. taicpu(p).clearop(1);
  8723. taicpu(p).clearop(0);
  8724. taicpu(p).ops:=0;
  8725. Result := True;
  8726. end
  8727. else if (cs_opt_size in current_settings.optimizerswitches) and
  8728. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8729. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8730. begin
  8731. { Change:
  8732. movl %edx,%eax
  8733. sarl $31,%edx
  8734. To:
  8735. movl %edx,%eax
  8736. cltd
  8737. Note that this creates a dependency between the two instructions,
  8738. so only perform if optimising for size.
  8739. }
  8740. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8741. taicpu(hp1).opcode := A_CDQ;
  8742. taicpu(hp1).opsize := S_NO;
  8743. taicpu(hp1).clearop(1);
  8744. taicpu(hp1).clearop(0);
  8745. taicpu(hp1).ops:=0;
  8746. end;
  8747. {$ifndef x86_64}
  8748. end
  8749. { Don't bother if CMOV is supported, because a more optimal
  8750. sequence would have been generated for the Abs() intrinsic }
  8751. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8752. { the use of %eax also covers the opsize being S_L }
  8753. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8754. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8755. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8756. GetNextInstruction(hp1, hp2) and
  8757. MatchInstruction(hp2, A_XOR, [S_L]) and
  8758. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8759. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8760. GetNextInstruction(hp2, hp3) and
  8761. MatchInstruction(hp3, A_SUB, [S_L]) and
  8762. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8763. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8764. begin
  8765. { Change:
  8766. movl %eax,%edx
  8767. sarl $31,%eax
  8768. xorl %eax,%edx
  8769. subl %eax,%edx
  8770. (Instruction that uses %edx)
  8771. (%eax deallocated)
  8772. (%edx deallocated)
  8773. To:
  8774. cltd
  8775. xorl %edx,%eax <-- Note the registers have swapped
  8776. subl %edx,%eax
  8777. (Instruction that uses %eax) <-- %eax rather than %edx
  8778. }
  8779. TransferUsedRegs(TmpUsedRegs);
  8780. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8781. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8782. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8783. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8784. begin
  8785. if GetNextInstruction(hp3, hp4) and
  8786. not RegModifiedByInstruction(NR_EDX, hp4) and
  8787. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8788. begin
  8789. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8790. taicpu(p).opcode := A_CDQ;
  8791. taicpu(p).clearop(1);
  8792. taicpu(p).clearop(0);
  8793. taicpu(p).ops:=0;
  8794. RemoveInstruction(hp1);
  8795. taicpu(hp2).loadreg(0, NR_EDX);
  8796. taicpu(hp2).loadreg(1, NR_EAX);
  8797. taicpu(hp3).loadreg(0, NR_EDX);
  8798. taicpu(hp3).loadreg(1, NR_EAX);
  8799. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8800. { Convert references in the following instruction (hp4) from %edx to %eax }
  8801. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8802. with taicpu(hp4).oper[OperIdx]^ do
  8803. case typ of
  8804. top_reg:
  8805. if getsupreg(reg) = RS_EDX then
  8806. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8807. top_ref:
  8808. begin
  8809. if getsupreg(reg) = RS_EDX then
  8810. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8811. if getsupreg(reg) = RS_EDX then
  8812. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8813. end;
  8814. else
  8815. ;
  8816. end;
  8817. end;
  8818. end;
  8819. {$else x86_64}
  8820. end;
  8821. end
  8822. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8823. { the use of %rdx also covers the opsize being S_Q }
  8824. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8825. begin
  8826. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8827. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8828. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8829. begin
  8830. { Change:
  8831. movq %rax,%rdx
  8832. sarq $63,%rdx
  8833. To:
  8834. cqto
  8835. }
  8836. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8837. RemoveInstruction(hp1);
  8838. taicpu(p).opcode := A_CQO;
  8839. taicpu(p).opsize := S_NO;
  8840. taicpu(p).clearop(1);
  8841. taicpu(p).clearop(0);
  8842. taicpu(p).ops:=0;
  8843. Result := True;
  8844. end
  8845. else if (cs_opt_size in current_settings.optimizerswitches) and
  8846. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8847. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8848. begin
  8849. { Change:
  8850. movq %rdx,%rax
  8851. sarq $63,%rdx
  8852. To:
  8853. movq %rdx,%rax
  8854. cqto
  8855. Note that this creates a dependency between the two instructions,
  8856. so only perform if optimising for size.
  8857. }
  8858. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8859. taicpu(hp1).opcode := A_CQO;
  8860. taicpu(hp1).opsize := S_NO;
  8861. taicpu(hp1).clearop(1);
  8862. taicpu(hp1).clearop(0);
  8863. taicpu(hp1).ops:=0;
  8864. {$endif x86_64}
  8865. end;
  8866. end;
  8867. end
  8868. else if MatchInstruction(hp1, A_MOV, []) and
  8869. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8870. { Though "GetNextInstruction" could be factored out, along with
  8871. the instructions that depend on hp2, it is an expensive call that
  8872. should be delayed for as long as possible, hence we do cheaper
  8873. checks first that are likely to be False. [Kit] }
  8874. begin
  8875. if (
  8876. (
  8877. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8878. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8879. (
  8880. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8881. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8882. )
  8883. ) or
  8884. (
  8885. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8886. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8887. (
  8888. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8889. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8890. )
  8891. )
  8892. ) and
  8893. GetNextInstruction(hp1, hp2) and
  8894. MatchInstruction(hp2, A_SAR, []) and
  8895. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8896. begin
  8897. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8898. begin
  8899. { Change:
  8900. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8901. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8902. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8903. To:
  8904. movl r/m,%eax <- Note the change in register
  8905. cltd
  8906. }
  8907. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8908. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8909. taicpu(p).loadreg(1, NR_EAX);
  8910. taicpu(hp1).opcode := A_CDQ;
  8911. taicpu(hp1).clearop(1);
  8912. taicpu(hp1).clearop(0);
  8913. taicpu(hp1).ops:=0;
  8914. RemoveInstruction(hp2);
  8915. (*
  8916. {$ifdef x86_64}
  8917. end
  8918. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8919. { This code sequence does not get generated - however it might become useful
  8920. if and when 128-bit signed integer types make an appearance, so the code
  8921. is kept here for when it is eventually needed. [Kit] }
  8922. (
  8923. (
  8924. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8925. (
  8926. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8927. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8928. )
  8929. ) or
  8930. (
  8931. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8932. (
  8933. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8934. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8935. )
  8936. )
  8937. ) and
  8938. GetNextInstruction(hp1, hp2) and
  8939. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8940. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8941. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8942. begin
  8943. { Change:
  8944. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8945. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8946. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8947. To:
  8948. movq r/m,%rax <- Note the change in register
  8949. cqto
  8950. }
  8951. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8952. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8953. taicpu(p).loadreg(1, NR_RAX);
  8954. taicpu(hp1).opcode := A_CQO;
  8955. taicpu(hp1).clearop(1);
  8956. taicpu(hp1).clearop(0);
  8957. taicpu(hp1).ops:=0;
  8958. RemoveInstruction(hp2);
  8959. {$endif x86_64}
  8960. *)
  8961. end;
  8962. end;
  8963. {$ifdef x86_64}
  8964. end
  8965. else if (taicpu(p).opsize = S_L) and
  8966. (taicpu(p).oper[1]^.typ = top_reg) and
  8967. (
  8968. MatchInstruction(hp1, A_MOV,[]) and
  8969. (taicpu(hp1).opsize = S_L) and
  8970. (taicpu(hp1).oper[1]^.typ = top_reg)
  8971. ) and (
  8972. GetNextInstruction(hp1, hp2) and
  8973. (tai(hp2).typ=ait_instruction) and
  8974. (taicpu(hp2).opsize = S_Q) and
  8975. (
  8976. (
  8977. MatchInstruction(hp2, A_ADD,[]) and
  8978. (taicpu(hp2).opsize = S_Q) and
  8979. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8980. (
  8981. (
  8982. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8983. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8984. ) or (
  8985. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8986. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8987. )
  8988. )
  8989. ) or (
  8990. MatchInstruction(hp2, A_LEA,[]) and
  8991. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8992. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8993. (
  8994. (
  8995. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8996. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8997. ) or (
  8998. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8999. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9000. )
  9001. ) and (
  9002. (
  9003. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9004. ) or (
  9005. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9006. )
  9007. )
  9008. )
  9009. )
  9010. ) and (
  9011. GetNextInstruction(hp2, hp3) and
  9012. MatchInstruction(hp3, A_SHR,[]) and
  9013. (taicpu(hp3).opsize = S_Q) and
  9014. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9015. (taicpu(hp3).oper[0]^.val = 1) and
  9016. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9017. ) then
  9018. begin
  9019. { Change movl x, reg1d movl x, reg1d
  9020. movl y, reg2d movl y, reg2d
  9021. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9022. shrq $1, reg1q shrq $1, reg1q
  9023. ( reg1d and reg2d can be switched around in the first two instructions )
  9024. To movl x, reg1d
  9025. addl y, reg1d
  9026. rcrl $1, reg1d
  9027. This corresponds to the common expression (x + y) shr 1, where
  9028. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9029. smaller code, but won't account for x + y causing an overflow). [Kit]
  9030. }
  9031. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9032. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9033. { Change first MOV command to have the same register as the final output }
  9034. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9035. else
  9036. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9037. { Change second MOV command to an ADD command. This is easier than
  9038. converting the existing command because it means we don't have to
  9039. touch 'y', which might be a complicated reference, and also the
  9040. fact that the third command might either be ADD or LEA. [Kit] }
  9041. taicpu(hp1).opcode := A_ADD;
  9042. { Delete old ADD/LEA instruction }
  9043. RemoveInstruction(hp2);
  9044. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9045. taicpu(hp3).opcode := A_RCR;
  9046. taicpu(hp3).changeopsize(S_L);
  9047. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9048. {$endif x86_64}
  9049. end;
  9050. if FuncMov2Func(p, hp1) then
  9051. begin
  9052. Result := True;
  9053. Exit;
  9054. end;
  9055. end;
  9056. {$push}
  9057. {$q-}{$r-}
  9058. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9059. var
  9060. ThisReg: TRegister;
  9061. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9062. TargetSubReg: TSubRegister;
  9063. hp1, hp2: tai;
  9064. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9065. { Store list of found instructions so we don't have to call
  9066. GetNextInstructionUsingReg multiple times }
  9067. InstrList: array of taicpu;
  9068. InstrMax, Index: Integer;
  9069. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9070. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9071. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9072. WorkingValue: TCgInt;
  9073. PreMessage: string;
  9074. { Data flow analysis }
  9075. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9076. BitwiseOnly, OrXorUsed,
  9077. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9078. function CheckOverflowConditions: Boolean;
  9079. begin
  9080. Result := True;
  9081. if (TestValSignedMax > SignedUpperLimit) then
  9082. UpperSignedOverflow := True;
  9083. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9084. LowerSignedOverflow := True;
  9085. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9086. LowerUnsignedOverflow := True;
  9087. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9088. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9089. begin
  9090. { Absolute overflow }
  9091. Result := False;
  9092. Exit;
  9093. end;
  9094. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9095. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9096. ShiftDownOverflow := True;
  9097. if (TestValMin < 0) or (TestValMax < 0) then
  9098. begin
  9099. LowerUnsignedOverflow := True;
  9100. UpperUnsignedOverflow := True;
  9101. end;
  9102. end;
  9103. function AdjustInitialLoadAndSize: Boolean;
  9104. begin
  9105. Result := False;
  9106. if not p_removed then
  9107. begin
  9108. if TargetSize = MinSize then
  9109. begin
  9110. { Convert the input MOVZX to a MOV }
  9111. if (taicpu(p).oper[0]^.typ = top_reg) and
  9112. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9113. begin
  9114. { Or remove it completely! }
  9115. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9116. RemoveCurrentP(p);
  9117. p_removed := True;
  9118. end
  9119. else
  9120. begin
  9121. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9122. taicpu(p).opcode := A_MOV;
  9123. taicpu(p).oper[1]^.reg := ThisReg;
  9124. taicpu(p).opsize := TargetSize;
  9125. end;
  9126. Result := True;
  9127. end
  9128. else if TargetSize <> MaxSize then
  9129. begin
  9130. case MaxSize of
  9131. S_L:
  9132. if TargetSize = S_W then
  9133. begin
  9134. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9135. taicpu(p).opsize := S_BW;
  9136. taicpu(p).oper[1]^.reg := ThisReg;
  9137. Result := True;
  9138. end
  9139. else
  9140. InternalError(2020112341);
  9141. S_W:
  9142. if TargetSize = S_L then
  9143. begin
  9144. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9145. taicpu(p).opsize := S_BL;
  9146. taicpu(p).oper[1]^.reg := ThisReg;
  9147. Result := True;
  9148. end
  9149. else
  9150. InternalError(2020112342);
  9151. else
  9152. ;
  9153. end;
  9154. end
  9155. else if not hp1_removed and not RegInUse then
  9156. begin
  9157. { If we have something like:
  9158. movzbl (oper),%regd
  9159. add x, %regd
  9160. movzbl %regb, %regd
  9161. We can reduce the register size to the input of the final
  9162. movzbl instruction. Overflows won't have any effect.
  9163. }
  9164. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9165. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9166. begin
  9167. TargetSize := S_B;
  9168. setsubreg(ThisReg, R_SUBL);
  9169. Result := True;
  9170. end
  9171. else if (taicpu(p).opsize = S_WL) and
  9172. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9173. begin
  9174. TargetSize := S_W;
  9175. setsubreg(ThisReg, R_SUBW);
  9176. Result := True;
  9177. end;
  9178. if Result then
  9179. begin
  9180. { Convert the input MOVZX to a MOV }
  9181. if (taicpu(p).oper[0]^.typ = top_reg) and
  9182. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9183. begin
  9184. { Or remove it completely! }
  9185. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9186. RemoveCurrentP(p);
  9187. p_removed := True;
  9188. end
  9189. else
  9190. begin
  9191. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9192. taicpu(p).opcode := A_MOV;
  9193. taicpu(p).oper[1]^.reg := ThisReg;
  9194. taicpu(p).opsize := TargetSize;
  9195. end;
  9196. end;
  9197. end;
  9198. end;
  9199. end;
  9200. procedure AdjustFinalLoad;
  9201. begin
  9202. if not LowerUnsignedOverflow then
  9203. begin
  9204. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9205. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9206. begin
  9207. { Convert the output MOVZX to a MOV }
  9208. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9209. begin
  9210. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9211. if (MinSize = S_B) or
  9212. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9213. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9214. begin
  9215. { Remove it completely! }
  9216. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9217. { Be careful; if p = hp1 and p was also removed, p
  9218. will become a dangling pointer }
  9219. if p = hp1 then
  9220. begin
  9221. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9222. p_removed := True;
  9223. end
  9224. else
  9225. RemoveInstruction(hp1);
  9226. hp1_removed := True;
  9227. end;
  9228. end
  9229. else
  9230. begin
  9231. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9232. taicpu(hp1).opcode := A_MOV;
  9233. taicpu(hp1).oper[0]^.reg := ThisReg;
  9234. taicpu(hp1).opsize := TargetSize;
  9235. end;
  9236. end
  9237. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9238. begin
  9239. { Need to change the size of the output }
  9240. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9241. taicpu(hp1).oper[0]^.reg := ThisReg;
  9242. taicpu(hp1).opsize := S_BL;
  9243. end;
  9244. end;
  9245. end;
  9246. function CompressInstructions: Boolean;
  9247. var
  9248. LocalIndex: Integer;
  9249. begin
  9250. Result := False;
  9251. { The objective here is to try to find a combination that
  9252. removes one of the MOV/Z instructions. }
  9253. if (
  9254. (taicpu(p).oper[0]^.typ <> top_reg) or
  9255. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9256. ) and
  9257. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9258. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9259. begin
  9260. { Make a preference to remove the second MOVZX instruction }
  9261. case taicpu(hp1).opsize of
  9262. S_BL, S_WL:
  9263. begin
  9264. TargetSize := S_L;
  9265. TargetSubReg := R_SUBD;
  9266. end;
  9267. S_BW:
  9268. begin
  9269. TargetSize := S_W;
  9270. TargetSubReg := R_SUBW;
  9271. end;
  9272. else
  9273. InternalError(2020112302);
  9274. end;
  9275. end
  9276. else
  9277. begin
  9278. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9279. begin
  9280. { Exceeded lower bound but not upper bound }
  9281. TargetSize := MaxSize;
  9282. end
  9283. else if not LowerUnsignedOverflow then
  9284. begin
  9285. { Size didn't exceed lower bound }
  9286. TargetSize := MinSize;
  9287. end
  9288. else
  9289. Exit;
  9290. end;
  9291. case TargetSize of
  9292. S_B:
  9293. TargetSubReg := R_SUBL;
  9294. S_W:
  9295. TargetSubReg := R_SUBW;
  9296. S_L:
  9297. TargetSubReg := R_SUBD;
  9298. else
  9299. InternalError(2020112350);
  9300. end;
  9301. { Update the register to its new size }
  9302. setsubreg(ThisReg, TargetSubReg);
  9303. RegInUse := False;
  9304. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9305. begin
  9306. { Check to see if the active register is used afterwards;
  9307. if not, we can change it and make a saving. }
  9308. TransferUsedRegs(TmpUsedRegs);
  9309. { The target register may be marked as in use to cross
  9310. a jump to a distant label, so exclude it }
  9311. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9312. hp2 := p;
  9313. repeat
  9314. { Explicitly check for the excluded register (don't include the first
  9315. instruction as it may be reading from here }
  9316. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9317. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9318. begin
  9319. RegInUse := True;
  9320. Break;
  9321. end;
  9322. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9323. if not GetNextInstruction(hp2, hp2) then
  9324. InternalError(2020112340);
  9325. until (hp2 = hp1);
  9326. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9327. { We might still be able to get away with this }
  9328. RegInUse := not
  9329. (
  9330. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9331. (hp2.typ = ait_instruction) and
  9332. (
  9333. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9334. instruction that doesn't actually contain ThisReg }
  9335. (cs_opt_level3 in current_settings.optimizerswitches) or
  9336. RegInInstruction(ThisReg, hp2)
  9337. ) and
  9338. RegLoadedWithNewValue(ThisReg, hp2)
  9339. );
  9340. if not RegInUse then
  9341. begin
  9342. { Force the register size to the same as this instruction so it can be removed}
  9343. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9344. begin
  9345. TargetSize := S_L;
  9346. TargetSubReg := R_SUBD;
  9347. end
  9348. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9349. begin
  9350. TargetSize := S_W;
  9351. TargetSubReg := R_SUBW;
  9352. end;
  9353. ThisReg := taicpu(hp1).oper[1]^.reg;
  9354. setsubreg(ThisReg, TargetSubReg);
  9355. RegChanged := True;
  9356. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9357. TransferUsedRegs(TmpUsedRegs);
  9358. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9359. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9360. if p = hp1 then
  9361. begin
  9362. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9363. p_removed := True;
  9364. end
  9365. else
  9366. RemoveInstruction(hp1);
  9367. hp1_removed := True;
  9368. { Instruction will become "mov %reg,%reg" }
  9369. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9370. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9371. begin
  9372. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9373. RemoveCurrentP(p);
  9374. p_removed := True;
  9375. end
  9376. else
  9377. taicpu(p).oper[1]^.reg := ThisReg;
  9378. Result := True;
  9379. end
  9380. else
  9381. begin
  9382. if TargetSize <> MaxSize then
  9383. begin
  9384. { Since the register is in use, we have to force it to
  9385. MaxSize otherwise part of it may become undefined later on }
  9386. TargetSize := MaxSize;
  9387. case TargetSize of
  9388. S_B:
  9389. TargetSubReg := R_SUBL;
  9390. S_W:
  9391. TargetSubReg := R_SUBW;
  9392. S_L:
  9393. TargetSubReg := R_SUBD;
  9394. else
  9395. InternalError(2020112351);
  9396. end;
  9397. setsubreg(ThisReg, TargetSubReg);
  9398. end;
  9399. AdjustFinalLoad;
  9400. end;
  9401. end
  9402. else
  9403. AdjustFinalLoad;
  9404. Result := AdjustInitialLoadAndSize or Result;
  9405. { Now go through every instruction we found and change the
  9406. size. If TargetSize = MaxSize, then almost no changes are
  9407. needed and Result can remain False if it hasn't been set
  9408. yet.
  9409. If RegChanged is True, then the register requires changing
  9410. and so the point about TargetSize = MaxSize doesn't apply. }
  9411. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9412. begin
  9413. for LocalIndex := 0 to InstrMax do
  9414. begin
  9415. { If p_removed is true, then the original MOV/Z was removed
  9416. and removing the AND instruction may not be safe if it
  9417. appears first }
  9418. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9419. InternalError(2020112310);
  9420. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9421. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9422. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9423. InstrList[LocalIndex].opsize := TargetSize;
  9424. end;
  9425. Result := True;
  9426. end;
  9427. end;
  9428. begin
  9429. Result := False;
  9430. p_removed := False;
  9431. hp1_removed := False;
  9432. ThisReg := taicpu(p).oper[1]^.reg;
  9433. { Check for:
  9434. movs/z ###,%ecx (or %cx or %rcx)
  9435. ...
  9436. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9437. (dealloc %ecx)
  9438. Change to:
  9439. mov ###,%cl (if ### = %cl, then remove completely)
  9440. ...
  9441. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9442. }
  9443. if (getsupreg(ThisReg) = RS_ECX) and
  9444. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9445. (hp1.typ = ait_instruction) and
  9446. (
  9447. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9448. instruction that doesn't actually contain ECX }
  9449. (cs_opt_level3 in current_settings.optimizerswitches) or
  9450. RegInInstruction(NR_ECX, hp1) or
  9451. (
  9452. { It's common for the shift/rotate's read/write register to be
  9453. initialised in between, so under -O2 and under, search ahead
  9454. one more instruction
  9455. }
  9456. GetNextInstruction(hp1, hp1) and
  9457. (hp1.typ = ait_instruction) and
  9458. RegInInstruction(NR_ECX, hp1)
  9459. )
  9460. ) and
  9461. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9462. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9463. begin
  9464. TransferUsedRegs(TmpUsedRegs);
  9465. hp2 := p;
  9466. repeat
  9467. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9468. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9469. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9470. begin
  9471. case taicpu(p).opsize of
  9472. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9473. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9474. begin
  9475. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9476. RemoveCurrentP(p);
  9477. end
  9478. else
  9479. begin
  9480. taicpu(p).opcode := A_MOV;
  9481. taicpu(p).opsize := S_B;
  9482. taicpu(p).oper[1]^.reg := NR_CL;
  9483. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9484. end;
  9485. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9486. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9487. begin
  9488. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9489. RemoveCurrentP(p);
  9490. end
  9491. else
  9492. begin
  9493. taicpu(p).opcode := A_MOV;
  9494. taicpu(p).opsize := S_W;
  9495. taicpu(p).oper[1]^.reg := NR_CX;
  9496. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9497. end;
  9498. {$ifdef x86_64}
  9499. S_LQ:
  9500. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9501. begin
  9502. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9503. RemoveCurrentP(p);
  9504. end
  9505. else
  9506. begin
  9507. taicpu(p).opcode := A_MOV;
  9508. taicpu(p).opsize := S_L;
  9509. taicpu(p).oper[1]^.reg := NR_ECX;
  9510. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9511. end;
  9512. {$endif x86_64}
  9513. else
  9514. InternalError(2021120401);
  9515. end;
  9516. Result := True;
  9517. Exit;
  9518. end;
  9519. end;
  9520. { This is anything but quick! }
  9521. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9522. Exit;
  9523. SetLength(InstrList, 0);
  9524. InstrMax := -1;
  9525. case taicpu(p).opsize of
  9526. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9527. begin
  9528. {$if defined(i386) or defined(i8086)}
  9529. { If the target size is 8-bit, make sure we can actually encode it }
  9530. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9531. Exit;
  9532. {$endif i386 or i8086}
  9533. LowerLimit := $FF;
  9534. SignedLowerLimit := $7F;
  9535. SignedLowerLimitBottom := -128;
  9536. MinSize := S_B;
  9537. if taicpu(p).opsize = S_BW then
  9538. begin
  9539. MaxSize := S_W;
  9540. UpperLimit := $FFFF;
  9541. SignedUpperLimit := $7FFF;
  9542. SignedUpperLimitBottom := -32768;
  9543. end
  9544. else
  9545. begin
  9546. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9547. MaxSize := S_L;
  9548. UpperLimit := $FFFFFFFF;
  9549. SignedUpperLimit := $7FFFFFFF;
  9550. SignedUpperLimitBottom := -2147483648;
  9551. end;
  9552. end;
  9553. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9554. begin
  9555. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9556. LowerLimit := $FFFF;
  9557. SignedLowerLimit := $7FFF;
  9558. SignedLowerLimitBottom := -32768;
  9559. UpperLimit := $FFFFFFFF;
  9560. SignedUpperLimit := $7FFFFFFF;
  9561. SignedUpperLimitBottom := -2147483648;
  9562. MinSize := S_W;
  9563. MaxSize := S_L;
  9564. end;
  9565. {$ifdef x86_64}
  9566. S_LQ:
  9567. begin
  9568. { Both the lower and upper limits are set to 32-bit. If a limit
  9569. is breached, then optimisation is impossible }
  9570. LowerLimit := $FFFFFFFF;
  9571. SignedLowerLimit := $7FFFFFFF;
  9572. SignedLowerLimitBottom := -2147483648;
  9573. UpperLimit := $FFFFFFFF;
  9574. SignedUpperLimit := $7FFFFFFF;
  9575. SignedUpperLimitBottom := -2147483648;
  9576. MinSize := S_L;
  9577. MaxSize := S_L;
  9578. end;
  9579. {$endif x86_64}
  9580. else
  9581. InternalError(2020112301);
  9582. end;
  9583. TestValMin := 0;
  9584. TestValMax := LowerLimit;
  9585. TestValSignedMax := SignedLowerLimit;
  9586. TryShiftDownLimit := LowerLimit;
  9587. TryShiftDown := S_NO;
  9588. ShiftDownOverflow := False;
  9589. RegChanged := False;
  9590. BitwiseOnly := True;
  9591. OrXorUsed := False;
  9592. UpperSignedOverflow := False;
  9593. LowerSignedOverflow := False;
  9594. UpperUnsignedOverflow := False;
  9595. LowerUnsignedOverflow := False;
  9596. hp1 := p;
  9597. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9598. (hp1.typ = ait_instruction) and
  9599. (
  9600. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9601. instruction that doesn't actually contain ThisReg }
  9602. (cs_opt_level3 in current_settings.optimizerswitches) or
  9603. { This allows this Movx optimisation to work through the SETcc instructions
  9604. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9605. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9606. skip over these SETcc instructions). }
  9607. (taicpu(hp1).opcode = A_SETcc) or
  9608. RegInInstruction(ThisReg, hp1)
  9609. ) do
  9610. begin
  9611. case taicpu(hp1).opcode of
  9612. A_INC,A_DEC:
  9613. begin
  9614. { Has to be an exact match on the register }
  9615. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9616. Break;
  9617. if taicpu(hp1).opcode = A_INC then
  9618. begin
  9619. Inc(TestValMin);
  9620. Inc(TestValMax);
  9621. Inc(TestValSignedMax);
  9622. end
  9623. else
  9624. begin
  9625. Dec(TestValMin);
  9626. Dec(TestValMax);
  9627. Dec(TestValSignedMax);
  9628. end;
  9629. end;
  9630. A_TEST, A_CMP:
  9631. begin
  9632. if (
  9633. { Too high a risk of non-linear behaviour that breaks DFA
  9634. here, unless it's cmp $0,%reg, which is equivalent to
  9635. test %reg,%reg }
  9636. OrXorUsed and
  9637. (taicpu(hp1).opcode = A_CMP) and
  9638. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9639. ) or
  9640. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9641. { Has to be an exact match on the register }
  9642. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9643. (
  9644. { Permit "test %reg,%reg" }
  9645. (taicpu(hp1).opcode = A_TEST) and
  9646. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9647. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9648. ) or
  9649. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9650. { Make sure the comparison value is not smaller than the
  9651. smallest allowed signed value for the minimum size (e.g.
  9652. -128 for 8-bit) }
  9653. not (
  9654. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9655. { Is it in the negative range? }
  9656. (
  9657. (taicpu(hp1).oper[0]^.val < 0) and
  9658. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9659. )
  9660. ) then
  9661. Break;
  9662. { Check to see if the active register is used afterwards }
  9663. TransferUsedRegs(TmpUsedRegs);
  9664. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9665. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9666. begin
  9667. { Make sure the comparison or any previous instructions
  9668. hasn't pushed the test values outside of the range of
  9669. MinSize }
  9670. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9671. begin
  9672. { Exceeded lower bound but not upper bound }
  9673. Exit;
  9674. end
  9675. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9676. begin
  9677. { Size didn't exceed lower bound }
  9678. TargetSize := MinSize;
  9679. end
  9680. else
  9681. Break;
  9682. case TargetSize of
  9683. S_B:
  9684. TargetSubReg := R_SUBL;
  9685. S_W:
  9686. TargetSubReg := R_SUBW;
  9687. S_L:
  9688. TargetSubReg := R_SUBD;
  9689. else
  9690. InternalError(2021051002);
  9691. end;
  9692. if TargetSize <> MaxSize then
  9693. begin
  9694. { Update the register to its new size }
  9695. setsubreg(ThisReg, TargetSubReg);
  9696. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9697. taicpu(hp1).oper[1]^.reg := ThisReg;
  9698. taicpu(hp1).opsize := TargetSize;
  9699. { Convert the input MOVZX to a MOV if necessary }
  9700. AdjustInitialLoadAndSize;
  9701. if (InstrMax >= 0) then
  9702. begin
  9703. for Index := 0 to InstrMax do
  9704. begin
  9705. { If p_removed is true, then the original MOV/Z was removed
  9706. and removing the AND instruction may not be safe if it
  9707. appears first }
  9708. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9709. InternalError(2020112311);
  9710. if InstrList[Index].oper[0]^.typ = top_reg then
  9711. InstrList[Index].oper[0]^.reg := ThisReg;
  9712. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9713. InstrList[Index].opsize := MinSize;
  9714. end;
  9715. end;
  9716. Result := True;
  9717. end;
  9718. Exit;
  9719. end;
  9720. end;
  9721. A_SETcc:
  9722. begin
  9723. { This allows this Movx optimisation to work through the SETcc instructions
  9724. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9725. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9726. skip over these SETcc instructions). }
  9727. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9728. { Of course, break out if the current register is used }
  9729. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9730. Break
  9731. else
  9732. { We must use Continue so the instruction doesn't get added
  9733. to InstrList }
  9734. Continue;
  9735. end;
  9736. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9737. begin
  9738. if
  9739. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9740. { Has to be an exact match on the register }
  9741. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9742. (
  9743. (
  9744. (taicpu(hp1).oper[0]^.typ = top_const) and
  9745. (
  9746. (
  9747. (taicpu(hp1).opcode = A_SHL) and
  9748. (
  9749. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9750. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9751. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9752. )
  9753. ) or (
  9754. (taicpu(hp1).opcode <> A_SHL) and
  9755. (
  9756. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9757. { Is it in the negative range? }
  9758. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9759. )
  9760. )
  9761. )
  9762. ) or (
  9763. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9764. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9765. )
  9766. ) then
  9767. Break;
  9768. { Only process OR and XOR if there are only bitwise operations,
  9769. since otherwise they can too easily fool the data flow
  9770. analysis (they can cause non-linear behaviour) }
  9771. case taicpu(hp1).opcode of
  9772. A_ADD:
  9773. begin
  9774. if OrXorUsed then
  9775. { Too high a risk of non-linear behaviour that breaks DFA here }
  9776. Break
  9777. else
  9778. BitwiseOnly := False;
  9779. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9780. begin
  9781. TestValMin := TestValMin * 2;
  9782. TestValMax := TestValMax * 2;
  9783. TestValSignedMax := TestValSignedMax * 2;
  9784. end
  9785. else
  9786. begin
  9787. WorkingValue := taicpu(hp1).oper[0]^.val;
  9788. TestValMin := TestValMin + WorkingValue;
  9789. TestValMax := TestValMax + WorkingValue;
  9790. TestValSignedMax := TestValSignedMax + WorkingValue;
  9791. end;
  9792. end;
  9793. A_SUB:
  9794. begin
  9795. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9796. begin
  9797. TestValMin := 0;
  9798. TestValMax := 0;
  9799. TestValSignedMax := 0;
  9800. end
  9801. else
  9802. begin
  9803. if OrXorUsed then
  9804. { Too high a risk of non-linear behaviour that breaks DFA here }
  9805. Break
  9806. else
  9807. BitwiseOnly := False;
  9808. WorkingValue := taicpu(hp1).oper[0]^.val;
  9809. TestValMin := TestValMin - WorkingValue;
  9810. TestValMax := TestValMax - WorkingValue;
  9811. TestValSignedMax := TestValSignedMax - WorkingValue;
  9812. end;
  9813. end;
  9814. A_AND:
  9815. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9816. begin
  9817. { we might be able to go smaller if AND appears first }
  9818. if InstrMax = -1 then
  9819. case MinSize of
  9820. S_B:
  9821. ;
  9822. S_W:
  9823. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9824. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9825. begin
  9826. TryShiftDown := S_B;
  9827. TryShiftDownLimit := $FF;
  9828. end;
  9829. S_L:
  9830. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9831. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9832. begin
  9833. TryShiftDown := S_B;
  9834. TryShiftDownLimit := $FF;
  9835. end
  9836. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9837. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9838. begin
  9839. TryShiftDown := S_W;
  9840. TryShiftDownLimit := $FFFF;
  9841. end;
  9842. else
  9843. InternalError(2020112320);
  9844. end;
  9845. WorkingValue := taicpu(hp1).oper[0]^.val;
  9846. TestValMin := TestValMin and WorkingValue;
  9847. TestValMax := TestValMax and WorkingValue;
  9848. TestValSignedMax := TestValSignedMax and WorkingValue;
  9849. end;
  9850. A_OR:
  9851. begin
  9852. if not BitwiseOnly then
  9853. Break;
  9854. OrXorUsed := True;
  9855. WorkingValue := taicpu(hp1).oper[0]^.val;
  9856. TestValMin := TestValMin or WorkingValue;
  9857. TestValMax := TestValMax or WorkingValue;
  9858. TestValSignedMax := TestValSignedMax or WorkingValue;
  9859. end;
  9860. A_XOR:
  9861. begin
  9862. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9863. begin
  9864. TestValMin := 0;
  9865. TestValMax := 0;
  9866. TestValSignedMax := 0;
  9867. end
  9868. else
  9869. begin
  9870. if not BitwiseOnly then
  9871. Break;
  9872. OrXorUsed := True;
  9873. WorkingValue := taicpu(hp1).oper[0]^.val;
  9874. TestValMin := TestValMin xor WorkingValue;
  9875. TestValMax := TestValMax xor WorkingValue;
  9876. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9877. end;
  9878. end;
  9879. A_SHL:
  9880. begin
  9881. BitwiseOnly := False;
  9882. WorkingValue := taicpu(hp1).oper[0]^.val;
  9883. TestValMin := TestValMin shl WorkingValue;
  9884. TestValMax := TestValMax shl WorkingValue;
  9885. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9886. end;
  9887. A_SHR,
  9888. { The first instruction was MOVZX, so the value won't be negative }
  9889. A_SAR:
  9890. begin
  9891. if InstrMax <> -1 then
  9892. BitwiseOnly := False
  9893. else
  9894. { we might be able to go smaller if SHR appears first }
  9895. case MinSize of
  9896. S_B:
  9897. ;
  9898. S_W:
  9899. if (taicpu(hp1).oper[0]^.val >= 8) then
  9900. begin
  9901. TryShiftDown := S_B;
  9902. TryShiftDownLimit := $FF;
  9903. TryShiftDownSignedLimit := $7F;
  9904. TryShiftDownSignedLimitLower := -128;
  9905. end;
  9906. S_L:
  9907. if (taicpu(hp1).oper[0]^.val >= 24) then
  9908. begin
  9909. TryShiftDown := S_B;
  9910. TryShiftDownLimit := $FF;
  9911. TryShiftDownSignedLimit := $7F;
  9912. TryShiftDownSignedLimitLower := -128;
  9913. end
  9914. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9915. begin
  9916. TryShiftDown := S_W;
  9917. TryShiftDownLimit := $FFFF;
  9918. TryShiftDownSignedLimit := $7FFF;
  9919. TryShiftDownSignedLimitLower := -32768;
  9920. end;
  9921. else
  9922. InternalError(2020112321);
  9923. end;
  9924. WorkingValue := taicpu(hp1).oper[0]^.val;
  9925. if taicpu(hp1).opcode = A_SAR then
  9926. begin
  9927. TestValMin := SarInt64(TestValMin, WorkingValue);
  9928. TestValMax := SarInt64(TestValMax, WorkingValue);
  9929. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9930. end
  9931. else
  9932. begin
  9933. TestValMin := TestValMin shr WorkingValue;
  9934. TestValMax := TestValMax shr WorkingValue;
  9935. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9936. end;
  9937. end;
  9938. else
  9939. InternalError(2020112303);
  9940. end;
  9941. end;
  9942. (*
  9943. A_IMUL:
  9944. case taicpu(hp1).ops of
  9945. 2:
  9946. begin
  9947. if not MatchOpType(hp1, top_reg, top_reg) or
  9948. { Has to be an exact match on the register }
  9949. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9950. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9951. Break;
  9952. TestValMin := TestValMin * TestValMin;
  9953. TestValMax := TestValMax * TestValMax;
  9954. TestValSignedMax := TestValSignedMax * TestValMax;
  9955. end;
  9956. 3:
  9957. begin
  9958. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9959. { Has to be an exact match on the register }
  9960. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9961. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9962. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9963. { Is it in the negative range? }
  9964. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9965. Break;
  9966. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9967. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9968. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9969. end;
  9970. else
  9971. Break;
  9972. end;
  9973. A_IDIV:
  9974. case taicpu(hp1).ops of
  9975. 3:
  9976. begin
  9977. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9978. { Has to be an exact match on the register }
  9979. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9980. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9981. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9982. { Is it in the negative range? }
  9983. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9984. Break;
  9985. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9986. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9987. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9988. end;
  9989. else
  9990. Break;
  9991. end;
  9992. *)
  9993. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9994. begin
  9995. { If there are no instructions in between, then we might be able to make a saving }
  9996. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9997. Break;
  9998. { We have something like:
  9999. movzbw %dl,%dx
  10000. ...
  10001. movswl %dx,%edx
  10002. Change the latter to a zero-extension then enter the
  10003. A_MOVZX case branch.
  10004. }
  10005. {$ifdef x86_64}
  10006. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10007. begin
  10008. { this becomes a zero extension from 32-bit to 64-bit, but
  10009. the upper 32 bits are already zero, so just delete the
  10010. instruction }
  10011. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10012. RemoveInstruction(hp1);
  10013. Result := True;
  10014. Exit;
  10015. end
  10016. else
  10017. {$endif x86_64}
  10018. begin
  10019. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10020. taicpu(hp1).opcode := A_MOVZX;
  10021. {$ifdef x86_64}
  10022. case taicpu(hp1).opsize of
  10023. S_BQ:
  10024. begin
  10025. taicpu(hp1).opsize := S_BL;
  10026. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10027. end;
  10028. S_WQ:
  10029. begin
  10030. taicpu(hp1).opsize := S_WL;
  10031. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10032. end;
  10033. S_LQ:
  10034. begin
  10035. taicpu(hp1).opcode := A_MOV;
  10036. taicpu(hp1).opsize := S_L;
  10037. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10038. { In this instance, we need to break out because the
  10039. instruction is no longer MOVZX or MOVSXD }
  10040. Result := True;
  10041. Exit;
  10042. end;
  10043. else
  10044. ;
  10045. end;
  10046. {$endif x86_64}
  10047. Result := CompressInstructions;
  10048. Exit;
  10049. end;
  10050. end;
  10051. A_MOVZX:
  10052. begin
  10053. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10054. Break;
  10055. if (InstrMax = -1) then
  10056. begin
  10057. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10058. begin
  10059. { Optimise around i40003 }
  10060. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10061. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10062. {$ifndef x86_64}
  10063. and (
  10064. (taicpu(p).oper[0]^.typ <> top_reg) or
  10065. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10066. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10067. )
  10068. {$endif not x86_64}
  10069. then
  10070. begin
  10071. if (taicpu(p).oper[0]^.typ = top_reg) then
  10072. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10073. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10074. taicpu(p).opsize := S_BL;
  10075. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10076. RemoveInstruction(hp1);
  10077. Result := True;
  10078. Exit;
  10079. end;
  10080. end
  10081. else
  10082. begin
  10083. { Will return false if the second parameter isn't ThisReg
  10084. (can happen on -O2 and under) }
  10085. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10086. begin
  10087. { The two MOVZX instructions are adjacent, so remove the first one }
  10088. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10089. RemoveCurrentP(p);
  10090. Result := True;
  10091. Exit;
  10092. end;
  10093. Break;
  10094. end;
  10095. end;
  10096. Result := CompressInstructions;
  10097. Exit;
  10098. end;
  10099. else
  10100. { This includes ADC, SBB and IDIV }
  10101. Break;
  10102. end;
  10103. if not CheckOverflowConditions then
  10104. Break;
  10105. { Contains highest index (so instruction count - 1) }
  10106. Inc(InstrMax);
  10107. if InstrMax > High(InstrList) then
  10108. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10109. InstrList[InstrMax] := taicpu(hp1);
  10110. end;
  10111. end;
  10112. {$pop}
  10113. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10114. var
  10115. hp1 : tai;
  10116. begin
  10117. Result:=false;
  10118. if (taicpu(p).ops >= 2) and
  10119. ((taicpu(p).oper[0]^.typ = top_const) or
  10120. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10121. (taicpu(p).oper[1]^.typ = top_reg) and
  10122. ((taicpu(p).ops = 2) or
  10123. ((taicpu(p).oper[2]^.typ = top_reg) and
  10124. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10125. GetLastInstruction(p,hp1) and
  10126. MatchInstruction(hp1,A_MOV,[]) and
  10127. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10128. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10129. begin
  10130. TransferUsedRegs(TmpUsedRegs);
  10131. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10132. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10133. { change
  10134. mov reg1,reg2
  10135. imul y,reg2 to imul y,reg1,reg2 }
  10136. begin
  10137. taicpu(p).ops := 3;
  10138. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10139. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10140. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10141. RemoveInstruction(hp1);
  10142. result:=true;
  10143. end;
  10144. end;
  10145. end;
  10146. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10147. var
  10148. ThisLabel: TAsmLabel;
  10149. begin
  10150. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10151. ThisLabel.decrefs;
  10152. taicpu(p).condition := C_None;
  10153. taicpu(p).opcode := A_RET;
  10154. taicpu(p).is_jmp := false;
  10155. taicpu(p).ops := taicpu(ret_p).ops;
  10156. case taicpu(ret_p).ops of
  10157. 0:
  10158. taicpu(p).clearop(0);
  10159. 1:
  10160. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10161. else
  10162. internalerror(2016041301);
  10163. end;
  10164. { If the original label is now dead, it might turn out that the label
  10165. immediately follows p. As a result, everything beyond it, which will
  10166. be just some final register configuration and a RET instruction, is
  10167. now dead code. [Kit] }
  10168. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10169. running RemoveDeadCodeAfterJump for each RET instruction, because
  10170. this optimisation rarely happens and most RETs appear at the end of
  10171. routines where there is nothing that can be stripped. [Kit] }
  10172. if not ThisLabel.is_used then
  10173. RemoveDeadCodeAfterJump(p);
  10174. end;
  10175. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10176. var
  10177. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10178. Unconditional, PotentialModified: Boolean;
  10179. OperPtr: POper;
  10180. NewRef: TReference;
  10181. InstrList: array of taicpu;
  10182. InstrMax, Index: Integer;
  10183. const
  10184. {$ifdef DEBUG_AOPTCPU}
  10185. SNoFlags: shortstring = ' so the flags aren''t modified';
  10186. {$else DEBUG_AOPTCPU}
  10187. SNoFlags = '';
  10188. {$endif DEBUG_AOPTCPU}
  10189. begin
  10190. Result:=false;
  10191. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10192. begin
  10193. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10194. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10195. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10196. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10197. GetNextInstruction(hp1, hp2) and
  10198. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10199. { Change from: To:
  10200. set(C) %reg j(~C) label
  10201. test %reg,%reg/cmp $0,%reg
  10202. je label
  10203. set(C) %reg j(C) label
  10204. test %reg,%reg/cmp $0,%reg
  10205. jne label
  10206. (Also do something similar with sete/setne instead of je/jne)
  10207. }
  10208. begin
  10209. { Before we do anything else, we need to check the instructions
  10210. in between SETcc and TEST to make sure they don't modify the
  10211. FLAGS register - if -O2 or under, there won't be any
  10212. instructions between SET and TEST }
  10213. TransferUsedRegs(TmpUsedRegs);
  10214. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10215. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10216. begin
  10217. next := p;
  10218. SetLength(InstrList, 0);
  10219. InstrMax := -1;
  10220. PotentialModified := False;
  10221. { Make a note of every instruction that modifies the FLAGS
  10222. register }
  10223. while GetNextInstruction(next, next) and (next <> hp1) do
  10224. begin
  10225. if next.typ <> ait_instruction then
  10226. { GetNextInstructionUsingReg should have returned False }
  10227. InternalError(2021051701);
  10228. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10229. begin
  10230. case taicpu(next).opcode of
  10231. A_SETcc,
  10232. A_CMOVcc,
  10233. A_Jcc:
  10234. begin
  10235. if PotentialModified then
  10236. { Not safe because the flags were modified earlier }
  10237. Exit
  10238. else
  10239. { Condition is the same as the initial SETcc, so this is safe
  10240. (don't add to instruction list though) }
  10241. Continue;
  10242. end;
  10243. A_ADD:
  10244. begin
  10245. if (taicpu(next).opsize = S_B) or
  10246. { LEA doesn't support 8-bit operands }
  10247. (taicpu(next).oper[1]^.typ <> top_reg) or
  10248. { Must write to a register }
  10249. (taicpu(next).oper[0]^.typ = top_ref) then
  10250. { Require a constant or a register }
  10251. Exit;
  10252. PotentialModified := True;
  10253. end;
  10254. A_SUB:
  10255. begin
  10256. if (taicpu(next).opsize = S_B) or
  10257. { LEA doesn't support 8-bit operands }
  10258. (taicpu(next).oper[1]^.typ <> top_reg) or
  10259. { Must write to a register }
  10260. (taicpu(next).oper[0]^.typ <> top_const) or
  10261. (taicpu(next).oper[0]^.val = $80000000) then
  10262. { Can't subtract a register with LEA - also
  10263. check that the value isn't -2^31, as this
  10264. can't be negated }
  10265. Exit;
  10266. PotentialModified := True;
  10267. end;
  10268. A_SAL,
  10269. A_SHL:
  10270. begin
  10271. if (taicpu(next).opsize = S_B) or
  10272. { LEA doesn't support 8-bit operands }
  10273. (taicpu(next).oper[1]^.typ <> top_reg) or
  10274. { Must write to a register }
  10275. (taicpu(next).oper[0]^.typ <> top_const) or
  10276. (taicpu(next).oper[0]^.val < 0) or
  10277. (taicpu(next).oper[0]^.val > 3) then
  10278. Exit;
  10279. PotentialModified := True;
  10280. end;
  10281. A_IMUL:
  10282. begin
  10283. if (taicpu(next).ops <> 3) or
  10284. (taicpu(next).oper[1]^.typ <> top_reg) or
  10285. { Must write to a register }
  10286. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10287. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10288. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10289. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10290. Exit
  10291. else
  10292. PotentialModified := True;
  10293. end;
  10294. else
  10295. { Don't know how to change this, so abort }
  10296. Exit;
  10297. end;
  10298. { Contains highest index (so instruction count - 1) }
  10299. Inc(InstrMax);
  10300. if InstrMax > High(InstrList) then
  10301. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10302. InstrList[InstrMax] := taicpu(next);
  10303. end;
  10304. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10305. end;
  10306. if not Assigned(next) or (next <> hp1) then
  10307. { It should be equal to hp1 }
  10308. InternalError(2021051702);
  10309. { Cycle through each instruction and check to see if we can
  10310. change them to versions that don't modify the flags }
  10311. if (InstrMax >= 0) then
  10312. begin
  10313. for Index := 0 to InstrMax do
  10314. case InstrList[Index].opcode of
  10315. A_ADD:
  10316. begin
  10317. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10318. InstrList[Index].opcode := A_LEA;
  10319. reference_reset(NewRef, 1, []);
  10320. NewRef.base := InstrList[Index].oper[1]^.reg;
  10321. if InstrList[Index].oper[0]^.typ = top_reg then
  10322. begin
  10323. NewRef.index := InstrList[Index].oper[0]^.reg;
  10324. NewRef.scalefactor := 1;
  10325. end
  10326. else
  10327. NewRef.offset := InstrList[Index].oper[0]^.val;
  10328. InstrList[Index].loadref(0, NewRef);
  10329. end;
  10330. A_SUB:
  10331. begin
  10332. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10333. InstrList[Index].opcode := A_LEA;
  10334. reference_reset(NewRef, 1, []);
  10335. NewRef.base := InstrList[Index].oper[1]^.reg;
  10336. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10337. InstrList[Index].loadref(0, NewRef);
  10338. end;
  10339. A_SHL,
  10340. A_SAL:
  10341. begin
  10342. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10343. InstrList[Index].opcode := A_LEA;
  10344. reference_reset(NewRef, 1, []);
  10345. NewRef.index := InstrList[Index].oper[1]^.reg;
  10346. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10347. InstrList[Index].loadref(0, NewRef);
  10348. end;
  10349. A_IMUL:
  10350. begin
  10351. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10352. InstrList[Index].opcode := A_LEA;
  10353. reference_reset(NewRef, 1, []);
  10354. NewRef.index := InstrList[Index].oper[1]^.reg;
  10355. case InstrList[Index].oper[0]^.val of
  10356. 2, 4, 8:
  10357. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10358. else {3, 5 and 9}
  10359. begin
  10360. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10361. NewRef.base := InstrList[Index].oper[1]^.reg;
  10362. end;
  10363. end;
  10364. InstrList[Index].loadref(0, NewRef);
  10365. end;
  10366. else
  10367. InternalError(2021051710);
  10368. end;
  10369. end;
  10370. { Mark the FLAGS register as used across this whole block }
  10371. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10372. end;
  10373. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10374. JumpC := taicpu(hp2).condition;
  10375. Unconditional := False;
  10376. if conditions_equal(JumpC, C_E) then
  10377. SetC := inverse_cond(taicpu(p).condition)
  10378. else if conditions_equal(JumpC, C_NE) then
  10379. SetC := taicpu(p).condition
  10380. else
  10381. { We've got something weird here (and inefficent) }
  10382. begin
  10383. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10384. SetC := C_NONE;
  10385. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10386. if condition_in(C_AE, JumpC) then
  10387. Unconditional := True
  10388. else
  10389. { Not sure what to do with this jump - drop out }
  10390. Exit;
  10391. end;
  10392. RemoveInstruction(hp1);
  10393. if Unconditional then
  10394. MakeUnconditional(taicpu(hp2))
  10395. else
  10396. begin
  10397. if SetC = C_NONE then
  10398. InternalError(2018061402);
  10399. taicpu(hp2).SetCondition(SetC);
  10400. end;
  10401. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10402. TmpUsedRegs }
  10403. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10404. begin
  10405. RemoveCurrentp(p, hp2);
  10406. if taicpu(hp2).opcode = A_SETcc then
  10407. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10408. else
  10409. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10410. end
  10411. else
  10412. if taicpu(hp2).opcode = A_SETcc then
  10413. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10414. else
  10415. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10416. Result := True;
  10417. end
  10418. else if
  10419. { Make sure the instructions are adjacent }
  10420. (
  10421. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10422. GetNextInstruction(p, hp1)
  10423. ) and
  10424. MatchInstruction(hp1, A_MOV, [S_B]) and
  10425. { Writing to memory is allowed }
  10426. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10427. begin
  10428. {
  10429. Watch out for sequences such as:
  10430. set(c)b %regb
  10431. movb %regb,(ref)
  10432. movb $0,1(ref)
  10433. movb $0,2(ref)
  10434. movb $0,3(ref)
  10435. Much more efficient to turn it into:
  10436. movl $0,%regl
  10437. set(c)b %regb
  10438. movl %regl,(ref)
  10439. Or:
  10440. set(c)b %regb
  10441. movzbl %regb,%regl
  10442. movl %regl,(ref)
  10443. }
  10444. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10445. GetNextInstruction(hp1, hp2) and
  10446. MatchInstruction(hp2, A_MOV, [S_B]) and
  10447. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10448. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10449. begin
  10450. { Don't do anything else except set Result to True }
  10451. end
  10452. else
  10453. begin
  10454. if taicpu(p).oper[0]^.typ = top_reg then
  10455. begin
  10456. TransferUsedRegs(TmpUsedRegs);
  10457. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10458. end;
  10459. { If it's not a register, it's a memory address }
  10460. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10461. begin
  10462. { Even if the register is still in use, we can minimise the
  10463. pipeline stall by changing the MOV into another SETcc. }
  10464. taicpu(hp1).opcode := A_SETcc;
  10465. taicpu(hp1).condition := taicpu(p).condition;
  10466. if taicpu(hp1).oper[1]^.typ = top_ref then
  10467. begin
  10468. { Swapping the operand pointers like this is probably a
  10469. bit naughty, but it is far faster than using loadoper
  10470. to transfer the reference from oper[1] to oper[0] if
  10471. you take into account the extra procedure calls and
  10472. the memory allocation and deallocation required }
  10473. OperPtr := taicpu(hp1).oper[1];
  10474. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10475. taicpu(hp1).oper[0] := OperPtr;
  10476. end
  10477. else
  10478. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10479. taicpu(hp1).clearop(1);
  10480. taicpu(hp1).ops := 1;
  10481. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10482. end
  10483. else
  10484. begin
  10485. if taicpu(hp1).oper[1]^.typ = top_reg then
  10486. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10487. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10488. RemoveInstruction(hp1);
  10489. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10490. end
  10491. end;
  10492. Result := True;
  10493. end;
  10494. end;
  10495. end;
  10496. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10497. var
  10498. hp1: tai;
  10499. Count: Integer;
  10500. OrigLabel: TAsmLabel;
  10501. begin
  10502. result := False;
  10503. { Sometimes, the optimisations below can permit this }
  10504. RemoveDeadCodeAfterJump(p);
  10505. 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
  10506. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10507. begin
  10508. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10509. { Also a side-effect of optimisations }
  10510. if CollapseZeroDistJump(p, OrigLabel) then
  10511. begin
  10512. Result := True;
  10513. Exit;
  10514. end;
  10515. hp1 := GetLabelWithSym(OrigLabel);
  10516. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10517. begin
  10518. if taicpu(hp1).opcode = A_RET then
  10519. begin
  10520. {
  10521. change
  10522. jmp .L1
  10523. ...
  10524. .L1:
  10525. ret
  10526. into
  10527. ret
  10528. }
  10529. begin
  10530. ConvertJumpToRET(p, hp1);
  10531. result:=true;
  10532. end;
  10533. end
  10534. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10535. not (cs_opt_size in current_settings.optimizerswitches) and
  10536. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10537. begin
  10538. Result := True;
  10539. Exit;
  10540. end;
  10541. end;
  10542. end;
  10543. end;
  10544. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10545. begin
  10546. Result := assigned(p) and
  10547. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10548. (taicpu(p).oper[1]^.typ = top_reg) and
  10549. (
  10550. (taicpu(p).oper[0]^.typ = top_reg) or
  10551. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10552. it is not expected that this can cause a seg. violation }
  10553. (
  10554. (taicpu(p).oper[0]^.typ = top_ref) and
  10555. { TODO: Can we detect which references become constants at this
  10556. stage so we don't have to do a blanket ban? }
  10557. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10558. (
  10559. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10560. (
  10561. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10562. not RefModified and
  10563. { If the reference also appears in the condition, then we know it's safe, otherwise
  10564. any kind of access violation would have occurred already }
  10565. Assigned(cond_p) and
  10566. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10567. (cond_p.typ = ait_instruction) and
  10568. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10569. { Just consider 2-operand comparison instructions for now to be safe }
  10570. (taicpu(cond_p).ops = 2) and
  10571. (
  10572. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10573. (
  10574. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10575. { Don't risk identical registers but different offsets, as we may have constructs
  10576. such as buffer streams with things like length fields that indicate whether
  10577. any more data follows. And there are probably some contrived examples where
  10578. writing to offsets behind the one being read also lead to access violations }
  10579. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10580. (
  10581. { Check that we're not modifying a register that appears in the reference }
  10582. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10583. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10584. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10585. )
  10586. )
  10587. )
  10588. )
  10589. )
  10590. )
  10591. );
  10592. end;
  10593. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10594. begin
  10595. { Update integer registers, ignoring deallocations }
  10596. repeat
  10597. while assigned(p) and
  10598. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10599. (p.typ = ait_label) or
  10600. ((p.typ = ait_marker) and
  10601. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10602. p := tai(p.next);
  10603. while assigned(p) and
  10604. (p.typ=ait_RegAlloc) Do
  10605. begin
  10606. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10607. begin
  10608. case tai_regalloc(p).ratype of
  10609. ra_alloc :
  10610. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10611. else
  10612. ;
  10613. end;
  10614. end;
  10615. p := tai(p.next);
  10616. end;
  10617. until not(assigned(p)) or
  10618. (not(p.typ in SkipInstr) and
  10619. not((p.typ = ait_label) and
  10620. labelCanBeSkipped(tai_label(p))));
  10621. end;
  10622. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10623. var
  10624. hp1,hp2: tai;
  10625. carryadd_opcode : TAsmOp;
  10626. symbol: TAsmSymbol;
  10627. increg, tmpreg: TRegister;
  10628. RefModified: Boolean;
  10629. {$ifndef i8086}
  10630. { Code and variables specific to CMOV optimisations }
  10631. hp3,hp4,hp5,
  10632. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10633. l, c, w, x : Longint;
  10634. condition, second_condition : TAsmCond;
  10635. FoundMatchingJump, RegMatch: Boolean;
  10636. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10637. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10638. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10639. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10640. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10641. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10642. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10643. new register to store the constant }
  10644. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10645. var
  10646. RegSize: TSubRegister;
  10647. CurrentVal: TCGInt;
  10648. ANewReg: TRegister;
  10649. X: ShortInt;
  10650. begin
  10651. Result := False;
  10652. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10653. Exit;
  10654. if StoredCount >= MAX_CMOV_REGISTERS then
  10655. { Arrays are full }
  10656. Exit;
  10657. { Remember that CMOV can't encode 8-bit registers }
  10658. case taicpu(p).opsize of
  10659. S_W:
  10660. RegSize := R_SUBW;
  10661. S_L:
  10662. RegSize := R_SUBD;
  10663. {$ifdef x86_64}
  10664. S_Q:
  10665. RegSize := R_SUBQ;
  10666. {$endif x86_64}
  10667. else
  10668. InternalError(2021100401);
  10669. end;
  10670. { See if the value has already been reserved for another CMOV instruction }
  10671. CurrentVal := taicpu(p).oper[0]^.val;
  10672. for X := 0 to StoredCount - 1 do
  10673. if ConstVals[X] = CurrentVal then
  10674. begin
  10675. ConstRegs[StoredCount] := ConstRegs[X];
  10676. ConstSizes[StoredCount] := RegSize;
  10677. ConstVals[StoredCount] := CurrentVal;
  10678. Result := True;
  10679. Inc(StoredCount);
  10680. { Don't increase CMOVCount this time, since we're re-using a register }
  10681. Exit;
  10682. end;
  10683. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10684. if ANewReg = NR_NO then
  10685. { No free registers }
  10686. Exit;
  10687. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10688. up vying for the same register }
  10689. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10690. ConstRegs[StoredCount] := ANewReg;
  10691. ConstSizes[StoredCount] := RegSize;
  10692. ConstVals[StoredCount] := CurrentVal;
  10693. Inc(StoredCount);
  10694. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10695. MOV required adds complexity and will cause diminishing returns
  10696. sooner than normal. This is more of an approximate weighting than
  10697. anything else. }
  10698. Inc(CMOVCount);
  10699. Result := True;
  10700. end;
  10701. {$endif i8086}
  10702. begin
  10703. result:=false;
  10704. if GetNextInstruction(p,hp1) then
  10705. begin
  10706. if (hp1.typ=ait_label) then
  10707. begin
  10708. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10709. Exit;
  10710. end
  10711. else if (hp1.typ<>ait_instruction) then
  10712. Exit;
  10713. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10714. if (
  10715. (
  10716. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10717. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10718. (Taicpu(hp1).oper[0]^.val=1)
  10719. ) or
  10720. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10721. ) and
  10722. GetNextInstruction(hp1,hp2) and
  10723. SkipAligns(hp2, hp2) and
  10724. (hp2.typ = ait_label) and
  10725. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10726. { jb @@1 cmc
  10727. inc/dec operand --> adc/sbb operand,0
  10728. @@1:
  10729. ... and ...
  10730. jnb @@1
  10731. inc/dec operand --> adc/sbb operand,0
  10732. @@1: }
  10733. begin
  10734. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10735. begin
  10736. case taicpu(hp1).opcode of
  10737. A_INC,
  10738. A_ADD:
  10739. carryadd_opcode:=A_ADC;
  10740. A_DEC,
  10741. A_SUB:
  10742. carryadd_opcode:=A_SBB;
  10743. else
  10744. InternalError(2021011001);
  10745. end;
  10746. Taicpu(p).clearop(0);
  10747. Taicpu(p).ops:=0;
  10748. Taicpu(p).is_jmp:=false;
  10749. Taicpu(p).opcode:=A_CMC;
  10750. Taicpu(p).condition:=C_NONE;
  10751. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10752. Taicpu(hp1).ops:=2;
  10753. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10754. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10755. else
  10756. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10757. Taicpu(hp1).loadconst(0,0);
  10758. Taicpu(hp1).opcode:=carryadd_opcode;
  10759. result:=true;
  10760. exit;
  10761. end
  10762. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10763. begin
  10764. case taicpu(hp1).opcode of
  10765. A_INC,
  10766. A_ADD:
  10767. carryadd_opcode:=A_ADC;
  10768. A_DEC,
  10769. A_SUB:
  10770. carryadd_opcode:=A_SBB;
  10771. else
  10772. InternalError(2021011002);
  10773. end;
  10774. Taicpu(hp1).ops:=2;
  10775. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10776. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10777. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10778. else
  10779. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10780. Taicpu(hp1).loadconst(0,0);
  10781. Taicpu(hp1).opcode:=carryadd_opcode;
  10782. RemoveCurrentP(p, hp1);
  10783. result:=true;
  10784. exit;
  10785. end
  10786. {
  10787. jcc @@1 setcc tmpreg
  10788. inc/dec/add/sub operand -> (movzx tmpreg)
  10789. @@1: add/sub tmpreg,operand
  10790. While this increases code size slightly, it makes the code much faster if the
  10791. jump is unpredictable
  10792. }
  10793. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10794. begin
  10795. { search for an available register which is volatile }
  10796. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10797. if increg <> NR_NO then
  10798. begin
  10799. { We don't need to check if tmpreg is in hp1 or not, because
  10800. it will be marked as in use at p (if not, this is
  10801. indictive of a compiler bug). }
  10802. TAsmLabel(symbol).decrefs;
  10803. Taicpu(p).clearop(0);
  10804. Taicpu(p).ops:=1;
  10805. Taicpu(p).is_jmp:=false;
  10806. Taicpu(p).opcode:=A_SETcc;
  10807. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10808. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10809. Taicpu(p).loadreg(0,increg);
  10810. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10811. begin
  10812. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10813. R_SUBW:
  10814. begin
  10815. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10816. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10817. end;
  10818. R_SUBD:
  10819. begin
  10820. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10821. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10822. end;
  10823. {$ifdef x86_64}
  10824. R_SUBQ:
  10825. begin
  10826. { MOVZX doesn't have a 64-bit variant, because
  10827. the 32-bit version implicitly zeroes the
  10828. upper 32-bits of the destination register }
  10829. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10830. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10831. setsubreg(tmpreg, R_SUBQ);
  10832. end;
  10833. {$endif x86_64}
  10834. else
  10835. Internalerror(2020030601);
  10836. end;
  10837. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10838. asml.InsertAfter(hp2,p);
  10839. end
  10840. else
  10841. tmpreg := increg;
  10842. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10843. begin
  10844. Taicpu(hp1).ops:=2;
  10845. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10846. end;
  10847. Taicpu(hp1).loadreg(0,tmpreg);
  10848. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10849. Result := True;
  10850. { p is no longer a Jcc instruction, so exit }
  10851. Exit;
  10852. end;
  10853. end;
  10854. end;
  10855. { Detect the following:
  10856. jmp<cond> @Lbl1
  10857. jmp @Lbl2
  10858. ...
  10859. @Lbl1:
  10860. ret
  10861. Change to:
  10862. jmp<inv_cond> @Lbl2
  10863. ret
  10864. }
  10865. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10866. begin
  10867. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10868. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10869. MatchInstruction(hp2,A_RET,[S_NO]) then
  10870. begin
  10871. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10872. { Change label address to that of the unconditional jump }
  10873. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10874. TAsmLabel(symbol).DecRefs;
  10875. taicpu(hp1).opcode := A_RET;
  10876. taicpu(hp1).is_jmp := false;
  10877. taicpu(hp1).ops := taicpu(hp2).ops;
  10878. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10879. case taicpu(hp2).ops of
  10880. 0:
  10881. taicpu(hp1).clearop(0);
  10882. 1:
  10883. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10884. else
  10885. internalerror(2016041302);
  10886. end;
  10887. end;
  10888. {$ifndef i8086}
  10889. end
  10890. {
  10891. convert
  10892. j<c> .L1
  10893. mov 1,reg
  10894. jmp .L2
  10895. .L1
  10896. mov 0,reg
  10897. .L2
  10898. into
  10899. mov 0,reg
  10900. set<not(c)> reg
  10901. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10902. would destroy the flag contents
  10903. }
  10904. else if MatchInstruction(hp1,A_MOV,[]) and
  10905. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10906. {$ifdef i386}
  10907. (
  10908. { Under i386, ESI, EDI, EBP and ESP
  10909. don't have an 8-bit representation }
  10910. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10911. ) and
  10912. {$endif i386}
  10913. (taicpu(hp1).oper[0]^.val=1) and
  10914. GetNextInstruction(hp1,hp2) and
  10915. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10916. GetNextInstruction(hp2,hp3) and
  10917. { skip align }
  10918. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10919. (hp3.typ=ait_label) and
  10920. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10921. (tai_label(hp3).labsym.getrefs=1) and
  10922. GetNextInstruction(hp3,hp4) and
  10923. MatchInstruction(hp4,A_MOV,[]) and
  10924. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10925. (taicpu(hp4).oper[0]^.val=0) and
  10926. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10927. GetNextInstruction(hp4,hp5) and
  10928. (hp5.typ=ait_label) and
  10929. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10930. (tai_label(hp5).labsym.getrefs=1) then
  10931. begin
  10932. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10933. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10934. { remove last label }
  10935. RemoveInstruction(hp5);
  10936. { remove second label }
  10937. RemoveInstruction(hp3);
  10938. { if align is present remove it }
  10939. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10940. RemoveInstruction(hp3);
  10941. { remove jmp }
  10942. RemoveInstruction(hp2);
  10943. if taicpu(hp1).opsize=S_B then
  10944. RemoveInstruction(hp1)
  10945. else
  10946. taicpu(hp1).loadconst(0,0);
  10947. taicpu(hp4).opcode:=A_SETcc;
  10948. taicpu(hp4).opsize:=S_B;
  10949. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10950. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10951. taicpu(hp4).opercnt:=1;
  10952. taicpu(hp4).ops:=1;
  10953. taicpu(hp4).freeop(1);
  10954. RemoveCurrentP(p);
  10955. Result:=true;
  10956. exit;
  10957. end
  10958. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10959. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10960. begin
  10961. { check for
  10962. jCC xxx
  10963. <several movs>
  10964. xxx:
  10965. Also spot:
  10966. Jcc xxx
  10967. <several movs>
  10968. jmp xxx
  10969. Change to:
  10970. <several cmovs with inverted condition>
  10971. jmp xxx (only for the 2nd case)
  10972. }
  10973. hp2 := p;
  10974. hp_lblxxx := hp1;
  10975. hp_flagalloc := nil;
  10976. hp_stop := nil;
  10977. FoundMatchingJump := False;
  10978. { Remember the first instruction in the first block of MOVs }
  10979. hpmov1 := hp1;
  10980. TransferUsedRegs(TmpUsedRegs);
  10981. while assigned(hp_lblxxx) and
  10982. { stop on labels }
  10983. (hp_lblxxx.typ <> ait_label) do
  10984. begin
  10985. { Keep track of all integer registers that are used }
  10986. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10987. if hp_lblxxx.typ = ait_instruction then
  10988. begin
  10989. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10990. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10991. begin
  10992. hp_stop := hp_lblxxx;
  10993. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10994. begin
  10995. { We found Jcc xxx; <several movs>; Jmp xxx }
  10996. FoundMatchingJump := True;
  10997. Break;
  10998. end;
  10999. { If it's not the jump we're looking for, it's
  11000. possibly the "if..else" variant }
  11001. end
  11002. { Check to see if we have a valid MOV instruction instead }
  11003. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11004. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11005. Break
  11006. else
  11007. { This will be a valid MOV }
  11008. hp_stop := hp_lblxxx;
  11009. end;
  11010. hp2 := hp_lblxxx;
  11011. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11012. end;
  11013. { Just make sure the last MOV is included if there's no jump }
  11014. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11015. hp_stop := hp_lblxxx;
  11016. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11017. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11018. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11019. jmp yyy; xxx:; movs; yyy:" variation }
  11020. if assigned(hp_lblxxx) and
  11021. (
  11022. { If we found JMP xxx, we don't actually need a label
  11023. (hp_lblxxx is the JMP instruction instead) }
  11024. FoundMatchingJump or
  11025. { Make sure we actually have the right label }
  11026. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11027. ) then
  11028. begin
  11029. { Use TmpUsedRegs to track registers that we reserve }
  11030. { When allocating temporary registers, try to look one
  11031. instruction back, as defining them before a CMP or TEST
  11032. instruction will be faster, and also avoid picking a
  11033. register that was only just deallocated }
  11034. if GetLastInstruction(p, hp_prev) and
  11035. 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
  11036. begin
  11037. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11038. for l := 0 to 1 do
  11039. with taicpu(hp_prev).oper[l]^ do
  11040. case typ of
  11041. top_reg:
  11042. if getregtype(reg) = R_INTREGISTER then
  11043. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11044. top_ref:
  11045. begin
  11046. if
  11047. {$ifdef x86_64}
  11048. (ref^.base <> NR_RIP) and
  11049. {$endif x86_64}
  11050. (ref^.base <> NR_NO) then
  11051. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11052. if (ref^.index <> NR_NO) then
  11053. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11054. end
  11055. else
  11056. ;
  11057. end;
  11058. { When inserting instructions before hp_prev, try to insert
  11059. them before the allocation of the FLAGS register }
  11060. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11061. { If not found, set it equal to hp_prev so it's something sensible }
  11062. hp_flagalloc := hp_prev;
  11063. hp_prev2 := nil;
  11064. { When dealing with a comparison against zero, take
  11065. note of the instruction before it to see if we can
  11066. move instructions further back in order to benefit
  11067. PostPeepholeOptTestOr.
  11068. }
  11069. if (
  11070. (
  11071. (taicpu(hp_prev).opcode = A_CMP) and
  11072. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11073. ) or
  11074. (
  11075. (taicpu(hp_prev).opcode = A_TEST) and
  11076. (
  11077. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11078. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11079. )
  11080. )
  11081. ) and
  11082. GetLastInstruction(hp_prev, hp_prev2) then
  11083. begin
  11084. if (hp_prev2.typ = ait_instruction) and
  11085. { These instructions set the zero flag if the result is zero }
  11086. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11087. begin
  11088. { Also mark all the registers in this previous instruction
  11089. as 'in use', even if they've just been deallocated }
  11090. for l := 0 to 1 do
  11091. with taicpu(hp_prev2).oper[l]^ do
  11092. case typ of
  11093. top_reg:
  11094. if getregtype(reg) = R_INTREGISTER then
  11095. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11096. top_ref:
  11097. begin
  11098. if
  11099. {$ifdef x86_64}
  11100. (ref^.base <> NR_RIP) and
  11101. {$endif x86_64}
  11102. (ref^.base <> NR_NO) then
  11103. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11104. if (ref^.index <> NR_NO) then
  11105. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11106. end
  11107. else
  11108. ;
  11109. end;
  11110. end
  11111. else
  11112. { Unsuitable instruction }
  11113. hp_prev2 := nil;
  11114. end;
  11115. end
  11116. else
  11117. begin
  11118. hp_prev := p;
  11119. { When inserting instructions before hp_prev, try to insert
  11120. them before the allocation of the FLAGS register }
  11121. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11122. { If not found, set it equal to p so it's something sensible }
  11123. hp_flagalloc := p;
  11124. hp_prev2 := nil;
  11125. end;
  11126. l := 0;
  11127. c := 0;
  11128. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11129. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11130. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11131. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11132. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11133. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11134. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11135. RefModified := False;
  11136. while assigned(hp1) and
  11137. { Stop on the label we found }
  11138. (hp1 <> hp_lblxxx) do
  11139. begin
  11140. case hp1.typ of
  11141. ait_instruction:
  11142. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11143. begin
  11144. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11145. begin
  11146. Inc(l);
  11147. { MOV instruction will be writing to a register }
  11148. if Assigned(hp_prev) and
  11149. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11150. (hp_prev.typ = ait_instruction) and
  11151. (taicpu(hp_prev).ops = 2) and
  11152. (
  11153. (
  11154. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11155. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11156. ) or
  11157. (
  11158. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11159. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11160. )
  11161. ) then
  11162. { It is no longer safe to use the reference in the condition.
  11163. this prevents problems such as:
  11164. mov (%reg),%reg
  11165. mov (%reg),...
  11166. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11167. (fixes #40165)
  11168. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11169. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11170. }
  11171. RefModified := True;
  11172. end
  11173. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11174. { CMOV with constants grows the code size }
  11175. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11176. begin
  11177. { Register was reserved by TryCMOVConst and
  11178. stored on ConstRegs[c] }
  11179. end
  11180. else
  11181. Break;
  11182. end
  11183. else
  11184. Break;
  11185. else
  11186. ;
  11187. end;
  11188. GetNextInstruction(hp1,hp1);
  11189. end;
  11190. if (hp1 = hp_lblxxx) then
  11191. begin
  11192. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11193. begin
  11194. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11195. TmpUsedRegs[R_INTREGISTER].Clear;
  11196. x := 0;
  11197. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11198. condition := inverse_cond(taicpu(p).condition);
  11199. UpdateUsedRegs(tai(p.next));
  11200. hp1 := hpmov1;
  11201. repeat
  11202. if not Assigned(hp1) then
  11203. InternalError(2018062900);
  11204. if (hp1.typ = ait_instruction) then
  11205. begin
  11206. { Extra safeguard }
  11207. if (taicpu(hp1).opcode <> A_MOV) then
  11208. InternalError(2018062901);
  11209. if taicpu(hp1).oper[0]^.typ = top_const then
  11210. begin
  11211. if x >= MAX_CMOV_REGISTERS then
  11212. InternalError(2021100410);
  11213. { If it's in TmpUsedRegs, then this register
  11214. is being used more than once and hence has
  11215. already had its value defined (it gets
  11216. added to UsedRegs through AllocRegBetween
  11217. below) }
  11218. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11219. begin
  11220. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11221. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11222. asml.InsertBefore(hp_new, hp_flagalloc);
  11223. if Assigned(hp_prev2) then
  11224. TrySwapMovOp(hp_prev2, hp_new);
  11225. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11226. ConstMovs[X] := hp_new;
  11227. end
  11228. else
  11229. { We just need an instruction between hp_prev and hp1
  11230. where we know the register is marked as in use }
  11231. hp_new := hpmov1;
  11232. { Keep track of largest write for this register so it can be optimised later }
  11233. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11234. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11235. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11236. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11237. Inc(x);
  11238. end;
  11239. taicpu(hp1).opcode := A_CMOVcc;
  11240. taicpu(hp1).condition := condition;
  11241. end;
  11242. UpdateUsedRegs(tai(hp1.next));
  11243. GetNextInstruction(hp1, hp1);
  11244. until (hp1 = hp_lblxxx);
  11245. { Update initialisation MOVs to the smallest possible size }
  11246. for c := 0 to x - 1 do
  11247. if Assigned(ConstMovs[c]) then
  11248. begin
  11249. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11250. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11251. end;
  11252. hp2 := hp_lblxxx;
  11253. repeat
  11254. if not Assigned(hp2) then
  11255. InternalError(2018062910);
  11256. case hp2.typ of
  11257. ait_label:
  11258. { What we expected - break out of the loop (it won't be a dead label at the top of
  11259. a cluster because that was optimised at an earlier stage) }
  11260. Break;
  11261. ait_align:
  11262. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11263. begin
  11264. hp2 := tai(hp2.Next);
  11265. Continue;
  11266. end;
  11267. ait_instruction:
  11268. begin
  11269. if taicpu(hp2).opcode<>A_JMP then
  11270. InternalError(2018062912);
  11271. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11272. Break;
  11273. end
  11274. else
  11275. begin
  11276. { Might be a comment or temporary allocation entry }
  11277. if not (hp2.typ in SkipInstr) then
  11278. InternalError(2018062911);
  11279. hp2 := tai(hp2.Next);
  11280. Continue;
  11281. end;
  11282. end;
  11283. until False;
  11284. { Now we can safely decrement the reference count }
  11285. tasmlabel(symbol).decrefs;
  11286. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11287. { Remove the original jump }
  11288. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11289. if hp2.typ=ait_instruction then
  11290. begin
  11291. p := hp2;
  11292. Result := True;
  11293. end
  11294. else
  11295. begin
  11296. UpdateUsedRegs(tai(hp2.next));
  11297. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11298. { Remove the label if this is its final reference }
  11299. if (tasmlabel(symbol).getrefs=0) then
  11300. begin
  11301. { Make sure the aligns get stripped too }
  11302. hp1 := tai(hp_lblxxx.Previous);
  11303. while Assigned(hp1) and (hp1.typ = ait_align) do
  11304. begin
  11305. hp_lblxxx := hp1;
  11306. hp1 := tai(hp_lblxxx.Previous);
  11307. end;
  11308. StripLabelFast(hp_lblxxx);
  11309. end;
  11310. end;
  11311. Exit;
  11312. end;
  11313. end
  11314. else if assigned(hp_lblxxx) and
  11315. { check further for
  11316. jCC xxx
  11317. <several movs 1>
  11318. jmp yyy
  11319. xxx:
  11320. <several movs 2>
  11321. yyy:
  11322. }
  11323. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11324. { hp1 should be pointing to jmp yyy }
  11325. MatchInstruction(hp1, A_JMP, []) and
  11326. { real label and jump, no further references to the
  11327. label are allowed }
  11328. (TAsmLabel(symbol).getrefs=1) and
  11329. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11330. begin
  11331. hp_jump := hp1;
  11332. { Don't set c to zero }
  11333. l := 0;
  11334. w := 0;
  11335. GetNextInstruction(hp_lblxxx, hpmov2);
  11336. hp2 := hp_lblxxx;
  11337. hp_lblyyy := hpmov2;
  11338. while assigned(hp_lblyyy) and
  11339. { stop on labels }
  11340. (hp_lblyyy.typ <> ait_label) do
  11341. begin
  11342. { Keep track of all integer registers that are used }
  11343. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11344. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11345. Break;
  11346. hp2 := hp_lblyyy;
  11347. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11348. end;
  11349. { Analyse the second batch of MOVs to see if the setup is valid }
  11350. RefModified := False;
  11351. hp1 := hpmov2;
  11352. while assigned(hp1) and
  11353. (hp1 <> hp_lblyyy) do
  11354. begin
  11355. case hp1.typ of
  11356. ait_instruction:
  11357. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11358. begin
  11359. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11360. begin
  11361. Inc(l);
  11362. { MOV instruction will be writing to a register }
  11363. if Assigned(hp_prev) and
  11364. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11365. (hp_prev.typ = ait_instruction) and
  11366. (taicpu(hp_prev).ops = 2) and
  11367. (
  11368. (
  11369. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11370. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11371. ) or
  11372. (
  11373. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11374. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11375. )
  11376. ) then
  11377. { It is no longer safe to use the reference in the condition.
  11378. this prevents problems such as:
  11379. mov (%reg),%reg
  11380. mov (%reg),...
  11381. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11382. (fixes #40165)
  11383. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11384. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11385. }
  11386. RefModified := True;
  11387. end
  11388. else if not (cs_opt_size in current_settings.optimizerswitches)
  11389. { CMOV with constants grows the code size }
  11390. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11391. begin
  11392. { Register was reserved by TryCMOVConst and
  11393. stored on ConstRegs[c] }
  11394. end
  11395. else
  11396. Break;
  11397. end
  11398. else
  11399. Break;
  11400. else
  11401. ;
  11402. end;
  11403. GetNextInstruction(hp1,hp1);
  11404. end;
  11405. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11406. TmpUsedRegs[R_INTREGISTER].Clear;
  11407. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11408. (hp1 = hp_lblyyy) and
  11409. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11410. begin
  11411. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11412. second_condition := taicpu(p).condition;
  11413. condition := inverse_cond(taicpu(p).condition);
  11414. UpdateUsedRegs(tai(p.next));
  11415. { Scan through the first set of MOVs to update UsedRegs,
  11416. but don't process them yet }
  11417. hp1 := hpmov1;
  11418. repeat
  11419. if not Assigned(hp1) then
  11420. InternalError(2018062901);
  11421. UpdateUsedRegs(tai(hp1.next));
  11422. GetNextInstruction(hp1, hp1);
  11423. until (hp1 = hp_lblxxx);
  11424. UpdateUsedRegs(tai(hp_lblxxx.next));
  11425. { Process the second set of MOVs first,
  11426. because if a destination register is
  11427. shared between the first and second MOV
  11428. sets, it is more efficient to turn the
  11429. first one into a MOV instruction and place
  11430. it before the CMP if possible, but we
  11431. won't know which registers are shared
  11432. until we've processed at least one list,
  11433. so we might as well make it the second
  11434. one since that won't be modified again. }
  11435. hp1 := hpmov2;
  11436. repeat
  11437. if not Assigned(hp1) then
  11438. InternalError(2018062902);
  11439. if (hp1.typ = ait_instruction) then
  11440. begin
  11441. { Extra safeguard }
  11442. if (taicpu(hp1).opcode <> A_MOV) then
  11443. InternalError(2018062903);
  11444. if taicpu(hp1).oper[0]^.typ = top_const then
  11445. begin
  11446. RegMatch := False;
  11447. for x := 0 to c - 1 do
  11448. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11449. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11450. begin
  11451. RegMatch := True;
  11452. { If it's in TmpUsedRegs, then this register
  11453. is being used more than once and hence has
  11454. already had its value defined (it gets
  11455. added to UsedRegs through AllocRegBetween
  11456. below) }
  11457. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11458. begin
  11459. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11460. asml.InsertBefore(hp_new, hp_flagalloc);
  11461. if Assigned(hp_prev2) then
  11462. TrySwapMovOp(hp_prev2, hp_new);
  11463. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11464. ConstMovs[X] := hp_new;
  11465. end
  11466. else
  11467. { We just need an instruction between hp_prev and hp1
  11468. where we know the register is marked as in use }
  11469. hp_new := hpmov2;
  11470. { Keep track of largest write for this register so it can be optimised later }
  11471. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11472. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11473. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11474. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11475. Break;
  11476. end;
  11477. if not RegMatch then
  11478. InternalError(2021100411);
  11479. end;
  11480. taicpu(hp1).opcode := A_CMOVcc;
  11481. taicpu(hp1).condition := second_condition;
  11482. { Store these writes to search for
  11483. duplicates later on }
  11484. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11485. Inc(w);
  11486. end;
  11487. UpdateUsedRegs(tai(hp1.next));
  11488. GetNextInstruction(hp1, hp1);
  11489. until (hp1 = hp_lblyyy);
  11490. { Now do the first set of MOVs }
  11491. hp1 := hpmov1;
  11492. repeat
  11493. if not Assigned(hp1) then
  11494. InternalError(2018062904);
  11495. if (hp1.typ = ait_instruction) then
  11496. begin
  11497. RegMatch := False;
  11498. { Extra safeguard }
  11499. if (taicpu(hp1).opcode <> A_MOV) then
  11500. InternalError(2018062905);
  11501. { Search through the RegWrites list to see
  11502. if there are any opposing CMOV pairs that
  11503. write to the same register }
  11504. for x := 0 to w - 1 do
  11505. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11506. begin
  11507. { We have a match. Keep this as a MOV }
  11508. { Move ahead in preparation }
  11509. GetNextInstruction(hp1, hp1);
  11510. RegMatch := True;
  11511. Break;
  11512. end;
  11513. if RegMatch then
  11514. Continue;
  11515. if taicpu(hp1).oper[0]^.typ = top_const then
  11516. begin
  11517. RegMatch := False;
  11518. for x := 0 to c - 1 do
  11519. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11520. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11521. begin
  11522. RegMatch := True;
  11523. { If it's in TmpUsedRegs, then this register
  11524. is being used more than once and hence has
  11525. already had its value defined (it gets
  11526. added to UsedRegs through AllocRegBetween
  11527. below) }
  11528. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11529. begin
  11530. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11531. asml.InsertBefore(hp_new, hp_flagalloc);
  11532. if Assigned(hp_prev2) then
  11533. TrySwapMovOp(hp_prev2, hp_new);
  11534. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11535. ConstMovs[X] := hp_new;
  11536. end
  11537. else
  11538. { We just need an instruction between hp_prev and hp1
  11539. where we know the register is marked as in use }
  11540. hp_new := hpmov1;
  11541. { Keep track of largest write for this register so it can be optimised later }
  11542. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11543. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11544. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11545. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11546. Break;
  11547. end;
  11548. if not RegMatch then
  11549. InternalError(2021100412);
  11550. end;
  11551. taicpu(hp1).opcode := A_CMOVcc;
  11552. taicpu(hp1).condition := condition;
  11553. end;
  11554. GetNextInstruction(hp1, hp1);
  11555. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11556. { Update initialisation MOVs to the smallest possible size }
  11557. for x := 0 to c - 1 do
  11558. if Assigned(ConstMovs[x]) then
  11559. begin
  11560. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11561. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11562. end;
  11563. UpdateUsedRegs(tai(hp_jump.next));
  11564. UpdateUsedRegs(tai(hp_lblyyy.next));
  11565. { Get first instruction after label }
  11566. hp1 := p;
  11567. GetNextInstruction(hp_lblyyy, p);
  11568. { Don't dereference yet, as doing so will cause
  11569. GetNextInstruction to skip the label and
  11570. optional align marker. [Kit] }
  11571. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11572. { remove Jcc }
  11573. RemoveInstruction(hp1);
  11574. { Now we can safely decrement it }
  11575. tasmlabel(symbol).decrefs;
  11576. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11577. { Make sure the aligns get stripped too }
  11578. hp1 := tai(hp_lblxxx.Previous);
  11579. while Assigned(hp1) and (hp1.typ = ait_align) do
  11580. begin
  11581. hp_lblxxx := hp1;
  11582. hp1 := tai(hp_lblxxx.Previous);
  11583. end;
  11584. StripLabelFast(hp_lblxxx);
  11585. { remove jmp }
  11586. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11587. RemoveInstruction(hp_jump);
  11588. { As before, now we can safely decrement it }
  11589. TAsmLabel(symbol).decrefs;
  11590. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11591. if TAsmLabel(symbol).getrefs = 0 then
  11592. begin
  11593. { Make sure the aligns get stripped too }
  11594. hp1 := tai(hp_lblyyy.Previous);
  11595. while Assigned(hp1) and (hp1.typ = ait_align) do
  11596. begin
  11597. hp_lblyyy := hp1;
  11598. hp1 := tai(hp_lblyyy.Previous);
  11599. end;
  11600. StripLabelFast(hp_lblyyy);
  11601. end;
  11602. if Assigned(p) then
  11603. result := True;
  11604. exit;
  11605. end;
  11606. end;
  11607. end;
  11608. {$endif i8086}
  11609. end;
  11610. end;
  11611. end;
  11612. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11613. var
  11614. hp1,hp2,hp3: tai;
  11615. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11616. NewSize: TOpSize;
  11617. NewRegSize: TSubRegister;
  11618. Limit: TCgInt;
  11619. SwapOper: POper;
  11620. begin
  11621. result:=false;
  11622. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11623. GetNextInstruction(p,hp1) and
  11624. (hp1.typ = ait_instruction);
  11625. if reg_and_hp1_is_instr and
  11626. (
  11627. (taicpu(hp1).opcode <> A_LEA) or
  11628. { If the LEA instruction can be converted into an arithmetic instruction,
  11629. it may be possible to then fold it. }
  11630. (
  11631. { If the flags register is in use, don't change the instruction
  11632. to an ADD otherwise this will scramble the flags. [Kit] }
  11633. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11634. ConvertLEA(taicpu(hp1))
  11635. )
  11636. ) and
  11637. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11638. GetNextInstruction(hp1,hp2) and
  11639. MatchInstruction(hp2,A_MOV,[]) and
  11640. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11641. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11642. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11643. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11644. {$ifdef i386}
  11645. { not all registers have byte size sub registers on i386 }
  11646. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11647. {$endif i386}
  11648. (((taicpu(hp1).ops=2) and
  11649. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11650. ((taicpu(hp1).ops=1) and
  11651. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11652. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11653. begin
  11654. { change movsX/movzX reg/ref, reg2
  11655. add/sub/or/... reg3/$const, reg2
  11656. mov reg2 reg/ref
  11657. to add/sub/or/... reg3/$const, reg/ref }
  11658. { by example:
  11659. movswl %si,%eax movswl %si,%eax p
  11660. decl %eax addl %edx,%eax hp1
  11661. movw %ax,%si movw %ax,%si hp2
  11662. ->
  11663. movswl %si,%eax movswl %si,%eax p
  11664. decw %eax addw %edx,%eax hp1
  11665. movw %ax,%si movw %ax,%si hp2
  11666. }
  11667. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11668. {
  11669. ->
  11670. movswl %si,%eax movswl %si,%eax p
  11671. decw %si addw %dx,%si hp1
  11672. movw %ax,%si movw %ax,%si hp2
  11673. }
  11674. case taicpu(hp1).ops of
  11675. 1:
  11676. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11677. 2:
  11678. begin
  11679. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11680. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11681. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11682. end;
  11683. else
  11684. internalerror(2008042702);
  11685. end;
  11686. {
  11687. ->
  11688. decw %si addw %dx,%si p
  11689. }
  11690. DebugMsg(SPeepholeOptimization + 'var3',p);
  11691. RemoveCurrentP(p, hp1);
  11692. RemoveInstruction(hp2);
  11693. Result := True;
  11694. Exit;
  11695. end;
  11696. if reg_and_hp1_is_instr and
  11697. (taicpu(hp1).opcode = A_MOV) and
  11698. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11699. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11700. {$ifdef x86_64}
  11701. { check for implicit extension to 64 bit }
  11702. or
  11703. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11704. (taicpu(hp1).opsize=S_Q) and
  11705. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11706. )
  11707. {$endif x86_64}
  11708. )
  11709. then
  11710. begin
  11711. { change
  11712. movx %reg1,%reg2
  11713. mov %reg2,%reg3
  11714. dealloc %reg2
  11715. into
  11716. movx %reg,%reg3
  11717. }
  11718. TransferUsedRegs(TmpUsedRegs);
  11719. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11720. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11721. begin
  11722. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11723. {$ifdef x86_64}
  11724. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11725. (taicpu(hp1).opsize=S_Q) then
  11726. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11727. else
  11728. {$endif x86_64}
  11729. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11730. RemoveInstruction(hp1);
  11731. Result := True;
  11732. Exit;
  11733. end;
  11734. end;
  11735. if reg_and_hp1_is_instr and
  11736. ((taicpu(hp1).opcode=A_MOV) or
  11737. (taicpu(hp1).opcode=A_ADD) or
  11738. (taicpu(hp1).opcode=A_SUB) or
  11739. (taicpu(hp1).opcode=A_CMP) or
  11740. (taicpu(hp1).opcode=A_OR) or
  11741. (taicpu(hp1).opcode=A_XOR) or
  11742. (taicpu(hp1).opcode=A_AND)
  11743. ) and
  11744. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11745. begin
  11746. AndTest := (taicpu(hp1).opcode=A_AND) and
  11747. GetNextInstruction(hp1, hp2) and
  11748. (hp2.typ = ait_instruction) and
  11749. (
  11750. (
  11751. (taicpu(hp2).opcode=A_TEST) and
  11752. (
  11753. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11754. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11755. (
  11756. { If the AND and TEST instructions share a constant, this is also valid }
  11757. (taicpu(hp1).oper[0]^.typ = top_const) and
  11758. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11759. )
  11760. ) and
  11761. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11762. ) or
  11763. (
  11764. (taicpu(hp2).opcode=A_CMP) and
  11765. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11766. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11767. )
  11768. );
  11769. { change
  11770. movx (oper),%reg2
  11771. and $x,%reg2
  11772. test %reg2,%reg2
  11773. dealloc %reg2
  11774. into
  11775. op %reg1,%reg3
  11776. if the second op accesses only the bits stored in reg1
  11777. }
  11778. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11779. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11780. (taicpu(hp1).oper[0]^.typ = top_const) and
  11781. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11782. AndTest then
  11783. begin
  11784. { Check if the AND constant is in range }
  11785. case taicpu(p).opsize of
  11786. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11787. begin
  11788. NewSize := S_B;
  11789. Limit := $FF;
  11790. end;
  11791. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11792. begin
  11793. NewSize := S_W;
  11794. Limit := $FFFF;
  11795. end;
  11796. {$ifdef x86_64}
  11797. S_LQ:
  11798. begin
  11799. NewSize := S_L;
  11800. Limit := $FFFFFFFF;
  11801. end;
  11802. {$endif x86_64}
  11803. else
  11804. InternalError(2021120303);
  11805. end;
  11806. if (
  11807. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11808. { Check for negative operands }
  11809. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11810. ) and
  11811. GetNextInstruction(hp2,hp3) and
  11812. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11813. (taicpu(hp3).condition in [C_E,C_NE]) then
  11814. begin
  11815. TransferUsedRegs(TmpUsedRegs);
  11816. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11817. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11818. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11819. begin
  11820. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11821. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11822. taicpu(hp1).opcode := A_TEST;
  11823. taicpu(hp1).opsize := NewSize;
  11824. RemoveInstruction(hp2);
  11825. RemoveCurrentP(p, hp1);
  11826. Result:=true;
  11827. exit;
  11828. end;
  11829. end;
  11830. end;
  11831. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11832. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11833. (taicpu(hp1).opsize=S_B)) or
  11834. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11835. (taicpu(hp1).opsize=S_W))
  11836. {$ifdef x86_64}
  11837. or ((taicpu(p).opsize=S_LQ) and
  11838. (taicpu(hp1).opsize=S_L))
  11839. {$endif x86_64}
  11840. ) and
  11841. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11842. begin
  11843. { change
  11844. movx %reg1,%reg2
  11845. op %reg2,%reg3
  11846. dealloc %reg2
  11847. into
  11848. op %reg1,%reg3
  11849. if the second op accesses only the bits stored in reg1
  11850. }
  11851. TransferUsedRegs(TmpUsedRegs);
  11852. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11853. if AndTest then
  11854. begin
  11855. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11856. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11857. end
  11858. else
  11859. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11860. if not RegUsed then
  11861. begin
  11862. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11863. if taicpu(p).oper[0]^.typ=top_reg then
  11864. begin
  11865. case taicpu(hp1).opsize of
  11866. S_B:
  11867. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11868. S_W:
  11869. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11870. S_L:
  11871. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11872. else
  11873. Internalerror(2020102301);
  11874. end;
  11875. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11876. end
  11877. else
  11878. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11879. RemoveCurrentP(p);
  11880. if AndTest then
  11881. RemoveInstruction(hp2);
  11882. result:=true;
  11883. exit;
  11884. end;
  11885. end
  11886. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11887. (
  11888. { Bitwise operations only }
  11889. (taicpu(hp1).opcode=A_AND) or
  11890. (taicpu(hp1).opcode=A_TEST) or
  11891. (
  11892. (taicpu(hp1).oper[0]^.typ = top_const) and
  11893. (
  11894. (taicpu(hp1).opcode=A_OR) or
  11895. (taicpu(hp1).opcode=A_XOR)
  11896. )
  11897. )
  11898. ) and
  11899. (
  11900. (taicpu(hp1).oper[0]^.typ = top_const) or
  11901. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11902. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11903. ) then
  11904. begin
  11905. { change
  11906. movx %reg2,%reg2
  11907. op const,%reg2
  11908. into
  11909. op const,%reg2 (smaller version)
  11910. movx %reg2,%reg2
  11911. also change
  11912. movx %reg1,%reg2
  11913. and/test (oper),%reg2
  11914. dealloc %reg2
  11915. into
  11916. and/test (oper),%reg1
  11917. }
  11918. case taicpu(p).opsize of
  11919. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11920. begin
  11921. NewSize := S_B;
  11922. NewRegSize := R_SUBL;
  11923. Limit := $FF;
  11924. end;
  11925. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11926. begin
  11927. NewSize := S_W;
  11928. NewRegSize := R_SUBW;
  11929. Limit := $FFFF;
  11930. end;
  11931. {$ifdef x86_64}
  11932. S_LQ:
  11933. begin
  11934. NewSize := S_L;
  11935. NewRegSize := R_SUBD;
  11936. Limit := $FFFFFFFF;
  11937. end;
  11938. {$endif x86_64}
  11939. else
  11940. Internalerror(2021120302);
  11941. end;
  11942. TransferUsedRegs(TmpUsedRegs);
  11943. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11944. if AndTest then
  11945. begin
  11946. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11947. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11948. end
  11949. else
  11950. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11951. if
  11952. (
  11953. (taicpu(p).opcode = A_MOVZX) and
  11954. (
  11955. (taicpu(hp1).opcode=A_AND) or
  11956. (taicpu(hp1).opcode=A_TEST)
  11957. ) and
  11958. not (
  11959. { If both are references, then the final instruction will have
  11960. both operands as references, which is not allowed }
  11961. (taicpu(p).oper[0]^.typ = top_ref) and
  11962. (taicpu(hp1).oper[0]^.typ = top_ref)
  11963. ) and
  11964. not RegUsed
  11965. ) or
  11966. (
  11967. (
  11968. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11969. not RegUsed
  11970. ) and
  11971. (taicpu(p).oper[0]^.typ = top_reg) and
  11972. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11973. (taicpu(hp1).oper[0]^.typ = top_const) and
  11974. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11975. ) then
  11976. begin
  11977. {$if defined(i386) or defined(i8086)}
  11978. { If the target size is 8-bit, make sure we can actually encode it }
  11979. 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
  11980. Exit;
  11981. {$endif i386 or i8086}
  11982. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11983. taicpu(hp1).opsize := NewSize;
  11984. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11985. if AndTest then
  11986. begin
  11987. RemoveInstruction(hp2);
  11988. if not RegUsed then
  11989. begin
  11990. taicpu(hp1).opcode := A_TEST;
  11991. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11992. begin
  11993. { Make sure the reference is the second operand }
  11994. SwapOper := taicpu(hp1).oper[0];
  11995. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11996. taicpu(hp1).oper[1] := SwapOper;
  11997. end;
  11998. end;
  11999. end;
  12000. case taicpu(hp1).oper[0]^.typ of
  12001. top_reg:
  12002. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12003. top_const:
  12004. { For the AND/TEST case }
  12005. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12006. else
  12007. ;
  12008. end;
  12009. if RegUsed then
  12010. begin
  12011. AsmL.Remove(p);
  12012. AsmL.InsertAfter(p, hp1);
  12013. p := hp1;
  12014. end
  12015. else
  12016. RemoveCurrentP(p, hp1);
  12017. result:=true;
  12018. exit;
  12019. end;
  12020. end;
  12021. end;
  12022. if reg_and_hp1_is_instr and
  12023. (taicpu(p).oper[0]^.typ = top_reg) and
  12024. (
  12025. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12026. ) and
  12027. (taicpu(hp1).oper[0]^.typ = top_const) and
  12028. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12029. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12030. { Minimum shift value allowed is the bit difference between the sizes }
  12031. (taicpu(hp1).oper[0]^.val >=
  12032. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12033. 8 * (
  12034. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12035. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12036. )
  12037. ) then
  12038. begin
  12039. { For:
  12040. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12041. shl/sal ##, %reg1
  12042. Remove the movsx/movzx instruction if the shift overwrites the
  12043. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12044. }
  12045. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12046. RemoveCurrentP(p, hp1);
  12047. Result := True;
  12048. Exit;
  12049. end
  12050. else if reg_and_hp1_is_instr and
  12051. (taicpu(p).oper[0]^.typ = top_reg) and
  12052. (
  12053. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12054. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12055. ) and
  12056. (taicpu(hp1).oper[0]^.typ = top_const) and
  12057. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12058. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12059. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12060. (taicpu(hp1).oper[0]^.val <
  12061. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12062. 8 * (
  12063. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12064. )
  12065. ) then
  12066. begin
  12067. { For:
  12068. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12069. sar ##, %reg1 shr ##, %reg1
  12070. Move the shift to before the movx instruction if the shift value
  12071. is not too large.
  12072. }
  12073. asml.Remove(hp1);
  12074. asml.InsertBefore(hp1, p);
  12075. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12076. case taicpu(p).opsize of
  12077. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12078. taicpu(hp1).opsize := S_B;
  12079. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12080. taicpu(hp1).opsize := S_W;
  12081. {$ifdef x86_64}
  12082. S_LQ:
  12083. taicpu(hp1).opsize := S_L;
  12084. {$endif}
  12085. else
  12086. InternalError(2020112401);
  12087. end;
  12088. if (taicpu(hp1).opcode = A_SHR) then
  12089. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12090. else
  12091. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12092. Result := True;
  12093. end;
  12094. if reg_and_hp1_is_instr and
  12095. (taicpu(p).oper[0]^.typ = top_reg) and
  12096. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12097. (
  12098. (taicpu(hp1).opcode = taicpu(p).opcode)
  12099. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12100. {$ifdef x86_64}
  12101. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12102. {$endif x86_64}
  12103. ) then
  12104. begin
  12105. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12106. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12107. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12108. begin
  12109. {
  12110. For example:
  12111. movzbw %al,%ax
  12112. movzwl %ax,%eax
  12113. Compress into:
  12114. movzbl %al,%eax
  12115. }
  12116. RegUsed := False;
  12117. case taicpu(p).opsize of
  12118. S_BW:
  12119. case taicpu(hp1).opsize of
  12120. S_WL:
  12121. begin
  12122. taicpu(p).opsize := S_BL;
  12123. RegUsed := True;
  12124. end;
  12125. {$ifdef x86_64}
  12126. S_WQ:
  12127. begin
  12128. if taicpu(p).opcode = A_MOVZX then
  12129. begin
  12130. taicpu(p).opsize := S_BL;
  12131. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12132. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12133. end
  12134. else
  12135. taicpu(p).opsize := S_BQ;
  12136. RegUsed := True;
  12137. end;
  12138. {$endif x86_64}
  12139. else
  12140. ;
  12141. end;
  12142. {$ifdef x86_64}
  12143. S_BL:
  12144. case taicpu(hp1).opsize of
  12145. S_LQ:
  12146. begin
  12147. if taicpu(p).opcode = A_MOVZX then
  12148. begin
  12149. taicpu(p).opsize := S_BL;
  12150. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12151. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12152. end
  12153. else
  12154. taicpu(p).opsize := S_BQ;
  12155. RegUsed := True;
  12156. end;
  12157. else
  12158. ;
  12159. end;
  12160. S_WL:
  12161. case taicpu(hp1).opsize of
  12162. S_LQ:
  12163. begin
  12164. if taicpu(p).opcode = A_MOVZX then
  12165. begin
  12166. taicpu(p).opsize := S_WL;
  12167. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12168. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12169. end
  12170. else
  12171. taicpu(p).opsize := S_WQ;
  12172. RegUsed := True;
  12173. end;
  12174. else
  12175. ;
  12176. end;
  12177. {$endif x86_64}
  12178. else
  12179. ;
  12180. end;
  12181. if RegUsed then
  12182. begin
  12183. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12184. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12185. RemoveInstruction(hp1);
  12186. Result := True;
  12187. Exit;
  12188. end;
  12189. end;
  12190. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12191. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12192. GetNextInstruction(hp1, hp2) and
  12193. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12194. (
  12195. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12196. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12197. {$ifdef x86_64}
  12198. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12199. {$endif x86_64}
  12200. ) and
  12201. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12202. (
  12203. (
  12204. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12205. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12206. ) or
  12207. (
  12208. { Only allow the operands in reverse order for TEST instructions }
  12209. (taicpu(hp2).opcode = A_TEST) and
  12210. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12211. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12212. )
  12213. ) then
  12214. begin
  12215. {
  12216. For example:
  12217. movzbl %al,%eax
  12218. movzbl (ref),%edx
  12219. andl %edx,%eax
  12220. (%edx deallocated)
  12221. Change to:
  12222. andb (ref),%al
  12223. movzbl %al,%eax
  12224. Rules are:
  12225. - First two instructions have the same opcode and opsize
  12226. - First instruction's operands are the same super-register
  12227. - Second instruction operates on a different register
  12228. - Third instruction is AND, OR, XOR or TEST
  12229. - Third instruction's operands are the destination registers of the first two instructions
  12230. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12231. - Second instruction's destination register is deallocated afterwards
  12232. }
  12233. TransferUsedRegs(TmpUsedRegs);
  12234. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12235. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12236. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12237. begin
  12238. case taicpu(p).opsize of
  12239. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12240. NewSize := S_B;
  12241. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12242. NewSize := S_W;
  12243. {$ifdef x86_64}
  12244. S_LQ:
  12245. NewSize := S_L;
  12246. {$endif x86_64}
  12247. else
  12248. InternalError(2021120301);
  12249. end;
  12250. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12251. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12252. taicpu(hp2).opsize := NewSize;
  12253. RemoveInstruction(hp1);
  12254. { With TEST, it's best to keep the MOVX instruction at the top }
  12255. if (taicpu(hp2).opcode <> A_TEST) then
  12256. begin
  12257. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12258. asml.Remove(p);
  12259. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12260. asml.InsertAfter(p, hp2);
  12261. p := hp2;
  12262. end
  12263. else
  12264. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12265. Result := True;
  12266. Exit;
  12267. end;
  12268. end;
  12269. end;
  12270. if taicpu(p).opcode=A_MOVZX then
  12271. begin
  12272. { removes superfluous And's after movzx's }
  12273. if reg_and_hp1_is_instr and
  12274. (taicpu(hp1).opcode = A_AND) and
  12275. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12276. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12277. {$ifdef x86_64}
  12278. { check for implicit extension to 64 bit }
  12279. or
  12280. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12281. (taicpu(hp1).opsize=S_Q) and
  12282. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12283. )
  12284. {$endif x86_64}
  12285. )
  12286. then
  12287. begin
  12288. case taicpu(p).opsize Of
  12289. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12290. if (taicpu(hp1).oper[0]^.val = $ff) then
  12291. begin
  12292. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12293. RemoveInstruction(hp1);
  12294. Result:=true;
  12295. exit;
  12296. end;
  12297. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12298. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12299. begin
  12300. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12301. RemoveInstruction(hp1);
  12302. Result:=true;
  12303. exit;
  12304. end;
  12305. {$ifdef x86_64}
  12306. S_LQ:
  12307. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12308. begin
  12309. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12310. RemoveInstruction(hp1);
  12311. Result:=true;
  12312. exit;
  12313. end;
  12314. {$endif x86_64}
  12315. else
  12316. ;
  12317. end;
  12318. { we cannot get rid of the and, but can we get rid of the movz ?}
  12319. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12320. begin
  12321. case taicpu(p).opsize Of
  12322. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12323. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12324. begin
  12325. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12326. RemoveCurrentP(p,hp1);
  12327. Result:=true;
  12328. exit;
  12329. end;
  12330. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12331. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12332. begin
  12333. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12334. RemoveCurrentP(p,hp1);
  12335. Result:=true;
  12336. exit;
  12337. end;
  12338. {$ifdef x86_64}
  12339. S_LQ:
  12340. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12341. begin
  12342. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12343. RemoveCurrentP(p,hp1);
  12344. Result:=true;
  12345. exit;
  12346. end;
  12347. {$endif x86_64}
  12348. else
  12349. ;
  12350. end;
  12351. end;
  12352. end;
  12353. { changes some movzx constructs to faster synonyms (all examples
  12354. are given with eax/ax, but are also valid for other registers)}
  12355. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12356. begin
  12357. case taicpu(p).opsize of
  12358. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12359. (the machine code is equivalent to movzbl %al,%eax), but the
  12360. code generator still generates that assembler instruction and
  12361. it is silently converted. This should probably be checked.
  12362. [Kit] }
  12363. S_BW:
  12364. begin
  12365. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12366. (
  12367. not IsMOVZXAcceptable
  12368. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12369. or (
  12370. (cs_opt_size in current_settings.optimizerswitches) and
  12371. (taicpu(p).oper[1]^.reg = NR_AX)
  12372. )
  12373. ) then
  12374. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12375. begin
  12376. DebugMsg(SPeepholeOptimization + 'var7',p);
  12377. taicpu(p).opcode := A_AND;
  12378. taicpu(p).changeopsize(S_W);
  12379. taicpu(p).loadConst(0,$ff);
  12380. Result := True;
  12381. end
  12382. else if not IsMOVZXAcceptable and
  12383. GetNextInstruction(p, hp1) and
  12384. (tai(hp1).typ = ait_instruction) and
  12385. (taicpu(hp1).opcode = A_AND) and
  12386. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12387. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12388. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12389. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12390. begin
  12391. DebugMsg(SPeepholeOptimization + 'var8',p);
  12392. taicpu(p).opcode := A_MOV;
  12393. taicpu(p).changeopsize(S_W);
  12394. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12395. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12396. Result := True;
  12397. end;
  12398. end;
  12399. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12400. S_BL:
  12401. if not IsMOVZXAcceptable then
  12402. begin
  12403. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12404. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12405. begin
  12406. DebugMsg(SPeepholeOptimization + 'var9',p);
  12407. taicpu(p).opcode := A_AND;
  12408. taicpu(p).changeopsize(S_L);
  12409. taicpu(p).loadConst(0,$ff);
  12410. Result := True;
  12411. end
  12412. else if GetNextInstruction(p, hp1) and
  12413. (tai(hp1).typ = ait_instruction) and
  12414. (taicpu(hp1).opcode = A_AND) and
  12415. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12416. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12417. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12418. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12419. begin
  12420. DebugMsg(SPeepholeOptimization + 'var10',p);
  12421. taicpu(p).opcode := A_MOV;
  12422. taicpu(p).changeopsize(S_L);
  12423. { do not use R_SUBWHOLE
  12424. as movl %rdx,%eax
  12425. is invalid in assembler PM }
  12426. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12427. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12428. Result := True;
  12429. end;
  12430. end;
  12431. {$endif i8086}
  12432. S_WL:
  12433. if not IsMOVZXAcceptable then
  12434. begin
  12435. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12436. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12437. begin
  12438. DebugMsg(SPeepholeOptimization + 'var11',p);
  12439. taicpu(p).opcode := A_AND;
  12440. taicpu(p).changeopsize(S_L);
  12441. taicpu(p).loadConst(0,$ffff);
  12442. Result := True;
  12443. end
  12444. else if GetNextInstruction(p, hp1) and
  12445. (tai(hp1).typ = ait_instruction) and
  12446. (taicpu(hp1).opcode = A_AND) and
  12447. (taicpu(hp1).oper[0]^.typ = top_const) and
  12448. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12449. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12450. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12451. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12452. begin
  12453. DebugMsg(SPeepholeOptimization + 'var12',p);
  12454. taicpu(p).opcode := A_MOV;
  12455. taicpu(p).changeopsize(S_L);
  12456. { do not use R_SUBWHOLE
  12457. as movl %rdx,%eax
  12458. is invalid in assembler PM }
  12459. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12461. Result := True;
  12462. end;
  12463. end;
  12464. else
  12465. InternalError(2017050705);
  12466. end;
  12467. end
  12468. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12469. begin
  12470. if GetNextInstruction(p, hp1) and
  12471. (tai(hp1).typ = ait_instruction) and
  12472. (taicpu(hp1).opcode = A_AND) and
  12473. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12474. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12475. begin
  12476. //taicpu(p).opcode := A_MOV;
  12477. case taicpu(p).opsize Of
  12478. S_BL:
  12479. begin
  12480. DebugMsg(SPeepholeOptimization + 'var13',p);
  12481. taicpu(hp1).changeopsize(S_L);
  12482. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12483. end;
  12484. S_WL:
  12485. begin
  12486. DebugMsg(SPeepholeOptimization + 'var14',p);
  12487. taicpu(hp1).changeopsize(S_L);
  12488. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12489. end;
  12490. S_BW:
  12491. begin
  12492. DebugMsg(SPeepholeOptimization + 'var15',p);
  12493. taicpu(hp1).changeopsize(S_W);
  12494. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12495. end;
  12496. else
  12497. Internalerror(2017050704)
  12498. end;
  12499. Result := True;
  12500. end;
  12501. end;
  12502. end;
  12503. end;
  12504. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12505. var
  12506. hp1, hp2 : tai;
  12507. MaskLength : Cardinal;
  12508. MaskedBits : TCgInt;
  12509. ActiveReg : TRegister;
  12510. begin
  12511. Result:=false;
  12512. { There are no optimisations for reference targets }
  12513. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12514. Exit;
  12515. while GetNextInstruction(p, hp1) and
  12516. (hp1.typ = ait_instruction) do
  12517. begin
  12518. if (taicpu(p).oper[0]^.typ = top_const) then
  12519. begin
  12520. case taicpu(hp1).opcode of
  12521. A_AND:
  12522. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12523. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12524. { the second register must contain the first one, so compare their subreg types }
  12525. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12526. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12527. { change
  12528. and const1, reg
  12529. and const2, reg
  12530. to
  12531. and (const1 and const2), reg
  12532. }
  12533. begin
  12534. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12535. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12536. RemoveCurrentP(p, hp1);
  12537. Result:=true;
  12538. exit;
  12539. end;
  12540. A_CMP:
  12541. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12542. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12543. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12544. { Just check that the condition on the next instruction is compatible }
  12545. GetNextInstruction(hp1, hp2) and
  12546. (hp2.typ = ait_instruction) and
  12547. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12548. then
  12549. { change
  12550. and 2^n, reg
  12551. cmp 2^n, reg
  12552. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12553. to
  12554. and 2^n, reg
  12555. test reg, reg
  12556. j(~c) / set(~c) / cmov(~c)
  12557. }
  12558. begin
  12559. { Keep TEST instruction in, rather than remove it, because
  12560. it may trigger other optimisations such as MovAndTest2Test }
  12561. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12562. taicpu(hp1).opcode := A_TEST;
  12563. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12564. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12565. Result := True;
  12566. Exit;
  12567. end
  12568. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12569. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12570. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12571. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12572. { change
  12573. and $ff/$ff/$ffff, reg
  12574. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12575. dealloc reg
  12576. to
  12577. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12578. }
  12579. begin
  12580. TransferUsedRegs(TmpUsedRegs);
  12581. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12582. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12583. begin
  12584. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12585. case taicpu(p).oper[0]^.val of
  12586. $ff:
  12587. begin
  12588. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12589. taicpu(hp1).opsize:=S_B;
  12590. end;
  12591. $ffff:
  12592. begin
  12593. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12594. taicpu(hp1).opsize:=S_W;
  12595. end;
  12596. $ffffffff:
  12597. begin
  12598. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12599. taicpu(hp1).opsize:=S_L;
  12600. end;
  12601. else
  12602. Internalerror(2023030401);
  12603. end;
  12604. RemoveCurrentP(p);
  12605. Result := True;
  12606. Exit;
  12607. end;
  12608. end;
  12609. A_MOVZX:
  12610. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12611. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12612. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12613. (
  12614. (
  12615. (taicpu(p).opsize=S_W) and
  12616. (taicpu(hp1).opsize=S_BW)
  12617. ) or
  12618. (
  12619. (taicpu(p).opsize=S_L) and
  12620. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12621. )
  12622. {$ifdef x86_64}
  12623. or
  12624. (
  12625. (taicpu(p).opsize=S_Q) and
  12626. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12627. )
  12628. {$endif x86_64}
  12629. ) then
  12630. begin
  12631. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12632. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12633. ) or
  12634. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12635. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12636. then
  12637. begin
  12638. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12639. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12640. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12641. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12642. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12643. }
  12644. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12645. RemoveInstruction(hp1);
  12646. { See if there are other optimisations possible }
  12647. Continue;
  12648. end;
  12649. end;
  12650. A_SHL:
  12651. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12652. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12653. begin
  12654. {$ifopt R+}
  12655. {$define RANGE_WAS_ON}
  12656. {$R-}
  12657. {$endif}
  12658. { get length of potential and mask }
  12659. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12660. { really a mask? }
  12661. {$ifdef RANGE_WAS_ON}
  12662. {$R+}
  12663. {$endif}
  12664. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12665. { unmasked part shifted out? }
  12666. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12667. begin
  12668. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12669. RemoveCurrentP(p, hp1);
  12670. Result:=true;
  12671. exit;
  12672. end;
  12673. end;
  12674. A_SHR:
  12675. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12676. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12677. (taicpu(hp1).oper[0]^.val <= 63) then
  12678. begin
  12679. { Does SHR combined with the AND cover all the bits?
  12680. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12681. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12682. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12683. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12684. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12685. begin
  12686. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12687. RemoveCurrentP(p, hp1);
  12688. Result := True;
  12689. Exit;
  12690. end;
  12691. end;
  12692. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12693. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12694. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12695. begin
  12696. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12697. (
  12698. (
  12699. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12700. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12701. ) or (
  12702. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12703. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12704. {$ifdef x86_64}
  12705. ) or (
  12706. (taicpu(hp1).opsize = S_LQ) and
  12707. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12708. {$endif x86_64}
  12709. )
  12710. ) then
  12711. begin
  12712. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12713. begin
  12714. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12715. RemoveInstruction(hp1);
  12716. { See if there are other optimisations possible }
  12717. Continue;
  12718. end;
  12719. { The super-registers are the same though.
  12720. Note that this change by itself doesn't improve
  12721. code speed, but it opens up other optimisations. }
  12722. {$ifdef x86_64}
  12723. { Convert 64-bit register to 32-bit }
  12724. case taicpu(hp1).opsize of
  12725. S_BQ:
  12726. begin
  12727. taicpu(hp1).opsize := S_BL;
  12728. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12729. end;
  12730. S_WQ:
  12731. begin
  12732. taicpu(hp1).opsize := S_WL;
  12733. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12734. end
  12735. else
  12736. ;
  12737. end;
  12738. {$endif x86_64}
  12739. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12740. taicpu(hp1).opcode := A_MOVZX;
  12741. { See if there are other optimisations possible }
  12742. Continue;
  12743. end;
  12744. end;
  12745. else
  12746. ;
  12747. end;
  12748. end
  12749. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12750. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12751. begin
  12752. {$ifdef x86_64}
  12753. if (taicpu(p).opsize = S_Q) then
  12754. begin
  12755. { Never necessary }
  12756. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12757. RemoveCurrentP(p, hp1);
  12758. Result := True;
  12759. Exit;
  12760. end;
  12761. {$endif x86_64}
  12762. { Forward check to determine necessity of and %reg,%reg }
  12763. TransferUsedRegs(TmpUsedRegs);
  12764. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12765. { Saves on a bunch of dereferences }
  12766. ActiveReg := taicpu(p).oper[1]^.reg;
  12767. case taicpu(hp1).opcode of
  12768. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12769. if (
  12770. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12771. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12772. ) and
  12773. (
  12774. (taicpu(hp1).opcode <> A_MOV) or
  12775. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12776. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12777. ) and
  12778. not (
  12779. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12780. (taicpu(hp1).opcode = A_MOV) and
  12781. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12782. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12783. ) and
  12784. (
  12785. (
  12786. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12787. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12788. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12789. ) or
  12790. (
  12791. {$ifdef x86_64}
  12792. (
  12793. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12794. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12795. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12796. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12797. ) and
  12798. {$endif x86_64}
  12799. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12800. )
  12801. ) then
  12802. begin
  12803. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12804. RemoveCurrentP(p, hp1);
  12805. Result := True;
  12806. Exit;
  12807. end;
  12808. A_ADD,
  12809. A_AND,
  12810. A_BSF,
  12811. A_BSR,
  12812. A_BTC,
  12813. A_BTR,
  12814. A_BTS,
  12815. A_OR,
  12816. A_SUB,
  12817. A_XOR:
  12818. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12819. if (
  12820. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12821. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12822. ) and
  12823. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12824. begin
  12825. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12826. RemoveCurrentP(p, hp1);
  12827. Result := True;
  12828. Exit;
  12829. end;
  12830. A_CMP,
  12831. A_TEST:
  12832. if (
  12833. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12834. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12835. ) and
  12836. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12837. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12838. begin
  12839. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12840. RemoveCurrentP(p, hp1);
  12841. Result := True;
  12842. Exit;
  12843. end;
  12844. A_BSWAP,
  12845. A_NEG,
  12846. A_NOT:
  12847. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12848. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12849. begin
  12850. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12851. RemoveCurrentP(p, hp1);
  12852. Result := True;
  12853. Exit;
  12854. end;
  12855. else
  12856. ;
  12857. end;
  12858. end;
  12859. if (taicpu(hp1).is_jmp) and
  12860. (taicpu(hp1).opcode<>A_JMP) and
  12861. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12862. begin
  12863. { change
  12864. and x, reg
  12865. jxx
  12866. to
  12867. test x, reg
  12868. jxx
  12869. if reg is deallocated before the
  12870. jump, but only if it's a conditional jump (PFV)
  12871. }
  12872. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12873. taicpu(p).opcode := A_TEST;
  12874. Exit;
  12875. end;
  12876. Break;
  12877. end;
  12878. { Lone AND tests }
  12879. if (taicpu(p).oper[0]^.typ = top_const) then
  12880. begin
  12881. {
  12882. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12883. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12884. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12885. }
  12886. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12887. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12888. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12889. begin
  12890. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12891. if taicpu(p).opsize = S_L then
  12892. begin
  12893. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12894. Result := True;
  12895. end;
  12896. end;
  12897. end;
  12898. { Backward check to determine necessity of and %reg,%reg }
  12899. if (taicpu(p).oper[0]^.typ = top_reg) and
  12900. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12901. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12902. GetLastInstruction(p, hp2) and
  12903. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12904. { Check size of adjacent instruction to determine if the AND is
  12905. effectively a null operation }
  12906. (
  12907. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12908. { Note: Don't include S_Q }
  12909. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12910. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12911. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12912. ) then
  12913. begin
  12914. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12915. { If GetNextInstruction returned False, hp1 will be nil }
  12916. RemoveCurrentP(p, hp1);
  12917. Result := True;
  12918. Exit;
  12919. end;
  12920. end;
  12921. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12922. var
  12923. hp1, hp2: tai;
  12924. NewRef: TReference;
  12925. Distance: Cardinal;
  12926. TempTracking: TAllUsedRegs;
  12927. { This entire nested function is used in an if-statement below, but we
  12928. want to avoid all the used reg transfers and GetNextInstruction calls
  12929. until we really have to check }
  12930. function MemRegisterNotUsedLater: Boolean; inline;
  12931. var
  12932. hp2: tai;
  12933. begin
  12934. TransferUsedRegs(TmpUsedRegs);
  12935. hp2 := p;
  12936. repeat
  12937. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12938. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12939. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12940. end;
  12941. begin
  12942. Result := False;
  12943. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12944. (taicpu(p).oper[1]^.typ = top_reg) then
  12945. begin
  12946. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12947. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12948. (hp1.typ <> ait_instruction) or
  12949. not
  12950. (
  12951. (cs_opt_level3 in current_settings.optimizerswitches) or
  12952. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12953. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12954. ) then
  12955. Exit;
  12956. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12957. addq $x, %rax
  12958. movq %rax, %rdx
  12959. sarq $63, %rdx
  12960. (%rax still in use)
  12961. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12962. leaq $x(%rax),%rdx
  12963. addq $x, %rax
  12964. sarq $63, %rdx
  12965. ...which is okay since it breaks the dependency chain between
  12966. addq and movq, but if OptPass2MOV is called first:
  12967. addq $x, %rax
  12968. cqto
  12969. ...which is better in all ways, taking only 2 cycles to execute
  12970. and much smaller in code size.
  12971. }
  12972. { The extra register tracking is quite strenuous }
  12973. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12974. MatchInstruction(hp1, A_MOV, []) then
  12975. begin
  12976. { Update the register tracking to the MOV instruction }
  12977. CopyUsedRegs(TempTracking);
  12978. hp2 := p;
  12979. repeat
  12980. UpdateUsedRegs(tai(hp2.Next));
  12981. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12982. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12983. OptPass2ADD get called again }
  12984. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12985. begin
  12986. { Reset the tracking to the current instruction }
  12987. RestoreUsedRegs(TempTracking);
  12988. ReleaseUsedRegs(TempTracking);
  12989. Result := True;
  12990. Exit;
  12991. end;
  12992. { Reset the tracking to the current instruction }
  12993. RestoreUsedRegs(TempTracking);
  12994. ReleaseUsedRegs(TempTracking);
  12995. { If OptPass2MOV returned True, we don't need to set Result to
  12996. True if hp1 didn't change because the ADD instruction didn't
  12997. get modified and we'll be evaluating hp1 again when the
  12998. peephole optimizer reaches it }
  12999. end;
  13000. { Change:
  13001. add %reg2,%reg1
  13002. (%reg2 not modified in between)
  13003. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13004. To:
  13005. mov/s/z #(%reg1,%reg2),%reg1
  13006. }
  13007. if (taicpu(p).oper[0]^.typ = top_reg) and
  13008. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13009. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13010. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13011. (
  13012. (
  13013. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13014. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13015. { r/esp cannot be an index }
  13016. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13017. ) or (
  13018. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13019. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13020. )
  13021. ) and (
  13022. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13023. (
  13024. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13025. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13026. MemRegisterNotUsedLater
  13027. )
  13028. ) then
  13029. begin
  13030. if (
  13031. { Instructions are guaranteed to be adjacent on -O2 and under }
  13032. (cs_opt_level3 in current_settings.optimizerswitches) and
  13033. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13034. ) then
  13035. begin
  13036. { If the other register is used in between, move the MOV
  13037. instruction to right after the ADD instruction so a
  13038. saving can still be made }
  13039. Asml.Remove(hp1);
  13040. Asml.InsertAfter(hp1, p);
  13041. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13042. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13043. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13044. RemoveCurrentp(p, hp1);
  13045. end
  13046. else
  13047. begin
  13048. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13049. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13050. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13051. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13052. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13053. { hp1 may not be the immediate next instruction under -O3 }
  13054. RemoveCurrentp(p)
  13055. else
  13056. RemoveCurrentp(p, hp1);
  13057. end;
  13058. Result := True;
  13059. Exit;
  13060. end;
  13061. { Change:
  13062. addl/q $x,%reg1
  13063. movl/q %reg1,%reg2
  13064. To:
  13065. leal/q $x(%reg1),%reg2
  13066. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13067. Breaks the dependency chain.
  13068. }
  13069. if (taicpu(p).oper[0]^.typ = top_const) and
  13070. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13071. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13072. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13073. (
  13074. { Instructions are guaranteed to be adjacent on -O2 and under }
  13075. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13076. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13077. ) then
  13078. begin
  13079. TransferUsedRegs(TmpUsedRegs);
  13080. hp2 := p;
  13081. repeat
  13082. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13083. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13084. if (
  13085. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13086. not (cs_opt_size in current_settings.optimizerswitches) or
  13087. (
  13088. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13089. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13090. )
  13091. ) then
  13092. begin
  13093. { Change the MOV instruction to a LEA instruction, and update the
  13094. first operand }
  13095. reference_reset(NewRef, 1, []);
  13096. NewRef.base := taicpu(p).oper[1]^.reg;
  13097. NewRef.scalefactor := 1;
  13098. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13099. taicpu(hp1).opcode := A_LEA;
  13100. taicpu(hp1).loadref(0, NewRef);
  13101. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13102. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13103. begin
  13104. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13105. { Move what is now the LEA instruction to before the ADD instruction }
  13106. Asml.Remove(hp1);
  13107. Asml.InsertBefore(hp1, p);
  13108. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13109. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13110. p := hp1;
  13111. end
  13112. else
  13113. begin
  13114. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13115. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13116. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13117. { hp1 may not be the immediate next instruction under -O3 }
  13118. RemoveCurrentp(p)
  13119. else
  13120. RemoveCurrentp(p, hp1);
  13121. end;
  13122. Result := True;
  13123. end;
  13124. end;
  13125. end;
  13126. end;
  13127. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13128. var
  13129. SubReg: TSubRegister;
  13130. begin
  13131. Result:=false;
  13132. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13133. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13134. with taicpu(p).oper[0]^.ref^ do
  13135. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13136. begin
  13137. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13138. begin
  13139. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13140. taicpu(p).opcode := A_ADD;
  13141. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13142. Result := True;
  13143. end
  13144. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13145. begin
  13146. if (base <> NR_NO) then
  13147. begin
  13148. if (scalefactor <= 1) then
  13149. begin
  13150. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13151. taicpu(p).opcode := A_ADD;
  13152. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13153. Result := True;
  13154. end;
  13155. end
  13156. else
  13157. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13158. if (scalefactor in [2, 4, 8]) then
  13159. begin
  13160. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13161. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13162. taicpu(p).opcode := A_SHL;
  13163. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13164. Result := True;
  13165. end;
  13166. end;
  13167. end;
  13168. end;
  13169. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13170. var
  13171. hp1, hp2: tai;
  13172. NewRef: TReference;
  13173. Distance: Cardinal;
  13174. TempTracking: TAllUsedRegs;
  13175. begin
  13176. Result := False;
  13177. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13178. MatchOpType(taicpu(p),top_const,top_reg) then
  13179. begin
  13180. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13181. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13182. (hp1.typ <> ait_instruction) or
  13183. not
  13184. (
  13185. (cs_opt_level3 in current_settings.optimizerswitches) or
  13186. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13187. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13188. ) then
  13189. Exit;
  13190. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13191. subq $x, %rax
  13192. movq %rax, %rdx
  13193. sarq $63, %rdx
  13194. (%rax still in use)
  13195. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13196. leaq $-x(%rax),%rdx
  13197. movq $x, %rax
  13198. sarq $63, %rdx
  13199. ...which is okay since it breaks the dependency chain between
  13200. subq and movq, but if OptPass2MOV is called first:
  13201. subq $x, %rax
  13202. cqto
  13203. ...which is better in all ways, taking only 2 cycles to execute
  13204. and much smaller in code size.
  13205. }
  13206. { The extra register tracking is quite strenuous }
  13207. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13208. MatchInstruction(hp1, A_MOV, []) then
  13209. begin
  13210. { Update the register tracking to the MOV instruction }
  13211. CopyUsedRegs(TempTracking);
  13212. hp2 := p;
  13213. repeat
  13214. UpdateUsedRegs(tai(hp2.Next));
  13215. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13216. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13217. OptPass2SUB get called again }
  13218. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13219. begin
  13220. { Reset the tracking to the current instruction }
  13221. RestoreUsedRegs(TempTracking);
  13222. ReleaseUsedRegs(TempTracking);
  13223. Result := True;
  13224. Exit;
  13225. end;
  13226. { Reset the tracking to the current instruction }
  13227. RestoreUsedRegs(TempTracking);
  13228. ReleaseUsedRegs(TempTracking);
  13229. { If OptPass2MOV returned True, we don't need to set Result to
  13230. True if hp1 didn't change because the SUB instruction didn't
  13231. get modified and we'll be evaluating hp1 again when the
  13232. peephole optimizer reaches it }
  13233. end;
  13234. { Change:
  13235. subl/q $x,%reg1
  13236. movl/q %reg1,%reg2
  13237. To:
  13238. leal/q $-x(%reg1),%reg2
  13239. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13240. Breaks the dependency chain and potentially permits the removal of
  13241. a CMP instruction if one follows.
  13242. }
  13243. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13244. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13245. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13246. (
  13247. { Instructions are guaranteed to be adjacent on -O2 and under }
  13248. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13249. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13250. ) then
  13251. begin
  13252. TransferUsedRegs(TmpUsedRegs);
  13253. hp2 := p;
  13254. repeat
  13255. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13256. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13257. if (
  13258. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13259. not (cs_opt_size in current_settings.optimizerswitches) or
  13260. (
  13261. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13262. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13263. )
  13264. ) then
  13265. begin
  13266. { Change the MOV instruction to a LEA instruction, and update the
  13267. first operand }
  13268. reference_reset(NewRef, 1, []);
  13269. NewRef.base := taicpu(p).oper[1]^.reg;
  13270. NewRef.scalefactor := 1;
  13271. NewRef.offset := -taicpu(p).oper[0]^.val;
  13272. taicpu(hp1).opcode := A_LEA;
  13273. taicpu(hp1).loadref(0, NewRef);
  13274. TransferUsedRegs(TmpUsedRegs);
  13275. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13276. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13277. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13278. begin
  13279. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13280. { Move what is now the LEA instruction to before the SUB instruction }
  13281. Asml.Remove(hp1);
  13282. Asml.InsertBefore(hp1, p);
  13283. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13284. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13285. p := hp1;
  13286. end
  13287. else
  13288. begin
  13289. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13290. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13291. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13292. { hp1 may not be the immediate next instruction under -O3 }
  13293. RemoveCurrentp(p)
  13294. else
  13295. RemoveCurrentp(p, hp1);
  13296. end;
  13297. Result := True;
  13298. end;
  13299. end;
  13300. end;
  13301. end;
  13302. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13303. begin
  13304. { we can skip all instructions not messing with the stack pointer }
  13305. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13306. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13307. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13308. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13309. ({(taicpu(hp1).ops=0) or }
  13310. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13311. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13312. ) and }
  13313. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13314. )
  13315. ) do
  13316. GetNextInstruction(hp1,hp1);
  13317. Result:=assigned(hp1);
  13318. end;
  13319. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13320. var
  13321. hp1, hp2, hp3, hp4, hp5: tai;
  13322. begin
  13323. Result:=false;
  13324. hp5:=nil;
  13325. { replace
  13326. leal(q) x(<stackpointer>),<stackpointer>
  13327. call procname
  13328. leal(q) -x(<stackpointer>),<stackpointer>
  13329. ret
  13330. by
  13331. jmp procname
  13332. but do it only on level 4 because it destroys stack back traces
  13333. }
  13334. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13335. MatchOpType(taicpu(p),top_ref,top_reg) and
  13336. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13337. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13338. { the -8 or -24 are not required, but bail out early if possible,
  13339. higher values are unlikely }
  13340. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13341. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13342. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13343. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13344. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13345. GetNextInstruction(p, hp1) and
  13346. { Take a copy of hp1 }
  13347. SetAndTest(hp1, hp4) and
  13348. { trick to skip label }
  13349. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13350. SkipSimpleInstructions(hp1) and
  13351. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13352. GetNextInstruction(hp1, hp2) and
  13353. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13354. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13355. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13356. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13357. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13358. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13359. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13360. { Segment register will be NR_NO }
  13361. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13362. GetNextInstruction(hp2, hp3) and
  13363. { trick to skip label }
  13364. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13365. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13366. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13367. SetAndTest(hp3,hp5) and
  13368. GetNextInstruction(hp3,hp3) and
  13369. MatchInstruction(hp3,A_RET,[S_NO])
  13370. )
  13371. ) and
  13372. (taicpu(hp3).ops=0) then
  13373. begin
  13374. taicpu(hp1).opcode := A_JMP;
  13375. taicpu(hp1).is_jmp := true;
  13376. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13377. RemoveCurrentP(p, hp4);
  13378. RemoveInstruction(hp2);
  13379. RemoveInstruction(hp3);
  13380. if Assigned(hp5) then
  13381. begin
  13382. AsmL.Remove(hp5);
  13383. ASmL.InsertBefore(hp5,hp1)
  13384. end;
  13385. Result:=true;
  13386. end;
  13387. end;
  13388. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13389. {$ifdef x86_64}
  13390. var
  13391. hp1, hp2, hp3, hp4, hp5: tai;
  13392. {$endif x86_64}
  13393. begin
  13394. Result:=false;
  13395. {$ifdef x86_64}
  13396. hp5:=nil;
  13397. { replace
  13398. push %rax
  13399. call procname
  13400. pop %rcx
  13401. ret
  13402. by
  13403. jmp procname
  13404. but do it only on level 4 because it destroys stack back traces
  13405. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13406. for all supported calling conventions
  13407. }
  13408. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13409. MatchOpType(taicpu(p),top_reg) and
  13410. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13411. GetNextInstruction(p, hp1) and
  13412. { Take a copy of hp1 }
  13413. SetAndTest(hp1, hp4) and
  13414. { trick to skip label }
  13415. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13416. SkipSimpleInstructions(hp1) and
  13417. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13418. GetNextInstruction(hp1, hp2) and
  13419. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13420. MatchOpType(taicpu(hp2),top_reg) and
  13421. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13422. GetNextInstruction(hp2, hp3) and
  13423. { trick to skip label }
  13424. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13425. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13426. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13427. SetAndTest(hp3,hp5) and
  13428. GetNextInstruction(hp3,hp3) and
  13429. MatchInstruction(hp3,A_RET,[S_NO])
  13430. )
  13431. ) and
  13432. (taicpu(hp3).ops=0) then
  13433. begin
  13434. taicpu(hp1).opcode := A_JMP;
  13435. taicpu(hp1).is_jmp := true;
  13436. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13437. RemoveCurrentP(p, hp4);
  13438. RemoveInstruction(hp2);
  13439. RemoveInstruction(hp3);
  13440. if Assigned(hp5) then
  13441. begin
  13442. AsmL.Remove(hp5);
  13443. ASmL.InsertBefore(hp5,hp1)
  13444. end;
  13445. Result:=true;
  13446. end;
  13447. {$endif x86_64}
  13448. end;
  13449. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13450. var
  13451. Value, RegName: string;
  13452. begin
  13453. Result:=false;
  13454. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13455. begin
  13456. case taicpu(p).oper[0]^.val of
  13457. 0:
  13458. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13459. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13460. begin
  13461. { change "mov $0,%reg" into "xor %reg,%reg" }
  13462. taicpu(p).opcode := A_XOR;
  13463. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13464. Result := True;
  13465. {$ifdef x86_64}
  13466. end
  13467. else if (taicpu(p).opsize = S_Q) then
  13468. begin
  13469. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13470. { The actual optimization }
  13471. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13472. taicpu(p).changeopsize(S_L);
  13473. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13474. Result := True;
  13475. end;
  13476. $1..$FFFFFFFF:
  13477. begin
  13478. { Code size reduction by J. Gareth "Kit" Moreton }
  13479. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13480. case taicpu(p).opsize of
  13481. S_Q:
  13482. begin
  13483. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13484. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13485. { The actual optimization }
  13486. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13487. taicpu(p).changeopsize(S_L);
  13488. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13489. Result := True;
  13490. end;
  13491. else
  13492. { Do nothing };
  13493. end;
  13494. {$endif x86_64}
  13495. end;
  13496. -1:
  13497. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13498. if (cs_opt_size in current_settings.optimizerswitches) and
  13499. (taicpu(p).opsize <> S_B) and
  13500. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13501. begin
  13502. { change "mov $-1,%reg" into "or $-1,%reg" }
  13503. { NOTES:
  13504. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13505. - This operation creates a false dependency on the register, so only do it when optimising for size
  13506. - 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
  13507. }
  13508. taicpu(p).opcode := A_OR;
  13509. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13510. Result := True;
  13511. end;
  13512. else
  13513. { Do nothing };
  13514. end;
  13515. end;
  13516. end;
  13517. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13518. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13519. begin
  13520. Result := False;
  13521. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13522. Exit;
  13523. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13524. so don't bother optimising }
  13525. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13526. Exit;
  13527. if (taicpu(p).oper[0]^.typ <> top_const) or
  13528. { If the value can fit into an 8-bit signed integer, a smaller
  13529. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13530. falls within this range }
  13531. (
  13532. (taicpu(p).oper[0]^.val > -128) and
  13533. (taicpu(p).oper[0]^.val <= 127)
  13534. ) then
  13535. Exit;
  13536. { If we're optimising for size, this is acceptable }
  13537. if (cs_opt_size in current_settings.optimizerswitches) then
  13538. Exit(True);
  13539. if (taicpu(p).oper[1]^.typ = top_reg) and
  13540. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13541. Exit(True);
  13542. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13543. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13544. Exit(True);
  13545. end;
  13546. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13547. var
  13548. hp1: tai;
  13549. Value: TCGInt;
  13550. begin
  13551. Result := False;
  13552. if MatchOpType(taicpu(p), top_const, top_reg) then
  13553. begin
  13554. { Detect:
  13555. andw x, %ax (0 <= x < $8000)
  13556. ...
  13557. movzwl %ax,%eax
  13558. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13559. }
  13560. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13561. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13562. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13563. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13564. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13565. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13566. begin
  13567. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13568. taicpu(hp1).opcode := A_CWDE;
  13569. taicpu(hp1).clearop(0);
  13570. taicpu(hp1).clearop(1);
  13571. taicpu(hp1).ops := 0;
  13572. { A change was made, but not with p, so don't set Result, but
  13573. notify the compiler that a change was made }
  13574. Include(OptsToCheck, aoc_ForceNewIteration);
  13575. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13576. end;
  13577. end;
  13578. { If "not x" is a power of 2 (popcnt = 1), change:
  13579. and $x, %reg/ref
  13580. To:
  13581. btr lb(x), %reg/ref
  13582. }
  13583. if IsBTXAcceptable(p) and
  13584. (
  13585. { Make sure a TEST doesn't follow that plays with the register }
  13586. not GetNextInstruction(p, hp1) or
  13587. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13588. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13589. ) then
  13590. begin
  13591. {$push}{$R-}{$Q-}
  13592. { Value is a sign-extended 32-bit integer - just correct it
  13593. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13594. checks to see if this operand is an immediate. }
  13595. Value := not taicpu(p).oper[0]^.val;
  13596. {$pop}
  13597. {$ifdef x86_64}
  13598. if taicpu(p).opsize = S_L then
  13599. {$endif x86_64}
  13600. Value := Value and $FFFFFFFF;
  13601. if (PopCnt(QWord(Value)) = 1) then
  13602. begin
  13603. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13604. taicpu(p).opcode := A_BTR;
  13605. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13606. Result := True;
  13607. Exit;
  13608. end;
  13609. end;
  13610. end;
  13611. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13612. begin
  13613. Result := False;
  13614. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13615. Exit;
  13616. { Convert:
  13617. movswl %ax,%eax -> cwtl
  13618. movslq %eax,%rax -> cdqe
  13619. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13620. refer to the same opcode and depends only on the assembler's
  13621. current operand-size attribute. [Kit]
  13622. }
  13623. with taicpu(p) do
  13624. case opsize of
  13625. S_WL:
  13626. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13627. begin
  13628. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13629. opcode := A_CWDE;
  13630. clearop(0);
  13631. clearop(1);
  13632. ops := 0;
  13633. Result := True;
  13634. end;
  13635. {$ifdef x86_64}
  13636. S_LQ:
  13637. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13638. begin
  13639. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13640. opcode := A_CDQE;
  13641. clearop(0);
  13642. clearop(1);
  13643. ops := 0;
  13644. Result := True;
  13645. end;
  13646. {$endif x86_64}
  13647. else
  13648. ;
  13649. end;
  13650. end;
  13651. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13652. var
  13653. hp1, hp2: tai;
  13654. IdentityMask, Shift: TCGInt;
  13655. LimitSize: Topsize;
  13656. DoNotMerge: Boolean;
  13657. begin
  13658. Result := False;
  13659. { All these optimisations work on "shr const,%reg" }
  13660. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13661. Exit;
  13662. DoNotMerge := False;
  13663. Shift := taicpu(p).oper[0]^.val;
  13664. LimitSize := taicpu(p).opsize;
  13665. hp1 := p;
  13666. repeat
  13667. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13668. Break;
  13669. { Detect:
  13670. shr x, %reg
  13671. and y, %reg
  13672. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13673. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13674. }
  13675. case taicpu(hp1).opcode of
  13676. A_AND:
  13677. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13678. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13679. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13680. begin
  13681. { Make sure the FLAGS register isn't in use }
  13682. TransferUsedRegs(TmpUsedRegs);
  13683. hp2 := p;
  13684. repeat
  13685. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13686. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13687. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13688. begin
  13689. { Generate the identity mask }
  13690. case taicpu(p).opsize of
  13691. S_B:
  13692. IdentityMask := $FF shr Shift;
  13693. S_W:
  13694. IdentityMask := $FFFF shr Shift;
  13695. S_L:
  13696. IdentityMask := $FFFFFFFF shr Shift;
  13697. {$ifdef x86_64}
  13698. S_Q:
  13699. { We need to force the operands to be unsigned 64-bit
  13700. integers otherwise the wrong value is generated }
  13701. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13702. {$endif x86_64}
  13703. else
  13704. InternalError(2022081501);
  13705. end;
  13706. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13707. begin
  13708. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13709. { All the possible 1 bits are covered, so we can remove the AND }
  13710. hp2 := tai(hp1.Previous);
  13711. RemoveInstruction(hp1);
  13712. { p wasn't actually changed, so don't set Result to True,
  13713. but a change was nonetheless made elsewhere }
  13714. Include(OptsToCheck, aoc_ForceNewIteration);
  13715. { Do another pass in case other AND or MOVZX instructions
  13716. follow }
  13717. hp1 := hp2;
  13718. Continue;
  13719. end;
  13720. end;
  13721. end;
  13722. A_TEST, A_CMP, A_Jcc:
  13723. { Skip over conditional jumps and relevant comparisons }
  13724. Continue;
  13725. A_MOVZX:
  13726. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13727. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13728. begin
  13729. { Since the original register is being read as is, subsequent
  13730. SHRs must not be merged at this point }
  13731. DoNotMerge := True;
  13732. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13733. begin
  13734. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13735. begin
  13736. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13737. { All the possible 1 bits are covered, so we can remove the AND }
  13738. hp2 := tai(hp1.Previous);
  13739. RemoveInstruction(hp1);
  13740. hp1 := hp2;
  13741. end
  13742. else { Different register target }
  13743. begin
  13744. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13745. taicpu(hp1).opcode := A_MOV;
  13746. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13747. case taicpu(hp1).opsize of
  13748. S_BW:
  13749. taicpu(hp1).opsize := S_W;
  13750. S_BL, S_WL:
  13751. taicpu(hp1).opsize := S_L;
  13752. else
  13753. InternalError(2022081503);
  13754. end;
  13755. end;
  13756. end
  13757. else if (Shift > 0) and
  13758. (taicpu(p).opsize = S_W) and
  13759. (taicpu(hp1).opsize = S_WL) and
  13760. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13761. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13762. begin
  13763. { Detect:
  13764. shr x, %ax (x > 0)
  13765. ...
  13766. movzwl %ax,%eax
  13767. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13768. }
  13769. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13770. taicpu(hp1).opcode := A_CWDE;
  13771. taicpu(hp1).clearop(0);
  13772. taicpu(hp1).clearop(1);
  13773. taicpu(hp1).ops := 0;
  13774. end;
  13775. { Move onto the next instruction }
  13776. Continue;
  13777. end;
  13778. A_SHL, A_SAL, A_SHR:
  13779. if (taicpu(hp1).opsize <= LimitSize) and
  13780. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13781. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13782. begin
  13783. { Make sure the sizes don't exceed the register size limit
  13784. (measured by the shift value falling below the limit) }
  13785. if taicpu(hp1).opsize < LimitSize then
  13786. LimitSize := taicpu(hp1).opsize;
  13787. if taicpu(hp1).opcode = A_SHR then
  13788. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13789. else
  13790. begin
  13791. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13792. DoNotMerge := True;
  13793. end;
  13794. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13795. Break;
  13796. { Since we've established that the combined shift is within
  13797. limits, we can actually combine the adjacent SHR
  13798. instructions even if they're different sizes }
  13799. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13800. begin
  13801. hp2 := tai(hp1.Previous);
  13802. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13803. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13804. RemoveInstruction(hp1);
  13805. hp1 := hp2;
  13806. end;
  13807. { Move onto the next instruction }
  13808. Continue;
  13809. end;
  13810. else
  13811. ;
  13812. end;
  13813. Break;
  13814. until False;
  13815. { Detect the following (looking backwards):
  13816. shr %cl,%reg
  13817. shr x, %reg
  13818. Swap the two SHR instructions to minimise a pipeline stall.
  13819. }
  13820. if GetLastInstruction(p, hp1) and
  13821. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13822. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13823. { First operand will be %cl }
  13824. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13825. { Just to be sure }
  13826. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13827. begin
  13828. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13829. { Moving the entries this way ensures the register tracking remains correct }
  13830. Asml.Remove(p);
  13831. Asml.InsertBefore(p, hp1);
  13832. p := hp1;
  13833. { Don't set Result to True because the current instruction is now
  13834. "shr %cl,%reg" and there's nothing more we can do with it }
  13835. end;
  13836. end;
  13837. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13838. var
  13839. hp1, hp2: tai;
  13840. Opposite, SecondOpposite: TAsmOp;
  13841. NewCond: TAsmCond;
  13842. begin
  13843. Result := False;
  13844. { Change:
  13845. add/sub 128,(dest)
  13846. To:
  13847. sub/add -128,(dest)
  13848. This generaally takes fewer bytes to encode because -128 can be stored
  13849. in a signed byte, whereas +128 cannot.
  13850. }
  13851. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13852. begin
  13853. if taicpu(p).opcode = A_ADD then
  13854. Opposite := A_SUB
  13855. else
  13856. Opposite := A_ADD;
  13857. { Be careful if the flags are in use, because the CF flag inverts
  13858. when changing from ADD to SUB and vice versa }
  13859. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13860. GetNextInstruction(p, hp1) then
  13861. begin
  13862. TransferUsedRegs(TmpUsedRegs);
  13863. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13864. hp2 := hp1;
  13865. { Scan ahead to check if everything's safe }
  13866. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13867. begin
  13868. if (hp1.typ <> ait_instruction) then
  13869. { Probably unsafe since the flags are still in use }
  13870. Exit;
  13871. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13872. { Stop searching at an unconditional jump }
  13873. Break;
  13874. if not
  13875. (
  13876. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13877. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13878. ) and
  13879. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13880. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13881. Exit;
  13882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13883. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13884. { Move to the next instruction }
  13885. GetNextInstruction(hp1, hp1);
  13886. end;
  13887. while Assigned(hp2) and (hp2 <> hp1) do
  13888. begin
  13889. NewCond := C_None;
  13890. case taicpu(hp2).condition of
  13891. C_A, C_NBE:
  13892. NewCond := C_BE;
  13893. C_B, C_C, C_NAE:
  13894. NewCond := C_AE;
  13895. C_AE, C_NB, C_NC:
  13896. NewCond := C_B;
  13897. C_BE, C_NA:
  13898. NewCond := C_A;
  13899. else
  13900. { No change needed };
  13901. end;
  13902. if NewCond <> C_None then
  13903. begin
  13904. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13905. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13906. taicpu(hp2).condition := NewCond;
  13907. end
  13908. else
  13909. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13910. begin
  13911. { Because of the flipping of the carry bit, to ensure
  13912. the operation remains equivalent, ADC becomes SBB
  13913. and vice versa, and the constant is not-inverted.
  13914. If multiple ADCs or SBBs appear in a row, each one
  13915. changed causes the carry bit to invert, so they all
  13916. need to be flipped }
  13917. if taicpu(hp2).opcode = A_ADC then
  13918. SecondOpposite := A_SBB
  13919. else
  13920. SecondOpposite := A_ADC;
  13921. if taicpu(hp2).oper[0]^.typ <> top_const then
  13922. { Should have broken out of this optimisation already }
  13923. InternalError(2021112901);
  13924. 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]^) + ' -> ' +
  13925. 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);
  13926. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13927. taicpu(hp2).opcode := SecondOpposite;
  13928. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13929. end;
  13930. { Move to the next instruction }
  13931. GetNextInstruction(hp2, hp2);
  13932. end;
  13933. if (hp2 <> hp1) then
  13934. InternalError(2021111501);
  13935. end;
  13936. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13937. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13938. taicpu(p).opcode := Opposite;
  13939. taicpu(p).oper[0]^.val := -128;
  13940. { No further optimisations can be made on this instruction, so move
  13941. onto the next one to save time }
  13942. p := tai(p.Next);
  13943. UpdateUsedRegs(p);
  13944. Result := True;
  13945. Exit;
  13946. end;
  13947. { Detect:
  13948. add/sub %reg2,(dest)
  13949. add/sub x, (dest)
  13950. (dest can be a register or a reference)
  13951. Swap the instructions to minimise a pipeline stall. This reverses the
  13952. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13953. optimisations could be made.
  13954. }
  13955. if (taicpu(p).oper[0]^.typ = top_reg) and
  13956. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13957. (
  13958. (
  13959. (taicpu(p).oper[1]^.typ = top_reg) and
  13960. { We can try searching further ahead if we're writing to a register }
  13961. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13962. ) or
  13963. (
  13964. (taicpu(p).oper[1]^.typ = top_ref) and
  13965. GetNextInstruction(p, hp1)
  13966. )
  13967. ) and
  13968. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13969. (taicpu(hp1).oper[0]^.typ = top_const) and
  13970. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13971. begin
  13972. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13973. TransferUsedRegs(TmpUsedRegs);
  13974. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13975. hp2 := p;
  13976. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13977. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13978. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13979. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13980. begin
  13981. asml.remove(hp1);
  13982. asml.InsertBefore(hp1, p);
  13983. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13984. Result := True;
  13985. end;
  13986. end;
  13987. end;
  13988. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13989. var
  13990. hp1: tai;
  13991. begin
  13992. Result:=false;
  13993. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13994. while GetNextInstruction(p, hp1) and
  13995. TrySwapMovCmp(p, hp1) do
  13996. begin
  13997. if MatchInstruction(hp1, A_MOV, []) then
  13998. begin
  13999. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14000. begin
  14001. { A little hacky, but since CMP doesn't read the flags, only
  14002. modify them, it's safe if they get scrambled by MOV -> XOR }
  14003. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14004. Result := PostPeepholeOptMov(hp1);
  14005. {$ifdef x86_64}
  14006. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14007. { Used to shrink instruction size }
  14008. PostPeepholeOptXor(hp1);
  14009. {$endif x86_64}
  14010. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14011. end
  14012. else
  14013. begin
  14014. Result := PostPeepholeOptMov(hp1);
  14015. {$ifdef x86_64}
  14016. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14017. { Used to shrink instruction size }
  14018. PostPeepholeOptXor(hp1);
  14019. {$endif x86_64}
  14020. end;
  14021. end;
  14022. { Enabling this flag is actually a null operation, but it marks
  14023. the code as 'modified' during this pass }
  14024. Include(OptsToCheck, aoc_ForceNewIteration);
  14025. end;
  14026. { change "cmp $0, %reg" to "test %reg, %reg" }
  14027. if MatchOpType(taicpu(p),top_const,top_reg) and
  14028. (taicpu(p).oper[0]^.val = 0) then
  14029. begin
  14030. taicpu(p).opcode := A_TEST;
  14031. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14032. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14033. Result:=true;
  14034. end;
  14035. end;
  14036. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14037. var
  14038. IsTestConstX, IsValid : Boolean;
  14039. hp1,hp2 : tai;
  14040. begin
  14041. Result:=false;
  14042. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14043. if (taicpu(p).opcode = A_TEST) then
  14044. while GetNextInstruction(p, hp1) and
  14045. TrySwapMovCmp(p, hp1) do
  14046. begin
  14047. if MatchInstruction(hp1, A_MOV, []) then
  14048. begin
  14049. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14050. begin
  14051. { A little hacky, but since TEST doesn't read the flags, only
  14052. modify them, it's safe if they get scrambled by MOV -> XOR }
  14053. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14054. Result := PostPeepholeOptMov(hp1);
  14055. {$ifdef x86_64}
  14056. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14057. { Used to shrink instruction size }
  14058. PostPeepholeOptXor(hp1);
  14059. {$endif x86_64}
  14060. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14061. end
  14062. else
  14063. begin
  14064. Result := PostPeepholeOptMov(hp1);
  14065. {$ifdef x86_64}
  14066. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14067. { Used to shrink instruction size }
  14068. PostPeepholeOptXor(hp1);
  14069. {$endif x86_64}
  14070. end;
  14071. end;
  14072. { Enabling this flag is actually a null operation, but it marks
  14073. the code as 'modified' during this pass }
  14074. Include(OptsToCheck, aoc_ForceNewIteration);
  14075. end;
  14076. { If x is a power of 2 (popcnt = 1), change:
  14077. or $x, %reg/ref
  14078. To:
  14079. bts lb(x), %reg/ref
  14080. }
  14081. if (taicpu(p).opcode = A_OR) and
  14082. IsBTXAcceptable(p) and
  14083. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14084. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14085. (
  14086. { Don't optimise if a test instruction follows }
  14087. not GetNextInstruction(p, hp1) or
  14088. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14089. ) then
  14090. begin
  14091. 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);
  14092. taicpu(p).opcode := A_BTS;
  14093. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14094. Result := True;
  14095. Exit;
  14096. end;
  14097. { If x is a power of 2 (popcnt = 1), change:
  14098. test $x, %reg/ref
  14099. je / sete / cmove (or jne / setne)
  14100. To:
  14101. bt lb(x), %reg/ref
  14102. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14103. }
  14104. if (taicpu(p).opcode = A_TEST) and
  14105. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14106. (taicpu(p).oper[0]^.typ = top_const) and
  14107. (
  14108. (cs_opt_size in current_settings.optimizerswitches) or
  14109. (
  14110. (taicpu(p).oper[1]^.typ = top_reg) and
  14111. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14112. ) or
  14113. (
  14114. (taicpu(p).oper[1]^.typ <> top_reg) and
  14115. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14116. )
  14117. ) and
  14118. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14119. { For sizes less than S_L, the byte size is equal or larger with BT,
  14120. so don't bother optimising }
  14121. (taicpu(p).opsize >= S_L) then
  14122. begin
  14123. IsValid := True;
  14124. { Check the next set of instructions, watching the FLAGS register
  14125. and the conditions used }
  14126. TransferUsedRegs(TmpUsedRegs);
  14127. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14128. hp1 := p;
  14129. hp2 := nil;
  14130. while GetNextInstruction(hp1, hp1) do
  14131. begin
  14132. if not Assigned(hp2) then
  14133. { The first instruction after TEST }
  14134. hp2 := hp1;
  14135. if (hp1.typ <> ait_instruction) then
  14136. begin
  14137. { If the flags are no longer in use, everything is fine }
  14138. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14139. IsValid := False;
  14140. Break;
  14141. end;
  14142. case taicpu(hp1).condition of
  14143. C_None:
  14144. begin
  14145. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14146. { Something is not quite normal, so play safe and don't change }
  14147. IsValid := False;
  14148. Break;
  14149. end;
  14150. C_E, C_Z, C_NE, C_NZ:
  14151. { This is fine };
  14152. else
  14153. begin
  14154. { Unsupported condition }
  14155. IsValid := False;
  14156. Break;
  14157. end;
  14158. end;
  14159. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14160. end;
  14161. if IsValid then
  14162. begin
  14163. while hp2 <> hp1 do
  14164. begin
  14165. case taicpu(hp2).condition of
  14166. C_Z, C_E:
  14167. taicpu(hp2).condition := C_NC;
  14168. C_NZ, C_NE:
  14169. taicpu(hp2).condition := C_C;
  14170. else
  14171. { Should not get this by this point }
  14172. InternalError(2022110701);
  14173. end;
  14174. GetNextInstruction(hp2, hp2);
  14175. end;
  14176. 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);
  14177. taicpu(p).opcode := A_BT;
  14178. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14179. Result := True;
  14180. Exit;
  14181. end;
  14182. end;
  14183. { removes the line marked with (x) from the sequence
  14184. and/or/xor/add/sub/... $x, %y
  14185. test/or %y, %y | test $-1, %y (x)
  14186. j(n)z _Label
  14187. as the first instruction already adjusts the ZF
  14188. %y operand may also be a reference }
  14189. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14190. MatchOperand(taicpu(p).oper[0]^,-1);
  14191. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14192. GetLastInstruction(p, hp1) and
  14193. (tai(hp1).typ = ait_instruction) and
  14194. GetNextInstruction(p,hp2) and
  14195. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14196. case taicpu(hp1).opcode Of
  14197. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14198. { These two instructions set the zero flag if the result is zero }
  14199. A_POPCNT, A_LZCNT:
  14200. begin
  14201. if (
  14202. { With POPCNT, an input of zero will set the zero flag
  14203. because the population count of zero is zero }
  14204. (taicpu(hp1).opcode = A_POPCNT) and
  14205. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14206. (
  14207. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14208. { Faster than going through the second half of the 'or'
  14209. condition below }
  14210. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14211. )
  14212. ) or (
  14213. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14214. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14215. { and in case of carry for A(E)/B(E)/C/NC }
  14216. (
  14217. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14218. (
  14219. (taicpu(hp1).opcode <> A_ADD) and
  14220. (taicpu(hp1).opcode <> A_SUB) and
  14221. (taicpu(hp1).opcode <> A_LZCNT)
  14222. )
  14223. )
  14224. ) then
  14225. begin
  14226. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14227. RemoveCurrentP(p, hp2);
  14228. Result:=true;
  14229. Exit;
  14230. end;
  14231. end;
  14232. A_SHL, A_SAL, A_SHR, A_SAR:
  14233. begin
  14234. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14235. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14236. { therefore, it's only safe to do this optimization for }
  14237. { shifts by a (nonzero) constant }
  14238. (taicpu(hp1).oper[0]^.typ = top_const) and
  14239. (taicpu(hp1).oper[0]^.val <> 0) and
  14240. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14241. { and in case of carry for A(E)/B(E)/C/NC }
  14242. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14243. begin
  14244. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14245. RemoveCurrentP(p, hp2);
  14246. Result:=true;
  14247. Exit;
  14248. end;
  14249. end;
  14250. A_DEC, A_INC, A_NEG:
  14251. begin
  14252. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14253. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14254. { and in case of carry for A(E)/B(E)/C/NC }
  14255. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14256. begin
  14257. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14258. RemoveCurrentP(p, hp2);
  14259. Result:=true;
  14260. Exit;
  14261. end;
  14262. end;
  14263. A_ANDN, A_BZHI:
  14264. begin
  14265. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14266. { Only the zero and sign flags are consistent with what the result is }
  14267. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14268. begin
  14269. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14270. RemoveCurrentP(p, hp2);
  14271. Result:=true;
  14272. Exit;
  14273. end;
  14274. end;
  14275. A_BEXTR:
  14276. begin
  14277. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14278. { Only the zero flag is set }
  14279. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14280. begin
  14281. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14282. RemoveCurrentP(p, hp2);
  14283. Result:=true;
  14284. Exit;
  14285. end;
  14286. end;
  14287. else
  14288. ;
  14289. end; { case }
  14290. { change "test $-1,%reg" into "test %reg,%reg" }
  14291. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14292. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14293. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14294. if MatchInstruction(p, A_OR, []) and
  14295. { Can only match if they're both registers }
  14296. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14297. begin
  14298. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14299. taicpu(p).opcode := A_TEST;
  14300. { No need to set Result to True, as we've done all the optimisations we can }
  14301. end;
  14302. end;
  14303. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14304. var
  14305. hp1,hp3 : tai;
  14306. {$ifndef x86_64}
  14307. hp2 : taicpu;
  14308. {$endif x86_64}
  14309. begin
  14310. Result:=false;
  14311. hp3:=nil;
  14312. {$ifndef x86_64}
  14313. { don't do this on modern CPUs, this really hurts them due to
  14314. broken call/ret pairing }
  14315. if (current_settings.optimizecputype < cpu_Pentium2) and
  14316. not(cs_create_pic in current_settings.moduleswitches) and
  14317. GetNextInstruction(p, hp1) and
  14318. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14319. MatchOpType(taicpu(hp1),top_ref) and
  14320. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14321. begin
  14322. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14323. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14324. InsertLLItem(p.previous, p, hp2);
  14325. taicpu(p).opcode := A_JMP;
  14326. taicpu(p).is_jmp := true;
  14327. RemoveInstruction(hp1);
  14328. Result:=true;
  14329. end
  14330. else
  14331. {$endif x86_64}
  14332. { replace
  14333. call procname
  14334. ret
  14335. by
  14336. jmp procname
  14337. but do it only on level 4 because it destroys stack back traces
  14338. else if the subroutine is marked as no return, remove the ret
  14339. }
  14340. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14341. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14342. GetNextInstruction(p, hp1) and
  14343. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14344. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14345. SetAndTest(hp1,hp3) and
  14346. GetNextInstruction(hp1,hp1) and
  14347. MatchInstruction(hp1,A_RET,[S_NO])
  14348. )
  14349. ) and
  14350. (taicpu(hp1).ops=0) then
  14351. begin
  14352. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14353. { we might destroy stack alignment here if we do not do a call }
  14354. (target_info.stackalign<=sizeof(SizeUInt)) then
  14355. begin
  14356. taicpu(p).opcode := A_JMP;
  14357. taicpu(p).is_jmp := true;
  14358. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14359. end
  14360. else
  14361. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14362. RemoveInstruction(hp1);
  14363. if Assigned(hp3) then
  14364. begin
  14365. AsmL.Remove(hp3);
  14366. AsmL.InsertBefore(hp3,p)
  14367. end;
  14368. Result:=true;
  14369. end;
  14370. end;
  14371. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14372. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14373. begin
  14374. case OpSize of
  14375. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14376. Result := (Val <= $FF) and (Val >= -128);
  14377. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14378. Result := (Val <= $FFFF) and (Val >= -32768);
  14379. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14380. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14381. else
  14382. Result := True;
  14383. end;
  14384. end;
  14385. var
  14386. hp1, hp2 : tai;
  14387. SizeChange: Boolean;
  14388. PreMessage: string;
  14389. begin
  14390. Result := False;
  14391. if (taicpu(p).oper[0]^.typ = top_reg) and
  14392. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14393. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14394. begin
  14395. { Change (using movzbl %al,%eax as an example):
  14396. movzbl %al, %eax movzbl %al, %eax
  14397. cmpl x, %eax testl %eax,%eax
  14398. To:
  14399. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14400. movzbl %al, %eax movzbl %al, %eax
  14401. Smaller instruction and minimises pipeline stall as the CPU
  14402. doesn't have to wait for the register to get zero-extended. [Kit]
  14403. Also allow if the smaller of the two registers is being checked,
  14404. as this still removes the false dependency.
  14405. }
  14406. if
  14407. (
  14408. (
  14409. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14410. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14411. ) or (
  14412. { If MatchOperand returns True, they must both be registers }
  14413. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14414. )
  14415. ) and
  14416. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14417. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14418. begin
  14419. 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);
  14420. asml.Remove(hp1);
  14421. asml.InsertBefore(hp1, p);
  14422. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14423. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14424. begin
  14425. taicpu(hp1).opcode := A_TEST;
  14426. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14427. end;
  14428. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14429. case taicpu(p).opsize of
  14430. S_BW, S_BL:
  14431. begin
  14432. SizeChange := taicpu(hp1).opsize <> S_B;
  14433. taicpu(hp1).changeopsize(S_B);
  14434. end;
  14435. S_WL:
  14436. begin
  14437. SizeChange := taicpu(hp1).opsize <> S_W;
  14438. taicpu(hp1).changeopsize(S_W);
  14439. end
  14440. else
  14441. InternalError(2020112701);
  14442. end;
  14443. UpdateUsedRegs(tai(p.Next));
  14444. { Check if the register is used aferwards - if not, we can
  14445. remove the movzx instruction completely }
  14446. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14447. begin
  14448. { Hp1 is a better position than p for debugging purposes }
  14449. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14450. RemoveCurrentp(p, hp1);
  14451. Result := True;
  14452. end;
  14453. if SizeChange then
  14454. DebugMsg(SPeepholeOptimization + PreMessage +
  14455. 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)
  14456. else
  14457. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14458. Exit;
  14459. end;
  14460. { Change (using movzwl %ax,%eax as an example):
  14461. movzwl %ax, %eax
  14462. movb %al, (dest) (Register is smaller than read register in movz)
  14463. To:
  14464. movb %al, (dest) (Move one back to avoid a false dependency)
  14465. movzwl %ax, %eax
  14466. }
  14467. if (taicpu(hp1).opcode = A_MOV) and
  14468. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14469. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14470. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14471. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14472. begin
  14473. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14474. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14475. asml.Remove(hp1);
  14476. asml.InsertBefore(hp1, p);
  14477. if taicpu(hp1).oper[1]^.typ = top_reg then
  14478. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14479. { Check if the register is used aferwards - if not, we can
  14480. remove the movzx instruction completely }
  14481. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14482. begin
  14483. { Hp1 is a better position than p for debugging purposes }
  14484. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14485. RemoveCurrentp(p, hp1);
  14486. Result := True;
  14487. end;
  14488. Exit;
  14489. end;
  14490. end;
  14491. end;
  14492. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14493. var
  14494. hp1: tai;
  14495. {$ifdef x86_64}
  14496. PreMessage, RegName: string;
  14497. {$endif x86_64}
  14498. begin
  14499. Result := False;
  14500. { If x is a power of 2 (popcnt = 1), change:
  14501. xor $x, %reg/ref
  14502. To:
  14503. btc lb(x), %reg/ref
  14504. }
  14505. if IsBTXAcceptable(p) and
  14506. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14507. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14508. (
  14509. { Don't optimise if a test instruction follows }
  14510. not GetNextInstruction(p, hp1) or
  14511. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14512. ) then
  14513. begin
  14514. 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);
  14515. taicpu(p).opcode := A_BTC;
  14516. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14517. Result := True;
  14518. Exit;
  14519. end;
  14520. {$ifdef x86_64}
  14521. { Code size reduction by J. Gareth "Kit" Moreton }
  14522. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14523. as this removes the REX prefix }
  14524. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14525. Exit;
  14526. if taicpu(p).oper[0]^.typ <> top_reg then
  14527. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14528. InternalError(2018011500);
  14529. case taicpu(p).opsize of
  14530. S_Q:
  14531. begin
  14532. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14533. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14534. { The actual optimization }
  14535. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14536. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14537. taicpu(p).changeopsize(S_L);
  14538. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14539. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14540. end;
  14541. else
  14542. ;
  14543. end;
  14544. {$endif x86_64}
  14545. end;
  14546. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14547. var
  14548. XReg: TRegister;
  14549. begin
  14550. Result := False;
  14551. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14552. Smaller encoding and slightly faster on some platforms (also works for
  14553. ZMM-sized registers) }
  14554. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14555. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14556. begin
  14557. XReg := taicpu(p).oper[0]^.reg;
  14558. if (taicpu(p).oper[1]^.reg = XReg) then
  14559. begin
  14560. taicpu(p).changeopsize(S_XMM);
  14561. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14562. if (cs_opt_size in current_settings.optimizerswitches) then
  14563. begin
  14564. { Change input registers to %xmm0 to reduce size. Note that
  14565. there's a risk of a false dependency doing this, so only
  14566. optimise for size here }
  14567. XReg := NR_XMM0;
  14568. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14569. end
  14570. else
  14571. begin
  14572. setsubreg(XReg, R_SUBMMX);
  14573. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14574. end;
  14575. taicpu(p).oper[0]^.reg := XReg;
  14576. taicpu(p).oper[1]^.reg := XReg;
  14577. Result := True;
  14578. end;
  14579. end;
  14580. end;
  14581. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14582. var
  14583. OperIdx: Integer;
  14584. begin
  14585. for OperIdx := 0 to p.ops - 1 do
  14586. if p.oper[OperIdx]^.typ = top_ref then
  14587. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14588. end;
  14589. end.