aoptx86.pas 733 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. private
  73. function SkipSimpleInstructions(var hp1: tai): Boolean;
  74. protected
  75. class function IsMOVZXAcceptable: Boolean; static; inline;
  76. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  77. { Attempts to allocate a volatile integer register for use between p and hp,
  78. using AUsedRegs for the current register usage information. Returns NR_NO
  79. if no free register could be found }
  80. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  81. { Attempts to allocate a volatile MM register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  86. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  87. { checks whether reading the value in reg1 depends on the value of reg2. This
  88. is very similar to SuperRegisterEquals, except it takes into account that
  89. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  90. depend on the value in AH). }
  91. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  92. { Replaces all references to AOldReg in a memory reference to ANewReg }
  93. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an operand to ANewReg }
  95. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  96. { Replaces all references to AOldReg in an instruction to ANewReg,
  97. except where the register is being written }
  98. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  99. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  100. or writes to a global symbol }
  101. class function IsRefSafe(const ref: PReference): Boolean; static;
  102. { Returns true if the given MOV instruction can be safely converted to CMOV }
  103. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  104. { Like UpdateUsedRegs, but ignores deallocations }
  105. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  106. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  107. class function IsBTXAcceptable(p : tai) : boolean; static;
  108. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  109. conversion was successful }
  110. function ConvertLEA(const p : taicpu): Boolean;
  111. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  112. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  113. procedure DebugMsg(const s : string; p : tai);inline;
  114. class function IsExitCode(p : tai) : boolean; static;
  115. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  116. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  117. procedure RemoveLastDeallocForFuncRes(p : tai);
  118. function DoArithCombineOpt(var p : tai) : Boolean;
  119. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  120. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  121. function PrePeepholeOptSxx(var p : tai) : boolean;
  122. function PrePeepholeOptIMUL(var p : tai) : boolean;
  123. function PrePeepholeOptAND(var p : tai) : boolean;
  124. function OptPass1Test(var p: tai): boolean;
  125. function OptPass1Add(var p: tai): boolean;
  126. function OptPass1AND(var p : tai) : boolean;
  127. function OptPass1CMOVcc(var p: tai): Boolean;
  128. function OptPass1_V_MOVAP(var p : tai) : boolean;
  129. function OptPass1VOP(var p : tai) : boolean;
  130. function OptPass1MOV(var p : tai) : boolean;
  131. function OptPass1Movx(var p : tai) : boolean;
  132. function OptPass1MOVXX(var p : tai) : boolean;
  133. function OptPass1OP(var p : tai) : boolean;
  134. function OptPass1LEA(var p : tai) : boolean;
  135. function OptPass1Sub(var p : tai) : boolean;
  136. function OptPass1SHLSAL(var p : tai) : boolean;
  137. function OptPass1SHR(var p : tai) : boolean;
  138. function OptPass1FSTP(var p : tai) : boolean;
  139. function OptPass1FLD(var p : tai) : boolean;
  140. function OptPass1Cmp(var p : tai) : boolean;
  141. function OptPass1PXor(var p : tai) : boolean;
  142. function OptPass1VPXor(var p: tai): boolean;
  143. function OptPass1Imul(var p : tai) : boolean;
  144. function OptPass1Jcc(var p : tai) : boolean;
  145. function OptPass1SHXX(var p: tai): boolean;
  146. function OptPass1VMOVDQ(var p: tai): Boolean;
  147. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  148. function OptPass1STCCLC(var p: tai): Boolean;
  149. function OptPass2STCCLC(var p: tai): Boolean;
  150. function OptPass2CMOVcc(var p: tai): Boolean;
  151. function OptPass2Movx(var p : tai): Boolean;
  152. function OptPass2MOV(var p : tai) : boolean;
  153. function OptPass2Imul(var p : tai) : boolean;
  154. function OptPass2Jmp(var p : tai) : boolean;
  155. function OptPass2Jcc(var p : tai) : boolean;
  156. function OptPass2Lea(var p: tai): Boolean;
  157. function OptPass2SUB(var p: tai): Boolean;
  158. function OptPass2ADD(var p : tai): Boolean;
  159. function OptPass2SETcc(var p : tai) : boolean;
  160. function OptPass2Cmp(var p: tai): Boolean;
  161. function OptPass2Test(var p: tai): Boolean;
  162. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  163. function PostPeepholeOptMov(var p : tai) : Boolean;
  164. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  165. function PostPeepholeOptXor(var p : tai) : Boolean;
  166. function PostPeepholeOptAnd(var p : tai) : boolean;
  167. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  168. function PostPeepholeOptCmp(var p : tai) : Boolean;
  169. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  170. function PostPeepholeOptCall(var p : tai) : Boolean;
  171. function PostPeepholeOptLea(var p : tai) : Boolean;
  172. function PostPeepholeOptPush(var p: tai): Boolean;
  173. function PostPeepholeOptShr(var p : tai) : boolean;
  174. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  175. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  176. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  177. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  178. function TrySwapMovOp(var p, hp1: tai): Boolean;
  179. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  180. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  181. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  182. { Processor-dependent reference optimisation }
  183. class procedure OptimizeRefs(var p: taicpu); static;
  184. end;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  187. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  188. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  189. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  190. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  191. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  192. {$if max_operands>2}
  193. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  194. {$endif max_operands>2}
  195. function RefsEqual(const r1, r2: treference): boolean;
  196. { Note that Result is set to True if the references COULD overlap but the
  197. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  198. might still overlap because %reg2 could be equal to %reg1-4 }
  199. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  200. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  201. { returns true, if ref is a reference using only the registers passed as base and index
  202. and having an offset }
  203. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  204. implementation
  205. uses
  206. cutils,verbose,
  207. systems,
  208. globals,
  209. cpuinfo,
  210. procinfo,
  211. paramgr,
  212. aasmbase,
  213. aoptbase,aoptutils,
  214. symconst,symsym,
  215. cgx86,
  216. itcpugas;
  217. {$ifndef 8086}
  218. const
  219. MAX_CMOV_INSTRUCTIONS = 4;
  220. MAX_CMOV_REGISTERS = 8;
  221. type
  222. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  223. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  224. tsProcessed);
  225. { For OptPass2Jcc }
  226. TCMOVTracking = object
  227. private
  228. CMOVScore, ConstCount: LongInt;
  229. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  230. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  231. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  232. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  233. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  234. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  235. fOptimizer: TX86AsmOptimizer;
  236. fLabel: TAsmSymbol;
  237. fInsertionPoint,
  238. fCondition,
  239. fInitialJump,
  240. fFirstMovBlock,
  241. fFirstMovBlockStop,
  242. fSecondJump,
  243. fThirdJump,
  244. fSecondMovBlock,
  245. fSecondMovBlockStop,
  246. fMidLabel,
  247. fEndLabel,
  248. fAllocationRange: tai;
  249. fState: TCMovTrackingState;
  250. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  251. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  252. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  253. public
  254. RegisterTracking: TAllUsedRegs;
  255. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  256. destructor Done;
  257. procedure Process(out new_p: tai);
  258. property State: TCMovTrackingState read fState;
  259. end;
  260. PCMOVTracking = ^TCMOVTracking;
  261. {$endif 8086}
  262. {$ifdef DEBUG_AOPTCPU}
  263. const
  264. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  265. {$else DEBUG_AOPTCPU}
  266. { Empty strings help the optimizer to remove string concatenations that won't
  267. ever appear to the user on release builds. [Kit] }
  268. const
  269. SPeepholeOptimization = '';
  270. {$endif DEBUG_AOPTCPU}
  271. LIST_STEP_SIZE = 4;
  272. type
  273. TJumpTrackingItem = class(TLinkedListItem)
  274. private
  275. FSymbol: TAsmSymbol;
  276. FRefs: LongInt;
  277. public
  278. constructor Create(ASymbol: TAsmSymbol);
  279. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  280. property Symbol: TAsmSymbol read FSymbol;
  281. property Refs: LongInt read FRefs;
  282. end;
  283. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  284. begin
  285. inherited Create;
  286. FSymbol := ASymbol;
  287. FRefs := 0;
  288. end;
  289. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  290. begin
  291. Inc(FRefs);
  292. end;
  293. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  294. begin
  295. result :=
  296. (instr.typ = ait_instruction) and
  297. (taicpu(instr).opcode = op) and
  298. ((opsize = []) or (taicpu(instr).opsize in opsize));
  299. end;
  300. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  301. begin
  302. result :=
  303. (instr.typ = ait_instruction) and
  304. ((taicpu(instr).opcode = op1) or
  305. (taicpu(instr).opcode = op2)
  306. ) and
  307. ((opsize = []) or (taicpu(instr).opsize in opsize));
  308. end;
  309. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  310. begin
  311. result :=
  312. (instr.typ = ait_instruction) and
  313. ((taicpu(instr).opcode = op1) or
  314. (taicpu(instr).opcode = op2) or
  315. (taicpu(instr).opcode = op3)
  316. ) and
  317. ((opsize = []) or (taicpu(instr).opsize in opsize));
  318. end;
  319. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  320. const opsize : topsizes) : boolean;
  321. var
  322. op : TAsmOp;
  323. begin
  324. result:=false;
  325. if (instr.typ <> ait_instruction) or
  326. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  327. exit;
  328. for op in ops do
  329. begin
  330. if taicpu(instr).opcode = op then
  331. begin
  332. result:=true;
  333. exit;
  334. end;
  335. end;
  336. end;
  337. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  338. begin
  339. result := (oper.typ = top_reg) and (oper.reg = reg);
  340. end;
  341. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  342. begin
  343. result := (oper.typ = top_const) and (oper.val = a);
  344. end;
  345. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  346. begin
  347. result := oper1.typ = oper2.typ;
  348. if result then
  349. case oper1.typ of
  350. top_const:
  351. Result:=oper1.val = oper2.val;
  352. top_reg:
  353. Result:=oper1.reg = oper2.reg;
  354. top_ref:
  355. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  356. else
  357. internalerror(2013102801);
  358. end
  359. end;
  360. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  361. begin
  362. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  363. if result then
  364. case oper1.typ of
  365. top_const:
  366. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  367. top_reg:
  368. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  369. top_ref:
  370. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  371. else
  372. internalerror(2020052401);
  373. end
  374. end;
  375. function RefsEqual(const r1, r2: treference): boolean;
  376. begin
  377. RefsEqual :=
  378. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  379. (r1.relsymbol = r2.relsymbol) and
  380. (r1.segment = r2.segment) and (r1.base = r2.base) and
  381. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  382. (r1.offset = r2.offset) and
  383. (r1.volatility + r2.volatility = []);
  384. end;
  385. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  386. begin
  387. if (r1.symbol<>r2.symbol) then
  388. { If the index registers are different, there's a chance one could
  389. be set so it equals the other symbol }
  390. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  391. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  392. (r1.relsymbol = r2.relsymbol) and
  393. (r1.segment = r2.segment) and (r1.base = r2.base) and
  394. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  395. (r1.volatility + r2.volatility = []) then
  396. { In this case, it all depends on the offsets }
  397. Exit(abs(r1.offset - r2.offset) < Range);
  398. { There's a chance things MIGHT overlap, so take no chances }
  399. Result := True;
  400. end;
  401. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  402. begin
  403. Result:=(ref.offset=0) and
  404. (ref.scalefactor in [0,1]) and
  405. (ref.segment=NR_NO) and
  406. (ref.symbol=nil) and
  407. (ref.relsymbol=nil) and
  408. ((base=NR_INVALID) or
  409. (ref.base=base)) and
  410. ((index=NR_INVALID) or
  411. (ref.index=index)) and
  412. (ref.volatility=[]);
  413. end;
  414. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  415. begin
  416. Result:=(ref.scalefactor in [0,1]) and
  417. (ref.segment=NR_NO) and
  418. (ref.symbol=nil) and
  419. (ref.relsymbol=nil) and
  420. ((base=NR_INVALID) or
  421. (ref.base=base)) and
  422. ((index=NR_INVALID) or
  423. (ref.index=index)) and
  424. (ref.volatility=[]);
  425. end;
  426. function InstrReadsFlags(p: tai): boolean;
  427. begin
  428. InstrReadsFlags := true;
  429. case p.typ of
  430. ait_instruction:
  431. if InsProp[taicpu(p).opcode].Ch*
  432. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  433. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  434. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  435. exit;
  436. ait_label:
  437. exit;
  438. else
  439. ;
  440. end;
  441. InstrReadsFlags := false;
  442. end;
  443. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  444. begin
  445. Next:=Current;
  446. repeat
  447. Result:=GetNextInstruction(Next,Next);
  448. until not (Result) or
  449. not(cs_opt_level3 in current_settings.optimizerswitches) or
  450. (Next.typ<>ait_instruction) or
  451. RegInInstruction(reg,Next) or
  452. is_calljmp(taicpu(Next).opcode);
  453. end;
  454. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  455. var
  456. GetNextResult: Boolean;
  457. begin
  458. Result:=0;
  459. Next:=Current;
  460. repeat
  461. GetNextResult := GetNextInstruction(Next,Next);
  462. if GetNextResult then
  463. Inc(Result)
  464. else
  465. { Must return zero upon hitting the end of the linked list without a match }
  466. Result := 0;
  467. until not (GetNextResult) or
  468. not(cs_opt_level3 in current_settings.optimizerswitches) or
  469. (Next.typ<>ait_instruction) or
  470. RegInInstruction(reg,Next) or
  471. is_calljmp(taicpu(Next).opcode);
  472. end;
  473. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  474. procedure TrackJump(Symbol: TAsmSymbol);
  475. var
  476. Search: TJumpTrackingItem;
  477. begin
  478. { See if an entry already exists in our jump tracking list
  479. (faster to search backwards due to the higher chance of
  480. matching destinations) }
  481. Search := TJumpTrackingItem(JumpTracking.Last);
  482. while Assigned(Search) do
  483. begin
  484. if Search.Symbol = Symbol then
  485. begin
  486. { Found it - remove it so it can be pushed to the front }
  487. JumpTracking.Remove(Search);
  488. Break;
  489. end;
  490. Search := TJumpTrackingItem(Search.Previous);
  491. end;
  492. if not Assigned(Search) then
  493. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  494. JumpTracking.Concat(Search);
  495. Search.IncRefs;
  496. end;
  497. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  498. var
  499. Search: TJumpTrackingItem;
  500. begin
  501. Result := False;
  502. { See if this label appears in the tracking list }
  503. Search := TJumpTrackingItem(JumpTracking.Last);
  504. while Assigned(Search) do
  505. begin
  506. if Search.Symbol = Symbol then
  507. begin
  508. { Found it - let's see what we can discover }
  509. if Search.Symbol.getrefs = Search.Refs then
  510. begin
  511. { Success - all the references are accounted for }
  512. JumpTracking.Remove(Search);
  513. Search.Free;
  514. { It is logically impossible for CrossJump to be false here
  515. because we must have run into a conditional jump for
  516. this label at some point }
  517. if not CrossJump then
  518. InternalError(2022041710);
  519. if JumpTracking.First = nil then
  520. { Tracking list is now empty - no more cross jumps }
  521. CrossJump := False;
  522. Result := True;
  523. Exit;
  524. end;
  525. { If the references don't match, it's possible to enter
  526. this label through other means, so drop out }
  527. Exit;
  528. end;
  529. Search := TJumpTrackingItem(Search.Previous);
  530. end;
  531. end;
  532. var
  533. Next_Label: tai;
  534. begin
  535. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  536. Next := Current;
  537. repeat
  538. Result := GetNextInstruction(Next,Next);
  539. if not Result then
  540. Break;
  541. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  542. if is_calljmpuncondret(taicpu(Next).opcode) then
  543. begin
  544. if (taicpu(Next).opcode = A_JMP) and
  545. { Remove dead code now to save time }
  546. RemoveDeadCodeAfterJump(taicpu(Next)) then
  547. { A jump was removed, but not the current instruction, and
  548. Result doesn't necessarily translate into an optimisation
  549. routine's Result, so use the "Force New Iteration" flag so
  550. mark a new pass }
  551. Include(OptsToCheck, aoc_ForceNewIteration);
  552. if not Assigned(JumpTracking) then
  553. begin
  554. { Cross-label optimisations often causes other optimisations
  555. to perform worse because they're not given the chance to
  556. optimise locally. In this case, don't do the cross-label
  557. optimisations yet, but flag them as a potential possibility
  558. for the next iteration of Pass 1 }
  559. if not NotFirstIteration then
  560. Include(OptsToCheck, aoc_ForceNewIteration);
  561. end
  562. else if IsJumpToLabel(taicpu(Next)) and
  563. GetNextInstruction(Next, Next_Label) then
  564. begin
  565. { If we have JMP .lbl, and the label after it has all of its
  566. references tracked, then this is probably an if-else style of
  567. block and we can keep tracking. If the label for this jump
  568. then appears later and is fully tracked, then it's the end
  569. of the if-else blocks and the code paths converge (thus
  570. marking the end of the cross-jump) }
  571. if (Next_Label.typ = ait_label) then
  572. begin
  573. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  574. begin
  575. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  576. Next := Next_Label;
  577. { CrossJump gets set to false by LabelAccountedFor if the
  578. list is completely emptied (as it indicates that all
  579. code paths have converged). We could avoid this nuance
  580. by moving the TrackJump call to before the
  581. LabelAccountedFor call, but this is slower in situations
  582. where LabelAccountedFor would return False due to the
  583. creation of a new object that is not used and destroyed
  584. soon after. }
  585. CrossJump := True;
  586. Continue;
  587. end;
  588. end
  589. else if (Next_Label.typ <> ait_marker) then
  590. { We just did a RemoveDeadCodeAfterJump, so either we find
  591. a label, the end of the procedure or some kind of marker}
  592. InternalError(2022041720);
  593. end;
  594. Result := False;
  595. Exit;
  596. end
  597. else
  598. begin
  599. if not Assigned(JumpTracking) then
  600. begin
  601. { Cross-label optimisations often causes other optimisations
  602. to perform worse because they're not given the chance to
  603. optimise locally. In this case, don't do the cross-label
  604. optimisations yet, but flag them as a potential possibility
  605. for the next iteration of Pass 1 }
  606. if not NotFirstIteration then
  607. Include(OptsToCheck, aoc_ForceNewIteration);
  608. end
  609. else if IsJumpToLabel(taicpu(Next)) then
  610. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  611. else
  612. { Conditional jumps should always be a jump to label }
  613. InternalError(2022041701);
  614. CrossJump := True;
  615. Continue;
  616. end;
  617. if Next.typ = ait_label then
  618. begin
  619. if not Assigned(JumpTracking) then
  620. begin
  621. { Cross-label optimisations often causes other optimisations
  622. to perform worse because they're not given the chance to
  623. optimise locally. In this case, don't do the cross-label
  624. optimisations yet, but flag them as a potential possibility
  625. for the next iteration of Pass 1 }
  626. if not NotFirstIteration then
  627. Include(OptsToCheck, aoc_ForceNewIteration);
  628. end
  629. else if LabelAccountedFor(tai_label(Next).labsym) then
  630. Continue;
  631. { If we reach here, we're at a label that hasn't been seen before
  632. (or JumpTracking was nil) }
  633. Break;
  634. end;
  635. until not Result or
  636. not (cs_opt_level3 in current_settings.optimizerswitches) or
  637. not (Next.typ in [ait_label, ait_instruction]) or
  638. RegInInstruction(reg,Next);
  639. end;
  640. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  641. begin
  642. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  643. begin
  644. Result:=GetNextInstruction(Current,Next);
  645. exit;
  646. end;
  647. Next:=tai(Current.Next);
  648. Result:=false;
  649. while assigned(Next) do
  650. begin
  651. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  652. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  653. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  654. exit
  655. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  656. begin
  657. Result:=true;
  658. exit;
  659. end;
  660. Next:=tai(Next.Next);
  661. end;
  662. end;
  663. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  664. begin
  665. Result:=RegReadByInstruction(reg,hp);
  666. end;
  667. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  668. var
  669. p: taicpu;
  670. opcount: longint;
  671. begin
  672. RegReadByInstruction := false;
  673. if hp.typ <> ait_instruction then
  674. exit;
  675. p := taicpu(hp);
  676. case p.opcode of
  677. A_CALL:
  678. regreadbyinstruction := true;
  679. A_IMUL:
  680. case p.ops of
  681. 1:
  682. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  683. (
  684. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  685. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  686. );
  687. 2,3:
  688. regReadByInstruction :=
  689. reginop(reg,p.oper[0]^) or
  690. reginop(reg,p.oper[1]^);
  691. else
  692. InternalError(2019112801);
  693. end;
  694. A_MUL:
  695. begin
  696. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  697. (
  698. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  699. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  700. );
  701. end;
  702. A_IDIV,A_DIV:
  703. begin
  704. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  705. (
  706. (getregtype(reg)=R_INTREGISTER) and
  707. (
  708. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  709. )
  710. );
  711. end;
  712. else
  713. begin
  714. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  715. begin
  716. RegReadByInstruction := false;
  717. exit;
  718. end;
  719. for opcount := 0 to p.ops-1 do
  720. if (p.oper[opCount]^.typ = top_ref) and
  721. RegInRef(reg,p.oper[opcount]^.ref^) then
  722. begin
  723. RegReadByInstruction := true;
  724. exit
  725. end;
  726. { special handling for SSE MOVSD }
  727. if (p.opcode=A_MOVSD) and (p.ops>0) then
  728. begin
  729. if p.ops<>2 then
  730. internalerror(2017042702);
  731. regReadByInstruction := reginop(reg,p.oper[0]^) or
  732. (
  733. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  734. );
  735. exit;
  736. end;
  737. with insprop[p.opcode] do
  738. begin
  739. case getregtype(reg) of
  740. R_INTREGISTER:
  741. begin
  742. case getsupreg(reg) of
  743. RS_EAX:
  744. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  745. begin
  746. RegReadByInstruction := true;
  747. exit
  748. end;
  749. RS_ECX:
  750. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  751. begin
  752. RegReadByInstruction := true;
  753. exit
  754. end;
  755. RS_EDX:
  756. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  757. begin
  758. RegReadByInstruction := true;
  759. exit
  760. end;
  761. RS_EBX:
  762. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ESP:
  768. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EBP:
  774. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_ESI:
  780. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_EDI:
  786. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. end;
  792. end;
  793. R_MMREGISTER:
  794. begin
  795. case getsupreg(reg) of
  796. RS_XMM0:
  797. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  798. begin
  799. RegReadByInstruction := true;
  800. exit
  801. end;
  802. end;
  803. end;
  804. else
  805. ;
  806. end;
  807. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  808. begin
  809. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  810. begin
  811. case p.condition of
  812. C_A,C_NBE, { CF=0 and ZF=0 }
  813. C_BE,C_NA: { CF=1 or ZF=1 }
  814. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  815. C_AE,C_NB,C_NC, { CF=0 }
  816. C_B,C_NAE,C_C: { CF=1 }
  817. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  818. C_NE,C_NZ, { ZF=0 }
  819. C_E,C_Z: { ZF=1 }
  820. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  821. C_G,C_NLE, { ZF=0 and SF=OF }
  822. C_LE,C_NG: { ZF=1 or SF<>OF }
  823. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  824. C_GE,C_NL, { SF=OF }
  825. C_L,C_NGE: { SF<>OF }
  826. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  827. C_NO, { OF=0 }
  828. C_O: { OF=1 }
  829. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  830. C_NP,C_PO, { PF=0 }
  831. C_P,C_PE: { PF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  833. C_NS, { SF=0 }
  834. C_S: { SF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  836. else
  837. internalerror(2017042701);
  838. end;
  839. if RegReadByInstruction then
  840. exit;
  841. end;
  842. case getsubreg(reg) of
  843. R_SUBW,R_SUBD,R_SUBQ:
  844. RegReadByInstruction :=
  845. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  846. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  847. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  848. R_SUBFLAGCARRY:
  849. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  850. R_SUBFLAGPARITY:
  851. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  852. R_SUBFLAGAUXILIARY:
  853. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  854. R_SUBFLAGZERO:
  855. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  856. R_SUBFLAGSIGN:
  857. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  858. R_SUBFLAGOVERFLOW:
  859. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  860. R_SUBFLAGINTERRUPT:
  861. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  862. R_SUBFLAGDIRECTION:
  863. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  864. else
  865. internalerror(2017042601);
  866. end;
  867. exit;
  868. end;
  869. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  870. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  871. (p.oper[0]^.reg=p.oper[1]^.reg) then
  872. exit;
  873. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  874. begin
  875. RegReadByInstruction := true;
  876. exit
  877. end;
  878. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  879. begin
  880. RegReadByInstruction := true;
  881. exit
  882. end;
  883. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  884. begin
  885. RegReadByInstruction := true;
  886. exit
  887. end;
  888. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  889. begin
  890. RegReadByInstruction := true;
  891. exit
  892. end;
  893. end;
  894. end;
  895. end;
  896. end;
  897. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  898. begin
  899. result:=false;
  900. if p1.typ<>ait_instruction then
  901. exit;
  902. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  903. exit(true);
  904. if (getregtype(reg)=R_INTREGISTER) and
  905. { change information for xmm movsd are not correct }
  906. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  907. begin
  908. { Handle instructions that behave differently depending on the size and operand count }
  909. case taicpu(p1).opcode of
  910. A_MUL, A_DIV, A_IDIV:
  911. if taicpu(p1).opsize = S_B then
  912. Result := (getsupreg(Reg) = RS_EAX)
  913. else
  914. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  915. A_IMUL:
  916. if taicpu(p1).ops = 1 then
  917. begin
  918. if taicpu(p1).opsize = S_B then
  919. Result := (getsupreg(Reg) = RS_EAX)
  920. else
  921. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  922. end;
  923. { If ops are greater than 1, call inherited method }
  924. else
  925. case getsupreg(reg) of
  926. { RS_EAX = RS_RAX on x86-64 }
  927. RS_EAX:
  928. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  929. RS_ECX:
  930. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  931. RS_EDX:
  932. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  933. RS_EBX:
  934. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  935. RS_ESP:
  936. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  937. RS_EBP:
  938. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  939. RS_ESI:
  940. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  941. RS_EDI:
  942. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  943. else
  944. ;
  945. end;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if getregtype(reg)=R_MMREGISTER then
  951. begin
  952. case getsupreg(reg) of
  953. RS_XMM0:
  954. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. else
  956. ;
  957. end;
  958. if result then
  959. exit;
  960. end
  961. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  962. begin
  963. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  964. exit(true);
  965. case getsubreg(reg) of
  966. R_SUBFLAGCARRY:
  967. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  968. R_SUBFLAGPARITY:
  969. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  970. R_SUBFLAGAUXILIARY:
  971. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  972. R_SUBFLAGZERO:
  973. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  974. R_SUBFLAGSIGN:
  975. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  976. R_SUBFLAGOVERFLOW:
  977. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  978. R_SUBFLAGINTERRUPT:
  979. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  980. R_SUBFLAGDIRECTION:
  981. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  982. R_SUBW,R_SUBD,R_SUBQ:
  983. { Everything except the direction bits }
  984. Result:=
  985. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  986. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  987. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  988. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  989. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  990. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  991. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. else
  993. ;
  994. end;
  995. if result then
  996. exit;
  997. end
  998. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  999. exit(true);
  1000. Result:=inherited RegInInstruction(Reg, p1);
  1001. end;
  1002. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1003. const
  1004. WriteOps: array[0..3] of set of TInsChange =
  1005. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1006. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1007. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1008. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1009. var
  1010. OperIdx: Integer;
  1011. begin
  1012. Result := False;
  1013. if p1.typ <> ait_instruction then
  1014. exit;
  1015. with insprop[taicpu(p1).opcode] do
  1016. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1017. begin
  1018. case getsubreg(reg) of
  1019. R_SUBW,R_SUBD,R_SUBQ:
  1020. Result :=
  1021. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1022. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1023. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1024. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1025. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1026. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1027. R_SUBFLAGCARRY:
  1028. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1029. R_SUBFLAGPARITY:
  1030. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1031. R_SUBFLAGAUXILIARY:
  1032. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1033. R_SUBFLAGZERO:
  1034. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1035. R_SUBFLAGSIGN:
  1036. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1037. R_SUBFLAGOVERFLOW:
  1038. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1039. R_SUBFLAGINTERRUPT:
  1040. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1041. R_SUBFLAGDIRECTION:
  1042. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1043. else
  1044. internalerror(2017042602);
  1045. end;
  1046. exit;
  1047. end;
  1048. case taicpu(p1).opcode of
  1049. A_CALL:
  1050. { We could potentially set Result to False if the register in
  1051. question is non-volatile for the subroutine's calling convention,
  1052. but this would require detecting the calling convention in use and
  1053. also assuming that the routine doesn't contain malformed assembly
  1054. language, for example... so it could only be done under -O4 as it
  1055. would be considered a side-effect. [Kit] }
  1056. Result := True;
  1057. A_MOVSD:
  1058. { special handling for SSE MOVSD }
  1059. if (taicpu(p1).ops>0) then
  1060. begin
  1061. if taicpu(p1).ops<>2 then
  1062. internalerror(2017042703);
  1063. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1064. end;
  1065. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1066. so fix it here (FK)
  1067. }
  1068. A_VMOVSS,
  1069. A_VMOVSD:
  1070. begin
  1071. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1072. exit;
  1073. end;
  1074. A_MUL, A_DIV, A_IDIV:
  1075. begin
  1076. if taicpu(p1).opsize = S_B then
  1077. Result := (getsupreg(Reg) = RS_EAX)
  1078. else
  1079. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1080. end;
  1081. A_IMUL:
  1082. begin
  1083. if taicpu(p1).ops = 1 then
  1084. begin
  1085. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1086. end
  1087. else
  1088. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1089. Exit;
  1090. end;
  1091. else
  1092. ;
  1093. end;
  1094. if Result then
  1095. exit;
  1096. with insprop[taicpu(p1).opcode] do
  1097. begin
  1098. if getregtype(reg)=R_INTREGISTER then
  1099. begin
  1100. case getsupreg(reg) of
  1101. RS_EAX:
  1102. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1103. begin
  1104. Result := True;
  1105. exit
  1106. end;
  1107. RS_ECX:
  1108. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1109. begin
  1110. Result := True;
  1111. exit
  1112. end;
  1113. RS_EDX:
  1114. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1115. begin
  1116. Result := True;
  1117. exit
  1118. end;
  1119. RS_EBX:
  1120. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ESP:
  1126. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EBP:
  1132. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_ESI:
  1138. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_EDI:
  1144. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. end;
  1150. end;
  1151. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1152. if (WriteOps[OperIdx]*Ch<>[]) and
  1153. { The register doesn't get modified inside a reference }
  1154. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1155. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1156. begin
  1157. Result := true;
  1158. exit
  1159. end;
  1160. end;
  1161. end;
  1162. {$ifdef DEBUG_AOPTCPU}
  1163. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1164. begin
  1165. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1166. end;
  1167. function debug_tostr(i: tcgint): string; inline;
  1168. begin
  1169. Result := tostr(i);
  1170. end;
  1171. function debug_hexstr(i: tcgint): string;
  1172. begin
  1173. Result := '0x';
  1174. case i of
  1175. 0..$FF:
  1176. Result := Result + hexstr(i, 2);
  1177. $100..$FFFF:
  1178. Result := Result + hexstr(i, 4);
  1179. $10000..$FFFFFF:
  1180. Result := Result + hexstr(i, 6);
  1181. $1000000..$FFFFFFFF:
  1182. Result := Result + hexstr(i, 8);
  1183. else
  1184. Result := Result + hexstr(i, 16);
  1185. end;
  1186. end;
  1187. function debug_regname(r: TRegister): string; inline;
  1188. begin
  1189. Result := '%' + std_regname(r);
  1190. end;
  1191. { Debug output function - creates a string representation of an operator }
  1192. function debug_operstr(oper: TOper): string;
  1193. begin
  1194. case oper.typ of
  1195. top_const:
  1196. Result := '$' + debug_tostr(oper.val);
  1197. top_reg:
  1198. Result := debug_regname(oper.reg);
  1199. top_ref:
  1200. begin
  1201. if oper.ref^.offset <> 0 then
  1202. Result := debug_tostr(oper.ref^.offset) + '('
  1203. else
  1204. Result := '(';
  1205. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1206. begin
  1207. Result := Result + debug_regname(oper.ref^.base);
  1208. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1209. Result := Result + ',' + debug_regname(oper.ref^.index);
  1210. end
  1211. else
  1212. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1213. Result := Result + debug_regname(oper.ref^.index);
  1214. if (oper.ref^.scalefactor > 1) then
  1215. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1216. else
  1217. Result := Result + ')';
  1218. end;
  1219. else
  1220. Result := '[UNKNOWN]';
  1221. end;
  1222. end;
  1223. function debug_op2str(opcode: tasmop): string; inline;
  1224. begin
  1225. Result := std_op2str[opcode];
  1226. end;
  1227. function debug_opsize2str(opsize: topsize): string; inline;
  1228. begin
  1229. Result := gas_opsize2str[opsize];
  1230. end;
  1231. {$else DEBUG_AOPTCPU}
  1232. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1233. begin
  1234. end;
  1235. function debug_tostr(i: tcgint): string; inline;
  1236. begin
  1237. Result := '';
  1238. end;
  1239. function debug_hexstr(i: tcgint): string; inline;
  1240. begin
  1241. Result := '';
  1242. end;
  1243. function debug_regname(r: TRegister): string; inline;
  1244. begin
  1245. Result := '';
  1246. end;
  1247. function debug_operstr(oper: TOper): string; inline;
  1248. begin
  1249. Result := '';
  1250. end;
  1251. function debug_op2str(opcode: tasmop): string; inline;
  1252. begin
  1253. Result := '';
  1254. end;
  1255. function debug_opsize2str(opsize: topsize): string; inline;
  1256. begin
  1257. Result := '';
  1258. end;
  1259. {$endif DEBUG_AOPTCPU}
  1260. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1261. begin
  1262. {$ifdef x86_64}
  1263. { Always fine on x86-64 }
  1264. Result := True;
  1265. {$else x86_64}
  1266. Result :=
  1267. {$ifdef i8086}
  1268. (current_settings.cputype >= cpu_386) and
  1269. {$endif i8086}
  1270. (
  1271. { Always accept if optimising for size }
  1272. (cs_opt_size in current_settings.optimizerswitches) or
  1273. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1274. (current_settings.optimizecputype >= cpu_Pentium2)
  1275. );
  1276. {$endif x86_64}
  1277. end;
  1278. { Attempts to allocate a volatile integer register for use between p and hp,
  1279. using AUsedRegs for the current register usage information. Returns NR_NO
  1280. if no free register could be found }
  1281. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1282. var
  1283. RegSet: TCPURegisterSet;
  1284. CurrentSuperReg: Integer;
  1285. CurrentReg: TRegister;
  1286. Currentp: tai;
  1287. Breakout: Boolean;
  1288. begin
  1289. Result := NR_NO;
  1290. RegSet :=
  1291. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1292. current_procinfo.saved_regs_int;
  1293. (*
  1294. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1295. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1296. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1297. *)
  1298. for CurrentSuperReg in RegSet do
  1299. begin
  1300. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1301. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1302. {$if defined(i386) or defined(i8086)}
  1303. { If the target size is 8-bit, make sure we can actually encode it }
  1304. and (
  1305. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1306. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1307. )
  1308. {$endif i386 or i8086}
  1309. then
  1310. begin
  1311. Currentp := p;
  1312. Breakout := False;
  1313. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1314. begin
  1315. case Currentp.typ of
  1316. ait_instruction:
  1317. begin
  1318. if RegInInstruction(CurrentReg, Currentp) then
  1319. begin
  1320. Breakout := True;
  1321. Break;
  1322. end;
  1323. { Cannot allocate across an unconditional jump }
  1324. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1325. Exit;
  1326. end;
  1327. ait_marker:
  1328. { Don't try anything more if a marker is hit }
  1329. Exit;
  1330. ait_regalloc:
  1331. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1332. begin
  1333. Breakout := True;
  1334. Break;
  1335. end;
  1336. else
  1337. ;
  1338. end;
  1339. end;
  1340. if Breakout then
  1341. { Try the next register }
  1342. Continue;
  1343. { We have a free register available }
  1344. Result := CurrentReg;
  1345. if not DontAlloc then
  1346. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1347. Exit;
  1348. end;
  1349. end;
  1350. end;
  1351. { Attempts to allocate a volatile MM register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_mm;
  1366. for CurrentSuperReg in RegSet do
  1367. begin
  1368. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1369. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1370. begin
  1371. Currentp := p;
  1372. Breakout := False;
  1373. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1374. begin
  1375. case Currentp.typ of
  1376. ait_instruction:
  1377. begin
  1378. if RegInInstruction(CurrentReg, Currentp) then
  1379. begin
  1380. Breakout := True;
  1381. Break;
  1382. end;
  1383. { Cannot allocate across an unconditional jump }
  1384. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1385. Exit;
  1386. end;
  1387. ait_marker:
  1388. { Don't try anything more if a marker is hit }
  1389. Exit;
  1390. ait_regalloc:
  1391. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. else
  1397. ;
  1398. end;
  1399. end;
  1400. if Breakout then
  1401. { Try the next register }
  1402. Continue;
  1403. { We have a free register available }
  1404. Result := CurrentReg;
  1405. if not DontAlloc then
  1406. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1407. Exit;
  1408. end;
  1409. end;
  1410. end;
  1411. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1412. begin
  1413. if not SuperRegistersEqual(reg1,reg2) then
  1414. exit(false);
  1415. if getregtype(reg1)<>R_INTREGISTER then
  1416. exit(true); {because SuperRegisterEqual is true}
  1417. case getsubreg(reg1) of
  1418. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1419. higher, it preserves the high bits, so the new value depends on
  1420. reg2's previous value. In other words, it is equivalent to doing:
  1421. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1422. R_SUBL:
  1423. exit(getsubreg(reg2)=R_SUBL);
  1424. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1425. higher, it actually does a:
  1426. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1427. R_SUBH:
  1428. exit(getsubreg(reg2)=R_SUBH);
  1429. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1430. bits of reg2:
  1431. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1432. R_SUBW:
  1433. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1434. { a write to R_SUBD always overwrites every other subregister,
  1435. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1436. R_SUBD,
  1437. R_SUBQ:
  1438. exit(true);
  1439. else
  1440. internalerror(2017042801);
  1441. end;
  1442. end;
  1443. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1444. begin
  1445. if not SuperRegistersEqual(reg1,reg2) then
  1446. exit(false);
  1447. if getregtype(reg1)<>R_INTREGISTER then
  1448. exit(true); {because SuperRegisterEqual is true}
  1449. case getsubreg(reg1) of
  1450. R_SUBL:
  1451. exit(getsubreg(reg2)<>R_SUBH);
  1452. R_SUBH:
  1453. exit(getsubreg(reg2)<>R_SUBL);
  1454. R_SUBW,
  1455. R_SUBD,
  1456. R_SUBQ:
  1457. exit(true);
  1458. else
  1459. internalerror(2017042802);
  1460. end;
  1461. end;
  1462. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1463. var
  1464. hp1 : tai;
  1465. l : TCGInt;
  1466. begin
  1467. result:=false;
  1468. if not(GetNextInstruction(p, hp1)) then
  1469. exit;
  1470. { changes the code sequence
  1471. shr/sar const1, x
  1472. shl const2, x
  1473. to
  1474. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1475. if (taicpu(p).oper[0]^.typ = top_const) and
  1476. MatchInstruction(hp1,A_SHL,[]) and
  1477. (taicpu(hp1).oper[0]^.typ = top_const) and
  1478. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1479. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1480. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1481. begin
  1482. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1483. not(cs_opt_size in current_settings.optimizerswitches) then
  1484. begin
  1485. { shr/sar const1, %reg
  1486. shl const2, %reg
  1487. with const1 > const2 }
  1488. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1489. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1490. taicpu(hp1).opcode := A_AND;
  1491. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1492. case taicpu(p).opsize Of
  1493. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1494. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1495. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1496. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1497. else
  1498. Internalerror(2017050703)
  1499. end;
  1500. end
  1501. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1502. not(cs_opt_size in current_settings.optimizerswitches) then
  1503. begin
  1504. { shr/sar const1, %reg
  1505. shl const2, %reg
  1506. with const1 < const2 }
  1507. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1508. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1509. taicpu(p).opcode := A_AND;
  1510. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1511. case taicpu(p).opsize Of
  1512. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1513. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1514. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1515. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1516. else
  1517. Internalerror(2017050702)
  1518. end;
  1519. end
  1520. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1521. begin
  1522. { shr/sar const1, %reg
  1523. shl const2, %reg
  1524. with const1 = const2 }
  1525. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1526. taicpu(p).opcode := A_AND;
  1527. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1528. case taicpu(p).opsize Of
  1529. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1530. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1531. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1532. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1533. else
  1534. Internalerror(2017050701)
  1535. end;
  1536. RemoveInstruction(hp1);
  1537. end;
  1538. end;
  1539. end;
  1540. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1541. var
  1542. opsize : topsize;
  1543. hp1, hp2 : tai;
  1544. tmpref : treference;
  1545. ShiftValue : Cardinal;
  1546. BaseValue : TCGInt;
  1547. begin
  1548. result:=false;
  1549. opsize:=taicpu(p).opsize;
  1550. { changes certain "imul const, %reg"'s to lea sequences }
  1551. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1552. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1553. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1554. if (taicpu(p).oper[0]^.val = 1) then
  1555. if (taicpu(p).ops = 2) then
  1556. { remove "imul $1, reg" }
  1557. begin
  1558. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1559. Result := RemoveCurrentP(p);
  1560. end
  1561. else
  1562. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1563. begin
  1564. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1565. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1566. asml.InsertAfter(hp1, p);
  1567. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1568. RemoveCurrentP(p, hp1);
  1569. Result := True;
  1570. end
  1571. else if ((taicpu(p).ops <= 2) or
  1572. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1573. not(cs_opt_size in current_settings.optimizerswitches) and
  1574. (not(GetNextInstruction(p, hp1)) or
  1575. not((tai(hp1).typ = ait_instruction) and
  1576. ((taicpu(hp1).opcode=A_Jcc) and
  1577. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1578. begin
  1579. {
  1580. imul X, reg1, reg2 to
  1581. lea (reg1,reg1,Y), reg2
  1582. shl ZZ,reg2
  1583. imul XX, reg1 to
  1584. lea (reg1,reg1,YY), reg1
  1585. shl ZZ,reg2
  1586. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1587. it does not exist as a separate optimization target in FPC though.
  1588. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1589. at most two zeros
  1590. }
  1591. reference_reset(tmpref,1,[]);
  1592. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1593. begin
  1594. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1595. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1596. TmpRef.base := taicpu(p).oper[1]^.reg;
  1597. TmpRef.index := taicpu(p).oper[1]^.reg;
  1598. if not(BaseValue in [3,5,9]) then
  1599. Internalerror(2018110101);
  1600. TmpRef.ScaleFactor := BaseValue-1;
  1601. if (taicpu(p).ops = 2) then
  1602. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1603. else
  1604. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1605. AsmL.InsertAfter(hp1,p);
  1606. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1607. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1608. RemoveCurrentP(p, hp1);
  1609. if ShiftValue>0 then
  1610. begin
  1611. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1612. AsmL.InsertAfter(hp2,hp1);
  1613. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1614. end;
  1615. Result := True;
  1616. end;
  1617. end;
  1618. end;
  1619. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1620. begin
  1621. Result := False;
  1622. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1623. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1624. begin
  1625. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1626. taicpu(p).opcode := A_MOV;
  1627. Result := True;
  1628. end;
  1629. end;
  1630. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1631. var
  1632. p: taicpu absolute hp; { Implicit typecast }
  1633. i: Integer;
  1634. begin
  1635. Result := False;
  1636. if not assigned(hp) or
  1637. (hp.typ <> ait_instruction) then
  1638. Exit;
  1639. Prefetch(insprop[p.opcode]);
  1640. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1641. with insprop[p.opcode] do
  1642. begin
  1643. case getsubreg(reg) of
  1644. R_SUBW,R_SUBD,R_SUBQ:
  1645. Result:=
  1646. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1647. uncommon flags are checked first }
  1648. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1649. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1650. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1651. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1652. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1653. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1654. R_SUBFLAGCARRY:
  1655. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1656. R_SUBFLAGPARITY:
  1657. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1658. R_SUBFLAGAUXILIARY:
  1659. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1660. R_SUBFLAGZERO:
  1661. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1662. R_SUBFLAGSIGN:
  1663. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1664. R_SUBFLAGOVERFLOW:
  1665. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1666. R_SUBFLAGINTERRUPT:
  1667. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1668. R_SUBFLAGDIRECTION:
  1669. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1670. else
  1671. internalerror(2017050501);
  1672. end;
  1673. exit;
  1674. end;
  1675. { Handle special cases first }
  1676. case p.opcode of
  1677. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1678. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1679. begin
  1680. Result :=
  1681. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1682. (p.oper[1]^.typ = top_reg) and
  1683. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1684. (
  1685. (p.oper[0]^.typ = top_const) or
  1686. (
  1687. (p.oper[0]^.typ = top_reg) and
  1688. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1689. ) or (
  1690. (p.oper[0]^.typ = top_ref) and
  1691. not RegInRef(reg,p.oper[0]^.ref^)
  1692. )
  1693. );
  1694. end;
  1695. A_MUL, A_IMUL:
  1696. Result :=
  1697. (
  1698. (p.ops=3) and { IMUL only }
  1699. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1700. (
  1701. (
  1702. (p.oper[1]^.typ=top_reg) and
  1703. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1704. ) or (
  1705. (p.oper[1]^.typ=top_ref) and
  1706. not RegInRef(reg,p.oper[1]^.ref^)
  1707. )
  1708. )
  1709. ) or (
  1710. (
  1711. (p.ops=1) and
  1712. (
  1713. (
  1714. (
  1715. (p.oper[0]^.typ=top_reg) and
  1716. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1717. )
  1718. ) or (
  1719. (p.oper[0]^.typ=top_ref) and
  1720. not RegInRef(reg,p.oper[0]^.ref^)
  1721. )
  1722. ) and (
  1723. (
  1724. (p.opsize=S_B) and
  1725. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1726. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1727. ) or (
  1728. (p.opsize=S_W) and
  1729. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1730. ) or (
  1731. (p.opsize=S_L) and
  1732. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1733. {$ifdef x86_64}
  1734. ) or (
  1735. (p.opsize=S_Q) and
  1736. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1737. {$endif x86_64}
  1738. )
  1739. )
  1740. )
  1741. );
  1742. A_CBW:
  1743. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1744. {$ifndef x86_64}
  1745. A_LDS:
  1746. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1747. A_LES:
  1748. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1749. {$endif not x86_64}
  1750. A_LFS:
  1751. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1752. A_LGS:
  1753. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1754. A_LSS:
  1755. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1756. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1757. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1758. A_LODSB:
  1759. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1760. A_LODSW:
  1761. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1762. {$ifdef x86_64}
  1763. A_LODSQ:
  1764. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1765. {$endif x86_64}
  1766. A_LODSD:
  1767. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1768. A_FSTSW, A_FNSTSW:
  1769. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1770. else
  1771. begin
  1772. with insprop[p.opcode] do
  1773. begin
  1774. if (
  1775. { xor %reg,%reg etc. is classed as a new value }
  1776. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1777. MatchOpType(p, top_reg, top_reg) and
  1778. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1779. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1780. ) then
  1781. begin
  1782. Result := True;
  1783. Exit;
  1784. end;
  1785. { Make sure the entire register is overwritten }
  1786. if (getregtype(reg) = R_INTREGISTER) then
  1787. begin
  1788. if (p.ops > 0) then
  1789. begin
  1790. if RegInOp(reg, p.oper[0]^) then
  1791. begin
  1792. if (p.oper[0]^.typ = top_ref) then
  1793. begin
  1794. if RegInRef(reg, p.oper[0]^.ref^) then
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end
  1800. else if (p.oper[0]^.typ = top_reg) then
  1801. begin
  1802. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1803. begin
  1804. Result := False;
  1805. Exit;
  1806. end
  1807. else if ([Ch_WOp1]*Ch<>[]) then
  1808. begin
  1809. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1810. Result := True
  1811. else
  1812. begin
  1813. Result := False;
  1814. Exit;
  1815. end;
  1816. end;
  1817. end;
  1818. end;
  1819. if (p.ops > 1) then
  1820. begin
  1821. if RegInOp(reg, p.oper[1]^) then
  1822. begin
  1823. if (p.oper[1]^.typ = top_ref) then
  1824. begin
  1825. if RegInRef(reg, p.oper[1]^.ref^) then
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end
  1831. else if (p.oper[1]^.typ = top_reg) then
  1832. begin
  1833. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1834. begin
  1835. Result := False;
  1836. Exit;
  1837. end
  1838. else if ([Ch_WOp2]*Ch<>[]) then
  1839. begin
  1840. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1841. Result := True
  1842. else
  1843. begin
  1844. Result := False;
  1845. Exit;
  1846. end;
  1847. end;
  1848. end;
  1849. end;
  1850. if (p.ops > 2) then
  1851. begin
  1852. if RegInOp(reg, p.oper[2]^) then
  1853. begin
  1854. if (p.oper[2]^.typ = top_ref) then
  1855. begin
  1856. if RegInRef(reg, p.oper[2]^.ref^) then
  1857. begin
  1858. Result := False;
  1859. Exit;
  1860. end;
  1861. end
  1862. else if (p.oper[2]^.typ = top_reg) then
  1863. begin
  1864. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1865. begin
  1866. Result := False;
  1867. Exit;
  1868. end
  1869. else if ([Ch_WOp3]*Ch<>[]) then
  1870. begin
  1871. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1872. Result := True
  1873. else
  1874. begin
  1875. Result := False;
  1876. Exit;
  1877. end;
  1878. end;
  1879. end;
  1880. end;
  1881. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1882. begin
  1883. if (p.oper[3]^.typ = top_ref) then
  1884. begin
  1885. if RegInRef(reg, p.oper[3]^.ref^) then
  1886. begin
  1887. Result := False;
  1888. Exit;
  1889. end;
  1890. end
  1891. else if (p.oper[3]^.typ = top_reg) then
  1892. begin
  1893. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1894. begin
  1895. Result := False;
  1896. Exit;
  1897. end
  1898. else if ([Ch_WOp4]*Ch<>[]) then
  1899. begin
  1900. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1901. Result := True
  1902. else
  1903. begin
  1904. Result := False;
  1905. Exit;
  1906. end;
  1907. end;
  1908. end;
  1909. end;
  1910. end;
  1911. end;
  1912. end;
  1913. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1914. case getsupreg(reg) of
  1915. RS_EAX:
  1916. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1917. begin
  1918. Result := True;
  1919. Exit;
  1920. end;
  1921. RS_ECX:
  1922. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1923. begin
  1924. Result := True;
  1925. Exit;
  1926. end;
  1927. RS_EDX:
  1928. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1929. begin
  1930. Result := True;
  1931. Exit;
  1932. end;
  1933. RS_EBX:
  1934. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1935. begin
  1936. Result := True;
  1937. Exit;
  1938. end;
  1939. RS_ESP:
  1940. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1941. begin
  1942. Result := True;
  1943. Exit;
  1944. end;
  1945. RS_EBP:
  1946. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1947. begin
  1948. Result := True;
  1949. Exit;
  1950. end;
  1951. RS_ESI:
  1952. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1953. begin
  1954. Result := True;
  1955. Exit;
  1956. end;
  1957. RS_EDI:
  1958. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1959. begin
  1960. Result := True;
  1961. Exit;
  1962. end;
  1963. else
  1964. ;
  1965. end;
  1966. end;
  1967. end;
  1968. end;
  1969. end;
  1970. end;
  1971. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1972. var
  1973. hp2,hp3 : tai;
  1974. begin
  1975. { some x86-64 issue a NOP before the real exit code }
  1976. if MatchInstruction(p,A_NOP,[]) then
  1977. GetNextInstruction(p,p);
  1978. result:=assigned(p) and (p.typ=ait_instruction) and
  1979. ((taicpu(p).opcode = A_RET) or
  1980. ((taicpu(p).opcode=A_LEAVE) and
  1981. GetNextInstruction(p,hp2) and
  1982. MatchInstruction(hp2,A_RET,[S_NO])
  1983. ) or
  1984. (((taicpu(p).opcode=A_LEA) and
  1985. MatchOpType(taicpu(p),top_ref,top_reg) and
  1986. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1987. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1988. ) and
  1989. GetNextInstruction(p,hp2) and
  1990. MatchInstruction(hp2,A_RET,[S_NO])
  1991. ) or
  1992. ((((taicpu(p).opcode=A_MOV) and
  1993. MatchOpType(taicpu(p),top_reg,top_reg) and
  1994. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1995. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1996. ((taicpu(p).opcode=A_LEA) and
  1997. MatchOpType(taicpu(p),top_ref,top_reg) and
  1998. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1999. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2000. )
  2001. ) and
  2002. GetNextInstruction(p,hp2) and
  2003. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2004. MatchOpType(taicpu(hp2),top_reg) and
  2005. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2006. GetNextInstruction(hp2,hp3) and
  2007. MatchInstruction(hp3,A_RET,[S_NO])
  2008. )
  2009. );
  2010. end;
  2011. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2012. begin
  2013. isFoldableArithOp := False;
  2014. case hp1.opcode of
  2015. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2016. isFoldableArithOp :=
  2017. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2018. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2019. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2020. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2021. (taicpu(hp1).oper[1]^.reg = reg);
  2022. A_INC,A_DEC,A_NEG,A_NOT:
  2023. isFoldableArithOp :=
  2024. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2025. (taicpu(hp1).oper[0]^.reg = reg);
  2026. else
  2027. ;
  2028. end;
  2029. end;
  2030. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2031. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2032. var
  2033. hp2: tai;
  2034. begin
  2035. hp2 := p;
  2036. repeat
  2037. hp2 := tai(hp2.previous);
  2038. if assigned(hp2) and
  2039. (hp2.typ = ait_regalloc) and
  2040. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2041. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2042. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2043. begin
  2044. RemoveInstruction(hp2);
  2045. break;
  2046. end;
  2047. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2048. end;
  2049. begin
  2050. case current_procinfo.procdef.returndef.typ of
  2051. arraydef,recorddef,pointerdef,
  2052. stringdef,enumdef,procdef,objectdef,errordef,
  2053. filedef,setdef,procvardef,
  2054. classrefdef,forwarddef:
  2055. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2056. orddef:
  2057. if current_procinfo.procdef.returndef.size <> 0 then
  2058. begin
  2059. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2060. { for int64/qword }
  2061. if current_procinfo.procdef.returndef.size = 8 then
  2062. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2063. end;
  2064. else
  2065. ;
  2066. end;
  2067. end;
  2068. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2069. var
  2070. hp1: tai;
  2071. operswap: poper;
  2072. begin
  2073. Result := False;
  2074. { Optimise:
  2075. cmov(c) %reg1,%reg2
  2076. mov %reg2,%reg1
  2077. (%reg2 dealloc.)
  2078. To:
  2079. cmov(~c) %reg2,%reg1
  2080. }
  2081. if (taicpu(p).oper[0]^.typ = top_reg) then
  2082. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2083. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2084. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2085. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2086. begin
  2087. TransferUsedRegs(TmpUsedRegs);
  2088. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2089. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2090. begin
  2091. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2092. { Save time by swapping the pointers (they're both registers, so
  2093. we don't need to worry about reference counts) }
  2094. operswap := taicpu(p).oper[0];
  2095. taicpu(p).oper[0] := taicpu(p).oper[1];
  2096. taicpu(p).oper[1] := operswap;
  2097. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2098. RemoveInstruction(hp1);
  2099. { It's still a CMOV, so we can look further ahead }
  2100. Include(OptsToCheck, aoc_ForceNewIteration);
  2101. { But first, let's see if this will get optimised again
  2102. (probably won't happen, but best to be sure) }
  2103. Continue;
  2104. end;
  2105. Break;
  2106. end;
  2107. end;
  2108. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2109. var
  2110. hp1,hp2 : tai;
  2111. begin
  2112. result:=false;
  2113. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2114. begin
  2115. { vmova* reg1,reg1
  2116. =>
  2117. <nop> }
  2118. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2119. begin
  2120. RemoveCurrentP(p);
  2121. result:=true;
  2122. exit;
  2123. end;
  2124. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2125. (hp1.typ = ait_instruction) and
  2126. (
  2127. { Under -O2 and below, the instructions are always adjacent }
  2128. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2129. (taicpu(hp1).ops <= 1) or
  2130. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2131. { If reg1 = reg3, reg1 must not be modified in between }
  2132. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2133. ) then
  2134. begin
  2135. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2136. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2137. begin
  2138. { vmova* reg1,reg2
  2139. ...
  2140. vmova* reg2,reg3
  2141. dealloc reg2
  2142. =>
  2143. vmova* reg1,reg3 }
  2144. TransferUsedRegs(TmpUsedRegs);
  2145. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2146. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2147. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2148. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2149. begin
  2150. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2151. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2152. TransferUsedRegs(TmpUsedRegs);
  2153. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2154. RemoveInstruction(hp1);
  2155. result:=true;
  2156. exit;
  2157. end;
  2158. { special case:
  2159. vmova* reg1,<op>
  2160. ...
  2161. vmova* <op>,reg1
  2162. =>
  2163. vmova* reg1,<op> }
  2164. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2165. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2166. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2167. ) then
  2168. begin
  2169. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2170. RemoveInstruction(hp1);
  2171. result:=true;
  2172. exit;
  2173. end
  2174. end
  2175. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2176. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2177. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2178. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2179. ) and
  2180. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2181. begin
  2182. { vmova* reg1,reg2
  2183. ...
  2184. vmovs* reg2,<op>
  2185. dealloc reg2
  2186. =>
  2187. vmovs* reg1,<op> }
  2188. TransferUsedRegs(TmpUsedRegs);
  2189. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2190. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2191. begin
  2192. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2193. taicpu(p).opcode:=taicpu(hp1).opcode;
  2194. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2195. TransferUsedRegs(TmpUsedRegs);
  2196. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2197. RemoveInstruction(hp1);
  2198. result:=true;
  2199. exit;
  2200. end
  2201. end;
  2202. if MatchInstruction(hp1,[A_VFMADDPD,
  2203. A_VFMADD132PD,
  2204. A_VFMADD132PS,
  2205. A_VFMADD132SD,
  2206. A_VFMADD132SS,
  2207. A_VFMADD213PD,
  2208. A_VFMADD213PS,
  2209. A_VFMADD213SD,
  2210. A_VFMADD213SS,
  2211. A_VFMADD231PD,
  2212. A_VFMADD231PS,
  2213. A_VFMADD231SD,
  2214. A_VFMADD231SS,
  2215. A_VFMADDSUB132PD,
  2216. A_VFMADDSUB132PS,
  2217. A_VFMADDSUB213PD,
  2218. A_VFMADDSUB213PS,
  2219. A_VFMADDSUB231PD,
  2220. A_VFMADDSUB231PS,
  2221. A_VFMSUB132PD,
  2222. A_VFMSUB132PS,
  2223. A_VFMSUB132SD,
  2224. A_VFMSUB132SS,
  2225. A_VFMSUB213PD,
  2226. A_VFMSUB213PS,
  2227. A_VFMSUB213SD,
  2228. A_VFMSUB213SS,
  2229. A_VFMSUB231PD,
  2230. A_VFMSUB231PS,
  2231. A_VFMSUB231SD,
  2232. A_VFMSUB231SS,
  2233. A_VFMSUBADD132PD,
  2234. A_VFMSUBADD132PS,
  2235. A_VFMSUBADD213PD,
  2236. A_VFMSUBADD213PS,
  2237. A_VFMSUBADD231PD,
  2238. A_VFMSUBADD231PS,
  2239. A_VFNMADD132PD,
  2240. A_VFNMADD132PS,
  2241. A_VFNMADD132SD,
  2242. A_VFNMADD132SS,
  2243. A_VFNMADD213PD,
  2244. A_VFNMADD213PS,
  2245. A_VFNMADD213SD,
  2246. A_VFNMADD213SS,
  2247. A_VFNMADD231PD,
  2248. A_VFNMADD231PS,
  2249. A_VFNMADD231SD,
  2250. A_VFNMADD231SS,
  2251. A_VFNMSUB132PD,
  2252. A_VFNMSUB132PS,
  2253. A_VFNMSUB132SD,
  2254. A_VFNMSUB132SS,
  2255. A_VFNMSUB213PD,
  2256. A_VFNMSUB213PS,
  2257. A_VFNMSUB213SD,
  2258. A_VFNMSUB213SS,
  2259. A_VFNMSUB231PD,
  2260. A_VFNMSUB231PS,
  2261. A_VFNMSUB231SD,
  2262. A_VFNMSUB231SS],[S_NO]) and
  2263. { we mix single and double opperations here because we assume that the compiler
  2264. generates vmovapd only after double operations and vmovaps only after single operations }
  2265. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2266. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2267. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2268. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2269. begin
  2270. TransferUsedRegs(TmpUsedRegs);
  2271. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2272. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2273. begin
  2274. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2275. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2276. RemoveCurrentP(p)
  2277. else
  2278. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2279. RemoveInstruction(hp2);
  2280. end;
  2281. end
  2282. else if (hp1.typ = ait_instruction) and
  2283. (((taicpu(p).opcode=A_MOVAPS) and
  2284. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2285. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2286. ((taicpu(p).opcode=A_MOVAPD) and
  2287. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2288. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2289. ) and
  2290. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2291. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2292. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2293. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2294. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2295. { change
  2296. movapX reg,reg2
  2297. addsX/subsX/... reg3, reg2
  2298. movapX reg2,reg
  2299. to
  2300. addsX/subsX/... reg3,reg
  2301. }
  2302. begin
  2303. TransferUsedRegs(TmpUsedRegs);
  2304. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2305. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2306. begin
  2307. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2308. debug_op2str(taicpu(p).opcode)+' '+
  2309. debug_op2str(taicpu(hp1).opcode)+' '+
  2310. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2311. { we cannot eliminate the first move if
  2312. the operations uses the same register for source and dest }
  2313. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2314. { Remember that hp1 is not necessarily the immediate
  2315. next instruction }
  2316. RemoveCurrentP(p);
  2317. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2318. RemoveInstruction(hp2);
  2319. result:=true;
  2320. end;
  2321. end
  2322. else if (hp1.typ = ait_instruction) and
  2323. (((taicpu(p).opcode=A_VMOVAPD) and
  2324. (taicpu(hp1).opcode=A_VCOMISD)) or
  2325. ((taicpu(p).opcode=A_VMOVAPS) and
  2326. ((taicpu(hp1).opcode=A_VCOMISS))
  2327. )
  2328. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2329. { change
  2330. movapX reg,reg1
  2331. vcomisX reg1,reg1
  2332. to
  2333. vcomisX reg,reg
  2334. }
  2335. begin
  2336. TransferUsedRegs(TmpUsedRegs);
  2337. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2338. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2339. begin
  2340. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2341. debug_op2str(taicpu(p).opcode)+' '+
  2342. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2343. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2344. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2345. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2346. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2347. RemoveCurrentP(p);
  2348. result:=true;
  2349. exit;
  2350. end;
  2351. end
  2352. end;
  2353. end;
  2354. end;
  2355. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2356. var
  2357. hp1 : tai;
  2358. begin
  2359. result:=false;
  2360. { replace
  2361. V<Op>X %mreg1,%mreg2,%mreg3
  2362. VMovX %mreg3,%mreg4
  2363. dealloc %mreg3
  2364. by
  2365. V<Op>X %mreg1,%mreg2,%mreg4
  2366. ?
  2367. }
  2368. if GetNextInstruction(p,hp1) and
  2369. { we mix single and double operations here because we assume that the compiler
  2370. generates vmovapd only after double operations and vmovaps only after single operations }
  2371. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2372. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2373. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2374. begin
  2375. TransferUsedRegs(TmpUsedRegs);
  2376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2377. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2378. begin
  2379. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2380. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2381. RemoveInstruction(hp1);
  2382. result:=true;
  2383. end;
  2384. end;
  2385. end;
  2386. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2387. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2388. begin
  2389. Result := False;
  2390. { For safety reasons, only check for exact register matches }
  2391. { Check base register }
  2392. if (ref.base = AOldReg) then
  2393. begin
  2394. ref.base := ANewReg;
  2395. Result := True;
  2396. end;
  2397. { Check index register }
  2398. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2399. begin
  2400. ref.index := ANewReg;
  2401. Result := True;
  2402. end;
  2403. end;
  2404. { Replaces all references to AOldReg in an operand to ANewReg }
  2405. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2406. var
  2407. OldSupReg, NewSupReg: TSuperRegister;
  2408. OldSubReg, NewSubReg: TSubRegister;
  2409. OldRegType: TRegisterType;
  2410. ThisOper: POper;
  2411. begin
  2412. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2413. Result := False;
  2414. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2415. InternalError(2020011801);
  2416. OldSupReg := getsupreg(AOldReg);
  2417. OldSubReg := getsubreg(AOldReg);
  2418. OldRegType := getregtype(AOldReg);
  2419. NewSupReg := getsupreg(ANewReg);
  2420. NewSubReg := getsubreg(ANewReg);
  2421. if OldRegType <> getregtype(ANewReg) then
  2422. InternalError(2020011802);
  2423. if OldSubReg <> NewSubReg then
  2424. InternalError(2020011803);
  2425. case ThisOper^.typ of
  2426. top_reg:
  2427. if (
  2428. (ThisOper^.reg = AOldReg) or
  2429. (
  2430. (OldRegType = R_INTREGISTER) and
  2431. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2432. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2433. (
  2434. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2435. {$ifndef x86_64}
  2436. and (
  2437. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2438. don't have an 8-bit representation }
  2439. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2440. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2441. )
  2442. {$endif x86_64}
  2443. )
  2444. )
  2445. ) then
  2446. begin
  2447. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2448. Result := True;
  2449. end;
  2450. top_ref:
  2451. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2452. Result := True;
  2453. else
  2454. ;
  2455. end;
  2456. end;
  2457. { Replaces all references to AOldReg in an instruction to ANewReg }
  2458. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2459. const
  2460. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2461. var
  2462. OperIdx: Integer;
  2463. begin
  2464. Result := False;
  2465. for OperIdx := 0 to p.ops - 1 do
  2466. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2467. begin
  2468. { The shift and rotate instructions can only use CL }
  2469. if not (
  2470. (OperIdx = 0) and
  2471. { This second condition just helps to avoid unnecessarily
  2472. calling MatchInstruction for 10 different opcodes }
  2473. (p.oper[0]^.reg = NR_CL) and
  2474. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2475. ) then
  2476. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2477. end
  2478. else if p.oper[OperIdx]^.typ = top_ref then
  2479. { It's okay to replace registers in references that get written to }
  2480. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2481. end;
  2482. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2483. begin
  2484. Result :=
  2485. (ref^.index = NR_NO) and
  2486. (
  2487. {$ifdef x86_64}
  2488. (
  2489. (ref^.base = NR_RIP) and
  2490. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2491. ) or
  2492. {$endif x86_64}
  2493. (ref^.refaddr = addr_full) or
  2494. (ref^.base = NR_STACK_POINTER_REG) or
  2495. (ref^.base = current_procinfo.framepointer)
  2496. );
  2497. end;
  2498. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2499. var
  2500. l: asizeint;
  2501. begin
  2502. Result := False;
  2503. { Should have been checked previously }
  2504. if p.opcode <> A_LEA then
  2505. InternalError(2020072501);
  2506. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2507. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2508. not(cs_opt_size in current_settings.optimizerswitches) then
  2509. exit;
  2510. with p.oper[0]^.ref^ do
  2511. begin
  2512. if (base <> p.oper[1]^.reg) or
  2513. (index <> NR_NO) or
  2514. assigned(symbol) then
  2515. exit;
  2516. l:=offset;
  2517. if (l=1) and UseIncDec then
  2518. begin
  2519. p.opcode:=A_INC;
  2520. p.loadreg(0,p.oper[1]^.reg);
  2521. p.ops:=1;
  2522. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2523. end
  2524. else if (l=-1) and UseIncDec then
  2525. begin
  2526. p.opcode:=A_DEC;
  2527. p.loadreg(0,p.oper[1]^.reg);
  2528. p.ops:=1;
  2529. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2530. end
  2531. else
  2532. begin
  2533. if (l<0) and (l<>-2147483648) then
  2534. begin
  2535. p.opcode:=A_SUB;
  2536. p.loadConst(0,-l);
  2537. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2538. end
  2539. else
  2540. begin
  2541. p.opcode:=A_ADD;
  2542. p.loadConst(0,l);
  2543. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2544. end;
  2545. end;
  2546. end;
  2547. Result := True;
  2548. end;
  2549. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2550. var
  2551. CurrentReg, ReplaceReg: TRegister;
  2552. begin
  2553. Result := False;
  2554. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2555. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2556. case hp.opcode of
  2557. A_FSTSW, A_FNSTSW,
  2558. A_IN, A_INS, A_OUT, A_OUTS,
  2559. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2560. { These routines have explicit operands, but they are restricted in
  2561. what they can be (e.g. IN and OUT can only read from AL, AX or
  2562. EAX. }
  2563. Exit;
  2564. A_IMUL:
  2565. begin
  2566. { The 1-operand version writes to implicit registers
  2567. The 2-operand version reads from the first operator, and reads
  2568. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2569. the 3-operand version reads from a register that it doesn't write to
  2570. }
  2571. case hp.ops of
  2572. 1:
  2573. if (
  2574. (
  2575. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2576. ) or
  2577. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2578. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2579. begin
  2580. Result := True;
  2581. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2582. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2583. end;
  2584. 2:
  2585. { Only modify the first parameter }
  2586. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2587. begin
  2588. Result := True;
  2589. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2590. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2591. end;
  2592. 3:
  2593. { Only modify the second parameter }
  2594. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2595. begin
  2596. Result := True;
  2597. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2598. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2599. end;
  2600. else
  2601. InternalError(2020012901);
  2602. end;
  2603. end;
  2604. else
  2605. if (hp.ops > 0) and
  2606. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2607. begin
  2608. Result := True;
  2609. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2610. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2611. end;
  2612. end;
  2613. end;
  2614. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2615. var
  2616. hp2: tai;
  2617. p_SourceReg, p_TargetReg: TRegister;
  2618. begin
  2619. Result := False;
  2620. { Backward optimisation. If we have:
  2621. func. %reg1,%reg2
  2622. mov %reg2,%reg3
  2623. (dealloc %reg2)
  2624. Change to:
  2625. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2626. Perform similar optimisations with 1, 3 and 4-operand instructions
  2627. that only have one output.
  2628. }
  2629. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2630. begin
  2631. p_SourceReg := taicpu(p).oper[0]^.reg;
  2632. p_TargetReg := taicpu(p).oper[1]^.reg;
  2633. TransferUsedRegs(TmpUsedRegs);
  2634. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2635. GetLastInstruction(p, hp2) and
  2636. (hp2.typ = ait_instruction) and
  2637. { Have to make sure it's an instruction that only reads from
  2638. the first operands and only writes (not reads or modifies) to
  2639. the last one; in essence, a pure function such as BSR, POPCNT
  2640. or ANDN }
  2641. (
  2642. (
  2643. (taicpu(hp2).ops = 1) and
  2644. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2645. ) or
  2646. (
  2647. (taicpu(hp2).ops = 2) and
  2648. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2649. ) or
  2650. (
  2651. (taicpu(hp2).ops = 3) and
  2652. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2653. ) or
  2654. (
  2655. (taicpu(hp2).ops = 4) and
  2656. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2657. )
  2658. ) and
  2659. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2660. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2661. begin
  2662. case taicpu(hp2).opcode of
  2663. A_FSTSW, A_FNSTSW,
  2664. A_IN, A_INS, A_OUT, A_OUTS,
  2665. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2666. { These routines have explicit operands, but they are restricted in
  2667. what they can be (e.g. IN and OUT can only read from AL, AX or
  2668. EAX. }
  2669. ;
  2670. else
  2671. begin
  2672. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2673. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2674. if not RegInInstruction(p_TargetReg, hp2) then
  2675. begin
  2676. { Since we're allocating from an earlier point, we
  2677. need to remove the register from the tracking }
  2678. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2679. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2680. end;
  2681. RemoveCurrentp(p, hp1);
  2682. { If the Func was another MOV instruction, we might get
  2683. "mov %reg,%reg" that doesn't get removed in Pass 2
  2684. otherwise, so deal with it here (also do something
  2685. similar with lea (%reg),%reg}
  2686. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2687. begin
  2688. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2689. if p = hp2 then
  2690. RemoveCurrentp(p)
  2691. else
  2692. RemoveInstruction(hp2);
  2693. end;
  2694. Result := True;
  2695. Exit;
  2696. end;
  2697. end;
  2698. end;
  2699. end;
  2700. end;
  2701. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2702. begin
  2703. Result := False;
  2704. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2705. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2706. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2707. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2708. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2709. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2710. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2711. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2712. begin
  2713. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2714. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2715. Result := True;
  2716. end;
  2717. end;
  2718. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2719. var
  2720. hp1, hp2, hp3, hp4: tai;
  2721. DoOptimisation, TempBool: Boolean;
  2722. {$ifdef x86_64}
  2723. NewConst: TCGInt;
  2724. {$endif x86_64}
  2725. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2726. begin
  2727. if taicpu(hp1).opcode = signed_movop then
  2728. begin
  2729. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2730. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2731. end
  2732. else
  2733. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2734. end;
  2735. function TryConstMerge(var p1, p2: tai): Boolean;
  2736. var
  2737. ThisRef: TReference;
  2738. begin
  2739. Result := False;
  2740. ThisRef := taicpu(p2).oper[1]^.ref^;
  2741. { Only permit writes to the stack, since we can guarantee alignment with that }
  2742. if (ThisRef.index = NR_NO) and
  2743. (
  2744. (ThisRef.base = NR_STACK_POINTER_REG) or
  2745. (ThisRef.base = current_procinfo.framepointer)
  2746. ) then
  2747. begin
  2748. case taicpu(p).opsize of
  2749. S_B:
  2750. begin
  2751. { Word writes must be on a 2-byte boundary }
  2752. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2753. begin
  2754. { Reduce offset of second reference to see if it is sequential with the first }
  2755. Dec(ThisRef.offset, 1);
  2756. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2757. begin
  2758. { Make sure the constants aren't represented as a
  2759. negative number, as these won't merge properly }
  2760. taicpu(p1).opsize := S_W;
  2761. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2762. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2763. RemoveInstruction(p2);
  2764. Result := True;
  2765. end;
  2766. end;
  2767. end;
  2768. S_W:
  2769. begin
  2770. { Longword writes must be on a 4-byte boundary }
  2771. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2772. begin
  2773. { Reduce offset of second reference to see if it is sequential with the first }
  2774. Dec(ThisRef.offset, 2);
  2775. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2776. begin
  2777. { Make sure the constants aren't represented as a
  2778. negative number, as these won't merge properly }
  2779. taicpu(p1).opsize := S_L;
  2780. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2781. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2782. RemoveInstruction(p2);
  2783. Result := True;
  2784. end;
  2785. end;
  2786. end;
  2787. {$ifdef x86_64}
  2788. S_L:
  2789. begin
  2790. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2791. see if the constants can be encoded this way. }
  2792. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2793. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2794. { Quadword writes must be on an 8-byte boundary }
  2795. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2796. begin
  2797. { Reduce offset of second reference to see if it is sequential with the first }
  2798. Dec(ThisRef.offset, 4);
  2799. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2800. begin
  2801. { Make sure the constants aren't represented as a
  2802. negative number, as these won't merge properly }
  2803. taicpu(p1).opsize := S_Q;
  2804. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2805. taicpu(p1).oper[0]^.val := NewConst;
  2806. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2807. RemoveInstruction(p2);
  2808. Result := True;
  2809. end;
  2810. end;
  2811. end;
  2812. {$endif x86_64}
  2813. else
  2814. ;
  2815. end;
  2816. end;
  2817. end;
  2818. var
  2819. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2820. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2821. NewSize: topsize; NewOffset: asizeint;
  2822. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2823. SourceRef, TargetRef: TReference;
  2824. MovAligned, MovUnaligned: TAsmOp;
  2825. ThisRef: TReference;
  2826. JumpTracking: TLinkedList;
  2827. begin
  2828. Result:=false;
  2829. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2830. { remove mov reg1,reg1? }
  2831. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2832. then
  2833. begin
  2834. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2835. { take care of the register (de)allocs following p }
  2836. RemoveCurrentP(p, hp1);
  2837. Result:=true;
  2838. exit;
  2839. end;
  2840. { All the next optimisations require a next instruction }
  2841. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2842. Exit;
  2843. { Prevent compiler warnings }
  2844. p_TargetReg := NR_NO;
  2845. if taicpu(p).oper[1]^.typ = top_reg then
  2846. begin
  2847. { Saves on a large number of dereferences }
  2848. p_TargetReg := taicpu(p).oper[1]^.reg;
  2849. { Look for:
  2850. mov %reg1,%reg2
  2851. ??? %reg2,r/m
  2852. Change to:
  2853. mov %reg1,%reg2
  2854. ??? %reg1,r/m
  2855. }
  2856. if taicpu(p).oper[0]^.typ = top_reg then
  2857. begin
  2858. if RegReadByInstruction(p_TargetReg, hp1) and
  2859. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2860. begin
  2861. { A change has occurred, just not in p }
  2862. Result := True;
  2863. TransferUsedRegs(TmpUsedRegs);
  2864. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2865. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2866. { Just in case something didn't get modified (e.g. an
  2867. implicit register) }
  2868. not RegReadByInstruction(p_TargetReg, hp1) then
  2869. begin
  2870. { We can remove the original MOV }
  2871. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2872. RemoveCurrentp(p, hp1);
  2873. { UsedRegs got updated by RemoveCurrentp }
  2874. Result := True;
  2875. Exit;
  2876. end;
  2877. { If we know a MOV instruction has become a null operation, we might as well
  2878. get rid of it now to save time. }
  2879. if (taicpu(hp1).opcode = A_MOV) and
  2880. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2881. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2882. { Just being a register is enough to confirm it's a null operation }
  2883. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2884. begin
  2885. Result := True;
  2886. { Speed-up to reduce a pipeline stall... if we had something like...
  2887. movl %eax,%edx
  2888. movw %dx,%ax
  2889. ... the second instruction would change to movw %ax,%ax, but
  2890. given that it is now %ax that's active rather than %eax,
  2891. penalties might occur due to a partial register write, so instead,
  2892. change it to a MOVZX instruction when optimising for speed.
  2893. }
  2894. if not (cs_opt_size in current_settings.optimizerswitches) and
  2895. IsMOVZXAcceptable and
  2896. (taicpu(hp1).opsize < taicpu(p).opsize)
  2897. {$ifdef x86_64}
  2898. { operations already implicitly set the upper 64 bits to zero }
  2899. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2900. {$endif x86_64}
  2901. then
  2902. begin
  2903. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2904. case taicpu(p).opsize of
  2905. S_W:
  2906. if taicpu(hp1).opsize = S_B then
  2907. taicpu(hp1).opsize := S_BL
  2908. else
  2909. InternalError(2020012911);
  2910. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2911. case taicpu(hp1).opsize of
  2912. S_B:
  2913. taicpu(hp1).opsize := S_BL;
  2914. S_W:
  2915. taicpu(hp1).opsize := S_WL;
  2916. else
  2917. InternalError(2020012912);
  2918. end;
  2919. else
  2920. InternalError(2020012910);
  2921. end;
  2922. taicpu(hp1).opcode := A_MOVZX;
  2923. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2924. end
  2925. else
  2926. begin
  2927. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2928. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2929. RemoveInstruction(hp1);
  2930. { The instruction after what was hp1 is now the immediate next instruction,
  2931. so we can continue to make optimisations if it's present }
  2932. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2933. Exit;
  2934. hp1 := hp2;
  2935. end;
  2936. end;
  2937. end;
  2938. end;
  2939. end;
  2940. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2941. overwrites the original destination register. e.g.
  2942. movl ###,%reg2d
  2943. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2944. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2945. }
  2946. if (taicpu(p).oper[1]^.typ = top_reg) and
  2947. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2948. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2949. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2950. begin
  2951. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2952. begin
  2953. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2954. case taicpu(p).oper[0]^.typ of
  2955. top_const:
  2956. { We have something like:
  2957. movb $x, %regb
  2958. movzbl %regb,%regd
  2959. Change to:
  2960. movl $x, %regd
  2961. }
  2962. begin
  2963. case taicpu(hp1).opsize of
  2964. S_BW:
  2965. begin
  2966. convert_mov_value(A_MOVSX, $FF);
  2967. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2968. taicpu(p).opsize := S_W;
  2969. end;
  2970. S_BL:
  2971. begin
  2972. convert_mov_value(A_MOVSX, $FF);
  2973. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2974. taicpu(p).opsize := S_L;
  2975. end;
  2976. S_WL:
  2977. begin
  2978. convert_mov_value(A_MOVSX, $FFFF);
  2979. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2980. taicpu(p).opsize := S_L;
  2981. end;
  2982. {$ifdef x86_64}
  2983. S_BQ:
  2984. begin
  2985. convert_mov_value(A_MOVSX, $FF);
  2986. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2987. taicpu(p).opsize := S_Q;
  2988. end;
  2989. S_WQ:
  2990. begin
  2991. convert_mov_value(A_MOVSX, $FFFF);
  2992. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2993. taicpu(p).opsize := S_Q;
  2994. end;
  2995. S_LQ:
  2996. begin
  2997. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2998. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2999. taicpu(p).opsize := S_Q;
  3000. end;
  3001. {$endif x86_64}
  3002. else
  3003. { If hp1 was a MOV instruction, it should have been
  3004. optimised already }
  3005. InternalError(2020021001);
  3006. end;
  3007. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3008. RemoveInstruction(hp1);
  3009. Result := True;
  3010. Exit;
  3011. end;
  3012. top_ref:
  3013. begin
  3014. { We have something like:
  3015. movb mem, %regb
  3016. movzbl %regb,%regd
  3017. Change to:
  3018. movzbl mem, %regd
  3019. }
  3020. ThisRef := taicpu(p).oper[0]^.ref^;
  3021. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3022. begin
  3023. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3024. taicpu(hp1).loadref(0, ThisRef);
  3025. { Make sure any registers in the references are properly tracked }
  3026. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  3027. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  3028. if (ThisRef.index <> NR_NO) then
  3029. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  3030. RemoveCurrentP(p, hp1);
  3031. Result := True;
  3032. Exit;
  3033. end;
  3034. end;
  3035. else
  3036. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3037. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3038. Exit;
  3039. end;
  3040. end
  3041. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3042. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3043. optimised }
  3044. else
  3045. begin
  3046. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3047. RemoveCurrentP(p, hp1);
  3048. Result := True;
  3049. Exit;
  3050. end;
  3051. end;
  3052. if (taicpu(hp1).opcode = A_AND) and
  3053. (taicpu(p).oper[1]^.typ = top_reg) and
  3054. MatchOpType(taicpu(hp1),top_const,top_reg) then
  3055. begin
  3056. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  3057. begin
  3058. case taicpu(p).opsize of
  3059. S_L:
  3060. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  3061. begin
  3062. { Optimize out:
  3063. mov x, %reg
  3064. and ffffffffh, %reg
  3065. }
  3066. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  3067. RemoveInstruction(hp1);
  3068. Result:=true;
  3069. exit;
  3070. end;
  3071. S_Q: { TODO: Confirm if this is even possible }
  3072. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  3073. begin
  3074. { Optimize out:
  3075. mov x, %reg
  3076. and ffffffffffffffffh, %reg
  3077. }
  3078. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  3079. RemoveInstruction(hp1);
  3080. Result:=true;
  3081. exit;
  3082. end;
  3083. else
  3084. ;
  3085. end;
  3086. if (
  3087. (taicpu(p).oper[0]^.typ=top_reg) or
  3088. (
  3089. (taicpu(p).oper[0]^.typ=top_ref) and
  3090. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  3091. )
  3092. ) and
  3093. GetNextInstruction(hp1,hp2) and
  3094. MatchInstruction(hp2,A_TEST,[]) and
  3095. (
  3096. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3097. (
  3098. { If the register being tested is smaller than the one
  3099. that received a bitwise AND, permit it if the constant
  3100. fits into the smaller size }
  3101. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3102. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3103. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3104. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3105. (
  3106. (
  3107. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3108. (taicpu(hp1).oper[0]^.val <= $FF)
  3109. ) or
  3110. (
  3111. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3112. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3113. {$ifdef x86_64}
  3114. ) or
  3115. (
  3116. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3117. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3118. {$endif x86_64}
  3119. )
  3120. )
  3121. )
  3122. ) and
  3123. (
  3124. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3125. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3126. ) and
  3127. GetNextInstruction(hp2,hp3) and
  3128. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3129. (taicpu(hp3).condition in [C_E,C_NE]) then
  3130. begin
  3131. TransferUsedRegs(TmpUsedRegs);
  3132. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3133. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3134. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3135. begin
  3136. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3137. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3138. taicpu(hp1).opcode:=A_TEST;
  3139. { Shrink the TEST instruction down to the smallest possible size }
  3140. case taicpu(hp1).oper[0]^.val of
  3141. 0..255:
  3142. if (taicpu(hp1).opsize <> S_B)
  3143. {$ifndef x86_64}
  3144. and (
  3145. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3146. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3147. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3148. )
  3149. {$endif x86_64}
  3150. then
  3151. begin
  3152. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3153. { Only print debug message if the TEST instruction
  3154. is a different size before and after }
  3155. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3156. taicpu(hp1).opsize := S_B;
  3157. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3158. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3159. end;
  3160. 256..65535:
  3161. if (taicpu(hp1).opsize <> S_W) then
  3162. begin
  3163. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3164. { Only print debug message if the TEST instruction
  3165. is a different size before and after }
  3166. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3167. taicpu(hp1).opsize := S_W;
  3168. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3169. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3170. end;
  3171. {$ifdef x86_64}
  3172. 65536..$7FFFFFFF:
  3173. if (taicpu(hp1).opsize <> S_L) then
  3174. begin
  3175. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3176. { Only print debug message if the TEST instruction
  3177. is a different size before and after }
  3178. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3179. taicpu(hp1).opsize := S_L;
  3180. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3181. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3182. end;
  3183. {$endif x86_64}
  3184. else
  3185. ;
  3186. end;
  3187. RemoveInstruction(hp2);
  3188. RemoveCurrentP(p, hp1);
  3189. Result:=true;
  3190. exit;
  3191. end;
  3192. end;
  3193. end
  3194. else if IsMOVZXAcceptable and
  3195. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3196. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3197. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3198. then
  3199. begin
  3200. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3201. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3202. case taicpu(p).opsize of
  3203. S_B:
  3204. if (taicpu(hp1).oper[0]^.val = $ff) then
  3205. begin
  3206. { Convert:
  3207. movb x, %regl movb x, %regl
  3208. andw ffh, %regw andl ffh, %regd
  3209. To:
  3210. movzbw x, %regd movzbl x, %regd
  3211. (Identical registers, just different sizes)
  3212. }
  3213. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3214. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3215. case taicpu(hp1).opsize of
  3216. S_W: NewSize := S_BW;
  3217. S_L: NewSize := S_BL;
  3218. {$ifdef x86_64}
  3219. S_Q: NewSize := S_BQ;
  3220. {$endif x86_64}
  3221. else
  3222. InternalError(2018011510);
  3223. end;
  3224. end
  3225. else
  3226. NewSize := S_NO;
  3227. S_W:
  3228. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3229. begin
  3230. { Convert:
  3231. movw x, %regw
  3232. andl ffffh, %regd
  3233. To:
  3234. movzwl x, %regd
  3235. (Identical registers, just different sizes)
  3236. }
  3237. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3238. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3239. case taicpu(hp1).opsize of
  3240. S_L: NewSize := S_WL;
  3241. {$ifdef x86_64}
  3242. S_Q: NewSize := S_WQ;
  3243. {$endif x86_64}
  3244. else
  3245. InternalError(2018011511);
  3246. end;
  3247. end
  3248. else
  3249. NewSize := S_NO;
  3250. else
  3251. NewSize := S_NO;
  3252. end;
  3253. if NewSize <> S_NO then
  3254. begin
  3255. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3256. { The actual optimization }
  3257. taicpu(p).opcode := A_MOVZX;
  3258. taicpu(p).changeopsize(NewSize);
  3259. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3260. { Safeguard if "and" is followed by a conditional command }
  3261. TransferUsedRegs(TmpUsedRegs);
  3262. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3263. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3264. begin
  3265. { At this point, the "and" command is effectively equivalent to
  3266. "test %reg,%reg". This will be handled separately by the
  3267. Peephole Optimizer. [Kit] }
  3268. DebugMsg(SPeepholeOptimization + PreMessage +
  3269. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3270. end
  3271. else
  3272. begin
  3273. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3274. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3275. RemoveInstruction(hp1);
  3276. end;
  3277. Result := True;
  3278. Exit;
  3279. end;
  3280. end;
  3281. end;
  3282. if (taicpu(hp1).opcode = A_OR) and
  3283. (taicpu(p).oper[1]^.typ = top_reg) and
  3284. MatchOperand(taicpu(p).oper[0]^, 0) and
  3285. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3286. begin
  3287. { mov 0, %reg
  3288. or ###,%reg
  3289. Change to (only if the flags are not used):
  3290. mov ###,%reg
  3291. }
  3292. TransferUsedRegs(TmpUsedRegs);
  3293. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3294. DoOptimisation := True;
  3295. { Even if the flags are used, we might be able to do the optimisation
  3296. if the conditions are predictable }
  3297. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3298. begin
  3299. { Only perform if ### = %reg (the same register) or equal to 0,
  3300. so %reg is guaranteed to still have a value of zero }
  3301. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3302. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3303. begin
  3304. hp2 := hp1;
  3305. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3306. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3307. GetNextInstruction(hp2, hp3) do
  3308. begin
  3309. { Don't continue modifying if the flags state is getting changed }
  3310. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3311. Break;
  3312. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3313. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3314. begin
  3315. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3316. begin
  3317. { Condition is always true }
  3318. case taicpu(hp3).opcode of
  3319. A_Jcc:
  3320. begin
  3321. { Check for jump shortcuts before we destroy the condition }
  3322. hp4 := hp3;
  3323. DoJumpOptimizations(hp3, TempBool);
  3324. { Make sure hp3 hasn't changed }
  3325. if (hp4 = hp3) then
  3326. begin
  3327. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3328. MakeUnconditional(taicpu(hp3));
  3329. end;
  3330. Result := True;
  3331. end;
  3332. A_CMOVcc:
  3333. begin
  3334. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3335. taicpu(hp3).opcode := A_MOV;
  3336. taicpu(hp3).condition := C_None;
  3337. Result := True;
  3338. end;
  3339. A_SETcc:
  3340. begin
  3341. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3342. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3343. taicpu(hp3).opcode := A_MOV;
  3344. taicpu(hp3).ops := 2;
  3345. taicpu(hp3).condition := C_None;
  3346. taicpu(hp3).opsize := S_B;
  3347. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3348. taicpu(hp3).loadconst(0, 1);
  3349. Result := True;
  3350. end;
  3351. else
  3352. InternalError(2021090701);
  3353. end;
  3354. end
  3355. 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
  3356. begin
  3357. { Condition is always false }
  3358. case taicpu(hp3).opcode of
  3359. A_Jcc:
  3360. begin
  3361. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3362. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3363. RemoveInstruction(hp3);
  3364. Result := True;
  3365. { Since hp3 was deleted, hp2 must not be updated }
  3366. Continue;
  3367. end;
  3368. A_CMOVcc:
  3369. begin
  3370. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3371. RemoveInstruction(hp3);
  3372. Result := True;
  3373. { Since hp3 was deleted, hp2 must not be updated }
  3374. Continue;
  3375. end;
  3376. A_SETcc:
  3377. begin
  3378. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3379. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3380. taicpu(hp3).opcode := A_MOV;
  3381. taicpu(hp3).ops := 2;
  3382. taicpu(hp3).condition := C_None;
  3383. taicpu(hp3).opsize := S_B;
  3384. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3385. taicpu(hp3).loadconst(0, 0);
  3386. Result := True;
  3387. end;
  3388. else
  3389. InternalError(2021090702);
  3390. end;
  3391. end
  3392. else
  3393. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3394. DoOptimisation := False;
  3395. end;
  3396. hp2 := hp3;
  3397. end;
  3398. { Flags are still in use - don't optimise }
  3399. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3400. DoOptimisation := False;
  3401. end
  3402. else
  3403. DoOptimisation := False;
  3404. end;
  3405. if DoOptimisation then
  3406. begin
  3407. {$ifdef x86_64}
  3408. { OR only supports 32-bit sign-extended constants for 64-bit
  3409. instructions, so compensate for this if the constant is
  3410. encoded as a value greater than or equal to 2^31 }
  3411. if (taicpu(hp1).opsize = S_Q) and
  3412. (taicpu(hp1).oper[0]^.typ = top_const) and
  3413. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3414. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3415. {$endif x86_64}
  3416. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3417. taicpu(hp1).opcode := A_MOV;
  3418. RemoveCurrentP(p, hp1);
  3419. Result := True;
  3420. Exit;
  3421. end;
  3422. end;
  3423. { Next instruction is also a MOV ? }
  3424. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3425. begin
  3426. if MatchOpType(taicpu(p), top_const, top_ref) and
  3427. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3428. TryConstMerge(p, hp1) then
  3429. begin
  3430. Result := True;
  3431. { In case we have four byte writes in a row, check for 2 more
  3432. right now so we don't have to wait for another iteration of
  3433. pass 1
  3434. }
  3435. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3436. case taicpu(p).opsize of
  3437. S_W:
  3438. begin
  3439. if GetNextInstruction(p, hp1) and
  3440. MatchInstruction(hp1, A_MOV, [S_B]) and
  3441. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3442. GetNextInstruction(hp1, hp2) and
  3443. MatchInstruction(hp2, A_MOV, [S_B]) and
  3444. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3445. { Try to merge the two bytes }
  3446. TryConstMerge(hp1, hp2) then
  3447. { Now try to merge the two words (hp2 will get deleted) }
  3448. TryConstMerge(p, hp1);
  3449. end;
  3450. S_L:
  3451. begin
  3452. { Though this only really benefits x86_64 and not i386, it
  3453. gets a potential optimisation done faster and hence
  3454. reduces the number of times OptPass1MOV is entered }
  3455. if GetNextInstruction(p, hp1) and
  3456. MatchInstruction(hp1, A_MOV, [S_W]) and
  3457. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3458. GetNextInstruction(hp1, hp2) and
  3459. MatchInstruction(hp2, A_MOV, [S_W]) and
  3460. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3461. { Try to merge the two words }
  3462. TryConstMerge(hp1, hp2) then
  3463. { This will always fail on i386, so don't bother
  3464. calling it unless we're doing x86_64 }
  3465. {$ifdef x86_64}
  3466. { Now try to merge the two longwords (hp2 will get deleted) }
  3467. TryConstMerge(p, hp1)
  3468. {$endif x86_64}
  3469. ;
  3470. end;
  3471. else
  3472. ;
  3473. end;
  3474. Exit;
  3475. end;
  3476. if (taicpu(p).oper[1]^.typ = top_reg) and
  3477. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3478. begin
  3479. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3480. TransferUsedRegs(TmpUsedRegs);
  3481. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3482. { we have
  3483. mov x, %treg
  3484. mov %treg, y
  3485. }
  3486. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3487. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3488. { we've got
  3489. mov x, %treg
  3490. mov %treg, y
  3491. with %treg is not used after }
  3492. case taicpu(p).oper[0]^.typ Of
  3493. { top_reg is covered by DeepMOVOpt }
  3494. top_const:
  3495. begin
  3496. { change
  3497. mov const, %treg
  3498. mov %treg, y
  3499. to
  3500. mov const, y
  3501. }
  3502. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3503. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3504. begin
  3505. if taicpu(hp1).oper[1]^.typ=top_reg then
  3506. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3507. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3508. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3509. RemoveInstruction(hp1);
  3510. Result:=true;
  3511. Exit;
  3512. end;
  3513. end;
  3514. top_ref:
  3515. case taicpu(hp1).oper[1]^.typ of
  3516. top_reg:
  3517. begin
  3518. { change
  3519. mov mem, %treg
  3520. mov %treg, %reg
  3521. to
  3522. mov mem, %reg"
  3523. }
  3524. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3525. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3526. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3527. RemoveInstruction(hp1);
  3528. Result:=true;
  3529. Exit;
  3530. end;
  3531. top_ref:
  3532. begin
  3533. {$ifdef x86_64}
  3534. { Look for the following to simplify:
  3535. mov x(mem1), %reg
  3536. mov %reg, y(mem2)
  3537. mov x+8(mem1), %reg
  3538. mov %reg, y+8(mem2)
  3539. Change to:
  3540. movdqu x(mem1), %xmmreg
  3541. movdqu %xmmreg, y(mem2)
  3542. ...but only as long as the memory blocks don't overlap
  3543. }
  3544. SourceRef := taicpu(p).oper[0]^.ref^;
  3545. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3546. if (taicpu(p).opsize = S_Q) and
  3547. GetNextInstruction(hp1, hp2) and
  3548. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3549. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3550. begin
  3551. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3552. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3553. Inc(SourceRef.offset, 8);
  3554. if UseAVX then
  3555. begin
  3556. MovAligned := A_VMOVDQA;
  3557. MovUnaligned := A_VMOVDQU;
  3558. end
  3559. else
  3560. begin
  3561. MovAligned := A_MOVDQA;
  3562. MovUnaligned := A_MOVDQU;
  3563. end;
  3564. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3565. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3566. begin
  3567. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3568. Inc(TargetRef.offset, 8);
  3569. if GetNextInstruction(hp2, hp3) and
  3570. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3571. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3572. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3573. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3574. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3575. begin
  3576. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3577. if NewMMReg <> NR_NO then
  3578. begin
  3579. { Remember that the offsets are 8 ahead }
  3580. if ((SourceRef.offset mod 16) = 8) and
  3581. (
  3582. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3583. (SourceRef.base = current_procinfo.framepointer) or
  3584. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3585. ) then
  3586. taicpu(p).opcode := MovAligned
  3587. else
  3588. taicpu(p).opcode := MovUnaligned;
  3589. taicpu(p).opsize := S_XMM;
  3590. taicpu(p).oper[1]^.reg := NewMMReg;
  3591. if ((TargetRef.offset mod 16) = 8) and
  3592. (
  3593. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3594. (TargetRef.base = current_procinfo.framepointer) or
  3595. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3596. ) then
  3597. taicpu(hp1).opcode := MovAligned
  3598. else
  3599. taicpu(hp1).opcode := MovUnaligned;
  3600. taicpu(hp1).opsize := S_XMM;
  3601. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3602. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3603. RemoveInstruction(hp2);
  3604. RemoveInstruction(hp3);
  3605. Result := True;
  3606. Exit;
  3607. end;
  3608. end;
  3609. end
  3610. else
  3611. begin
  3612. { See if the next references are 8 less rather than 8 greater }
  3613. Dec(SourceRef.offset, 16); { -8 the other way }
  3614. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3615. begin
  3616. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3617. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3618. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3619. GetNextInstruction(hp2, hp3) and
  3620. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3621. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3622. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3623. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3624. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3625. begin
  3626. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3627. if NewMMReg <> NR_NO then
  3628. begin
  3629. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3630. if ((SourceRef.offset mod 16) = 0) and
  3631. (
  3632. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3633. (SourceRef.base = current_procinfo.framepointer) or
  3634. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3635. ) then
  3636. taicpu(hp2).opcode := MovAligned
  3637. else
  3638. taicpu(hp2).opcode := MovUnaligned;
  3639. taicpu(hp2).opsize := S_XMM;
  3640. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3641. if ((TargetRef.offset mod 16) = 0) and
  3642. (
  3643. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3644. (TargetRef.base = current_procinfo.framepointer) or
  3645. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3646. ) then
  3647. taicpu(hp3).opcode := MovAligned
  3648. else
  3649. taicpu(hp3).opcode := MovUnaligned;
  3650. taicpu(hp3).opsize := S_XMM;
  3651. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3652. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3653. RemoveInstruction(hp1);
  3654. RemoveCurrentP(p, hp2);
  3655. Result := True;
  3656. Exit;
  3657. end;
  3658. end;
  3659. end;
  3660. end;
  3661. end;
  3662. {$endif x86_64}
  3663. end;
  3664. else
  3665. { The write target should be a reg or a ref }
  3666. InternalError(2021091601);
  3667. end;
  3668. else
  3669. ;
  3670. end
  3671. else
  3672. { %treg is used afterwards, but all eventualities
  3673. other than the first MOV instruction being a constant
  3674. are covered by DeepMOVOpt, so only check for that }
  3675. if (taicpu(p).oper[0]^.typ = top_const) and
  3676. (
  3677. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3678. not (cs_opt_size in current_settings.optimizerswitches) or
  3679. (taicpu(hp1).opsize = S_B)
  3680. ) and
  3681. (
  3682. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3683. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3684. ) then
  3685. begin
  3686. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3687. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3688. end;
  3689. end;
  3690. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3691. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3692. { mov reg1, mem1 or mov mem1, reg1
  3693. mov mem2, reg2 mov reg2, mem2}
  3694. begin
  3695. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3696. { mov reg1, mem1 or mov mem1, reg1
  3697. mov mem2, reg1 mov reg2, mem1}
  3698. begin
  3699. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3700. { Removes the second statement from
  3701. mov reg1, mem1/reg2
  3702. mov mem1/reg2, reg1 }
  3703. begin
  3704. if taicpu(p).oper[0]^.typ=top_reg then
  3705. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3706. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3707. RemoveInstruction(hp1);
  3708. Result:=true;
  3709. exit;
  3710. end
  3711. else
  3712. begin
  3713. TransferUsedRegs(TmpUsedRegs);
  3714. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3715. if (taicpu(p).oper[1]^.typ = top_ref) and
  3716. { mov reg1, mem1
  3717. mov mem2, reg1 }
  3718. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3719. GetNextInstruction(hp1, hp2) and
  3720. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3721. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3722. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3723. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3724. { change to
  3725. mov reg1, mem1 mov reg1, mem1
  3726. mov mem2, reg1 cmp reg1, mem2
  3727. cmp mem1, reg1
  3728. }
  3729. begin
  3730. RemoveInstruction(hp2);
  3731. taicpu(hp1).opcode := A_CMP;
  3732. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3733. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3734. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3735. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3736. end;
  3737. end;
  3738. end
  3739. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3740. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3741. begin
  3742. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3743. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3744. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3745. end
  3746. else
  3747. begin
  3748. TransferUsedRegs(TmpUsedRegs);
  3749. if GetNextInstruction(hp1, hp2) and
  3750. MatchOpType(taicpu(p),top_ref,top_reg) and
  3751. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3752. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3753. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3754. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3755. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3756. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3757. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3758. { mov mem1, %reg1
  3759. mov %reg1, mem2
  3760. mov mem2, reg2
  3761. to:
  3762. mov mem1, reg2
  3763. mov reg2, mem2}
  3764. begin
  3765. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3766. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3767. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3768. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3769. RemoveInstruction(hp2);
  3770. Result := True;
  3771. end
  3772. {$ifdef i386}
  3773. { this is enabled for i386 only, as the rules to create the reg sets below
  3774. are too complicated for x86-64, so this makes this code too error prone
  3775. on x86-64
  3776. }
  3777. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3778. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3779. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3780. { mov mem1, reg1 mov mem1, reg1
  3781. mov reg1, mem2 mov reg1, mem2
  3782. mov mem2, reg2 mov mem2, reg1
  3783. to: to:
  3784. mov mem1, reg1 mov mem1, reg1
  3785. mov mem1, reg2 mov reg1, mem2
  3786. mov reg1, mem2
  3787. or (if mem1 depends on reg1
  3788. and/or if mem2 depends on reg2)
  3789. to:
  3790. mov mem1, reg1
  3791. mov reg1, mem2
  3792. mov reg1, reg2
  3793. }
  3794. begin
  3795. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3796. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3797. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3798. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3799. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3800. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3801. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3802. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3803. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3804. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3805. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3806. end
  3807. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3808. begin
  3809. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3810. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3811. end
  3812. else
  3813. begin
  3814. RemoveInstruction(hp2);
  3815. end
  3816. {$endif i386}
  3817. ;
  3818. end;
  3819. end
  3820. { movl [mem1],reg1
  3821. movl [mem1],reg2
  3822. to
  3823. movl [mem1],reg1
  3824. movl reg1,reg2
  3825. }
  3826. else if not CheckMovMov2MovMov2(p, hp1) and
  3827. { movl const1,[mem1]
  3828. movl [mem1],reg1
  3829. to
  3830. movl const1,reg1
  3831. movl reg1,[mem1]
  3832. }
  3833. MatchOpType(Taicpu(p),top_const,top_ref) and
  3834. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3835. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3836. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3837. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3838. begin
  3839. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3840. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3841. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3842. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3843. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3844. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3845. Result:=true;
  3846. exit;
  3847. end;
  3848. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3849. { Change:
  3850. movl %reg1,%reg2
  3851. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3852. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3853. To:
  3854. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3855. movl x(%reg1),%reg1
  3856. movl %reg1,%regX
  3857. }
  3858. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3859. begin
  3860. p_SourceReg := taicpu(p).oper[0]^.reg;
  3861. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3862. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3863. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3864. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3865. GetNextInstruction(hp1, hp2) and
  3866. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3867. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3868. begin
  3869. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3870. if RegInRef(p_TargetReg, SourceRef) and
  3871. { If %reg1 also appears in the second reference, then it will
  3872. not refer to the same memory block as the first reference }
  3873. not RegInRef(p_SourceReg, SourceRef) then
  3874. begin
  3875. { Check to see if the references match if %reg2 is changed to %reg1 }
  3876. if SourceRef.base = p_TargetReg then
  3877. SourceRef.base := p_SourceReg;
  3878. if SourceRef.index = p_TargetReg then
  3879. SourceRef.index := p_SourceReg;
  3880. { RefsEqual also checks to ensure both references are non-volatile }
  3881. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3882. begin
  3883. taicpu(hp2).loadreg(0, p_SourceReg);
  3884. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3885. Result := True;
  3886. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3887. begin
  3888. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3889. RemoveCurrentP(p, hp1);
  3890. Exit;
  3891. end
  3892. else
  3893. begin
  3894. { Check to see if %reg2 is no longer in use }
  3895. TransferUsedRegs(TmpUsedRegs);
  3896. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3897. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3898. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3899. begin
  3900. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3901. RemoveCurrentP(p, hp1);
  3902. Exit;
  3903. end;
  3904. end;
  3905. { If we reach this point, p and hp1 weren't actually modified,
  3906. so we can do a bit more work on this pass }
  3907. end;
  3908. end;
  3909. end;
  3910. end;
  3911. end;
  3912. {$ifdef x86_64}
  3913. { Change:
  3914. movl %reg1l,%reg2l
  3915. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3916. To:
  3917. movl %reg1l,%reg2l
  3918. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3919. If %reg1 = %reg3, convert to:
  3920. movl %reg1l,%reg2l
  3921. andl %reg1l,%reg1l
  3922. }
  3923. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3924. MatchOpType(taicpu(p), top_reg, top_reg) and
  3925. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3926. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3927. begin
  3928. TransferUsedRegs(TmpUsedRegs);
  3929. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3930. taicpu(hp1).opsize := S_L;
  3931. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3932. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3933. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3934. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3935. begin
  3936. { %reg1 = %reg3 }
  3937. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3938. taicpu(hp1).opcode := A_AND;
  3939. end
  3940. else
  3941. begin
  3942. { %reg1 <> %reg3 }
  3943. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3944. end;
  3945. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3946. begin
  3947. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3948. RemoveCurrentP(p, hp1);
  3949. Result := True;
  3950. Exit;
  3951. end
  3952. else
  3953. begin
  3954. { Initial instruction wasn't actually changed }
  3955. Include(OptsToCheck, aoc_ForceNewIteration);
  3956. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3957. appears below since %reg1 has technically changed }
  3958. if taicpu(hp1).opcode = A_AND then
  3959. Exit;
  3960. end;
  3961. end;
  3962. {$endif x86_64}
  3963. { search further than the next instruction for a mov (as long as it's not a jump) }
  3964. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3965. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3966. (taicpu(p).oper[1]^.typ = top_reg) and
  3967. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3968. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3969. begin
  3970. { we work with hp2 here, so hp1 can be still used later on when
  3971. checking for GetNextInstruction_p }
  3972. hp3 := hp1;
  3973. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3974. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3975. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3976. TransferUsedRegs(TmpUsedRegs);
  3977. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3978. if NotFirstIteration then
  3979. JumpTracking := TLinkedList.Create
  3980. else
  3981. JumpTracking := nil;
  3982. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3983. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3984. (hp2.typ=ait_instruction) do
  3985. begin
  3986. case taicpu(hp2).opcode of
  3987. A_POP:
  3988. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3989. begin
  3990. if not CrossJump and
  3991. not RegUsedBetween(p_TargetReg, p, hp2) then
  3992. begin
  3993. { We can remove the original MOV since the register
  3994. wasn't used between it and its popping from the stack }
  3995. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3996. RemoveCurrentp(p, hp1);
  3997. Result := True;
  3998. JumpTracking.Free;
  3999. Exit;
  4000. end;
  4001. { Can't go any further }
  4002. Break;
  4003. end;
  4004. A_MOV:
  4005. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4006. ((taicpu(p).oper[0]^.typ=top_const) or
  4007. ((taicpu(p).oper[0]^.typ=top_reg) and
  4008. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4009. )
  4010. ) then
  4011. begin
  4012. { we have
  4013. mov x, %treg
  4014. mov %treg, y
  4015. }
  4016. { We don't need to call UpdateUsedRegs for every instruction between
  4017. p and hp2 because the register we're concerned about will not
  4018. become deallocated (otherwise GetNextInstructionUsingReg would
  4019. have stopped at an earlier instruction). [Kit] }
  4020. TempRegUsed :=
  4021. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4022. RegReadByInstruction(p_TargetReg, hp3) or
  4023. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4024. case taicpu(p).oper[0]^.typ Of
  4025. top_reg:
  4026. begin
  4027. { change
  4028. mov %reg, %treg
  4029. mov %treg, y
  4030. to
  4031. mov %reg, y
  4032. }
  4033. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4034. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4035. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4036. begin
  4037. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4038. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4039. if TempRegUsed then
  4040. begin
  4041. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4042. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4043. { Set the start of the next GetNextInstructionUsingRegCond search
  4044. to start at the entry right before hp2 (which is about to be removed) }
  4045. hp3 := tai(hp2.Previous);
  4046. RemoveInstruction(hp2);
  4047. Include(OptsToCheck, aoc_ForceNewIteration);
  4048. { See if there's more we can optimise }
  4049. Continue;
  4050. end
  4051. else
  4052. begin
  4053. RemoveInstruction(hp2);
  4054. { We can remove the original MOV too }
  4055. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4056. RemoveCurrentP(p, hp1);
  4057. Result:=true;
  4058. JumpTracking.Free;
  4059. Exit;
  4060. end;
  4061. end
  4062. else
  4063. begin
  4064. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4065. taicpu(hp2).loadReg(0, p_SourceReg);
  4066. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4067. { Check to see if the register also appears in the reference }
  4068. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4069. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4070. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4071. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4072. begin
  4073. { Don't remove the first instruction if the temporary register is in use }
  4074. if not TempRegUsed then
  4075. begin
  4076. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4077. RemoveCurrentP(p, hp1);
  4078. Result:=true;
  4079. JumpTracking.Free;
  4080. Exit;
  4081. end;
  4082. { No need to set Result to True here. If there's another instruction later
  4083. on that can be optimised, it will be detected when the main Pass 1 loop
  4084. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4085. hp3 := hp2;
  4086. Continue;
  4087. end;
  4088. end;
  4089. end;
  4090. top_const:
  4091. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4092. begin
  4093. { change
  4094. mov const, %treg
  4095. mov %treg, y
  4096. to
  4097. mov const, y
  4098. }
  4099. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4100. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4101. begin
  4102. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4103. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4104. if TempRegUsed then
  4105. begin
  4106. { Don't remove the first instruction if the temporary register is in use }
  4107. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4108. { No need to set Result to True. If there's another instruction later on
  4109. that can be optimised, it will be detected when the main Pass 1 loop
  4110. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4111. end
  4112. else
  4113. begin
  4114. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4115. RemoveCurrentP(p, hp1);
  4116. Result:=true;
  4117. Exit;
  4118. end;
  4119. end;
  4120. end;
  4121. else
  4122. Internalerror(2019103001);
  4123. end;
  4124. end
  4125. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4126. begin
  4127. if not CrossJump and
  4128. not RegUsedBetween(p_TargetReg, p, hp2) and
  4129. not RegReadByInstruction(p_TargetReg, hp2) then
  4130. begin
  4131. { Register is not used before it is overwritten }
  4132. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4133. RemoveCurrentp(p, hp1);
  4134. Result := True;
  4135. Exit;
  4136. end;
  4137. if (taicpu(p).oper[0]^.typ = top_const) and
  4138. (taicpu(hp2).oper[0]^.typ = top_const) then
  4139. begin
  4140. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4141. begin
  4142. { Same value - register hasn't changed }
  4143. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4144. RemoveInstruction(hp2);
  4145. Include(OptsToCheck, aoc_ForceNewIteration);
  4146. { See if there's more we can optimise }
  4147. Continue;
  4148. end;
  4149. end;
  4150. {$ifdef x86_64}
  4151. end
  4152. { Change:
  4153. movl %reg1l,%reg2l
  4154. ...
  4155. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4156. To:
  4157. movl %reg1l,%reg2l
  4158. ...
  4159. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4160. If %reg1 = %reg3, convert to:
  4161. movl %reg1l,%reg2l
  4162. ...
  4163. andl %reg1l,%reg1l
  4164. }
  4165. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4166. (taicpu(p).oper[0]^.typ = top_reg) and
  4167. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4168. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4169. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4170. begin
  4171. TempRegUsed :=
  4172. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4173. RegReadByInstruction(p_TargetReg, hp3) or
  4174. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4175. taicpu(hp2).opsize := S_L;
  4176. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4177. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4178. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4179. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4180. begin
  4181. { %reg1 = %reg3 }
  4182. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4183. taicpu(hp2).opcode := A_AND;
  4184. end
  4185. else
  4186. begin
  4187. { %reg1 <> %reg3 }
  4188. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4189. end;
  4190. if not TempRegUsed then
  4191. begin
  4192. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4193. RemoveCurrentP(p, hp1);
  4194. Result := True;
  4195. Exit;
  4196. end
  4197. else
  4198. begin
  4199. { Initial instruction wasn't actually changed }
  4200. Include(OptsToCheck, aoc_ForceNewIteration);
  4201. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4202. appears below since %reg1 has technically changed }
  4203. if taicpu(hp2).opcode = A_AND then
  4204. Break;
  4205. end;
  4206. {$endif x86_64}
  4207. end
  4208. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4209. GetNextInstruction(hp2, hp4) and
  4210. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4211. { Optimise the following first:
  4212. movl [mem1],reg1
  4213. movl [mem1],reg2
  4214. to
  4215. movl [mem1],reg1
  4216. movl reg1,reg2
  4217. If [mem1] contains the target register and reg1 is the
  4218. the source register, this optimisation will get missed
  4219. and produce less efficient code later on.
  4220. }
  4221. if CheckMovMov2MovMov2(hp2, hp4) then
  4222. { Initial instruction wasn't actually changed }
  4223. Include(OptsToCheck, aoc_ForceNewIteration);
  4224. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4225. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4226. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4227. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4228. begin
  4229. {
  4230. Change from:
  4231. mov ###, %reg
  4232. ...
  4233. movs/z %reg,%reg (Same register, just different sizes)
  4234. To:
  4235. movs/z ###, %reg (Longer version)
  4236. ...
  4237. (remove)
  4238. }
  4239. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4240. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4241. { Keep the first instruction as mov if ### is a constant }
  4242. if taicpu(p).oper[0]^.typ = top_const then
  4243. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4244. else
  4245. begin
  4246. taicpu(p).opcode := taicpu(hp2).opcode;
  4247. taicpu(p).opsize := taicpu(hp2).opsize;
  4248. end;
  4249. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4250. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4251. RemoveInstruction(hp2);
  4252. Result := True;
  4253. JumpTracking.Free;
  4254. Exit;
  4255. end;
  4256. else
  4257. { Move down to the if-block below };
  4258. end;
  4259. { Also catches MOV/S/Z instructions that aren't modified }
  4260. if taicpu(p).oper[0]^.typ = top_reg then
  4261. begin
  4262. p_SourceReg := taicpu(p).oper[0]^.reg;
  4263. if
  4264. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4265. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4266. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4267. begin
  4268. Result := True;
  4269. { Just in case something didn't get modified (e.g. an
  4270. implicit register). Also, if it does read from this
  4271. register, then there's no longer an advantage to
  4272. changing the register on subsequent instructions.}
  4273. if not RegReadByInstruction(p_TargetReg, hp2) then
  4274. begin
  4275. { If a conditional jump was crossed, do not delete
  4276. the original MOV no matter what }
  4277. if not CrossJump and
  4278. { RegEndOfLife returns True if the register is
  4279. deallocated before the next instruction or has
  4280. been loaded with a new value }
  4281. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4282. begin
  4283. { We can remove the original MOV }
  4284. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4285. RemoveCurrentp(p, hp1);
  4286. JumpTracking.Free;
  4287. Result := True;
  4288. Exit;
  4289. end;
  4290. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4291. begin
  4292. { See if there's more we can optimise }
  4293. hp3 := hp2;
  4294. Continue;
  4295. end;
  4296. end;
  4297. end;
  4298. end;
  4299. { Break out of the while loop under normal circumstances }
  4300. Break;
  4301. end;
  4302. JumpTracking.Free;
  4303. end;
  4304. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4305. (taicpu(p).oper[1]^.typ = top_reg) and
  4306. (taicpu(p).opsize = S_L) and
  4307. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4308. (hp2.typ = ait_instruction) and
  4309. (taicpu(hp2).opcode = A_AND) and
  4310. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4311. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4312. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4313. ) then
  4314. begin
  4315. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4316. begin
  4317. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4318. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4319. begin
  4320. { Optimize out:
  4321. mov x, %reg
  4322. and ffffffffh, %reg
  4323. }
  4324. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4325. RemoveInstruction(hp2);
  4326. Result:=true;
  4327. exit;
  4328. end;
  4329. end;
  4330. end;
  4331. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4332. x >= RetOffset) as it doesn't do anything (it writes either to a
  4333. parameter or to the temporary storage room for the function
  4334. result)
  4335. }
  4336. if IsExitCode(hp1) and
  4337. (taicpu(p).oper[1]^.typ = top_ref) and
  4338. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4339. (
  4340. (
  4341. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4342. not (
  4343. assigned(current_procinfo.procdef.funcretsym) and
  4344. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4345. )
  4346. ) or
  4347. { Also discard writes to the stack that are below the base pointer,
  4348. as this is temporary storage rather than a function result on the
  4349. stack, say. }
  4350. (
  4351. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4352. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4353. )
  4354. ) then
  4355. begin
  4356. RemoveCurrentp(p, hp1);
  4357. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4358. RemoveLastDeallocForFuncRes(p);
  4359. Result:=true;
  4360. exit;
  4361. end;
  4362. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4363. begin
  4364. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4365. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4366. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4367. begin
  4368. { change
  4369. mov reg1, mem1
  4370. test/cmp x, mem1
  4371. to
  4372. mov reg1, mem1
  4373. test/cmp x, reg1
  4374. }
  4375. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4376. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4377. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4378. Result := True;
  4379. Exit;
  4380. end;
  4381. if DoMovCmpMemOpt(p, hp1) then
  4382. begin
  4383. Result := True;
  4384. Exit;
  4385. end;
  4386. end;
  4387. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4388. { If the flags register is in use, don't change the instruction to an
  4389. ADD otherwise this will scramble the flags. [Kit] }
  4390. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4391. begin
  4392. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4393. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4394. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4395. ) or
  4396. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4397. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4398. )
  4399. ) then
  4400. { mov reg1,ref
  4401. lea reg2,[reg1,reg2]
  4402. to
  4403. add reg2,ref}
  4404. begin
  4405. TransferUsedRegs(TmpUsedRegs);
  4406. { reg1 may not be used afterwards }
  4407. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4408. begin
  4409. Taicpu(hp1).opcode:=A_ADD;
  4410. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4411. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4412. RemoveCurrentp(p, hp1);
  4413. result:=true;
  4414. exit;
  4415. end;
  4416. end;
  4417. { If the LEA instruction can be converted into an arithmetic instruction,
  4418. it may be possible to then fold it in the next optimisation, otherwise
  4419. there's nothing more that can be optimised here. }
  4420. if not ConvertLEA(taicpu(hp1)) then
  4421. Exit;
  4422. end;
  4423. if (taicpu(p).oper[1]^.typ = top_reg) and
  4424. (hp1.typ = ait_instruction) and
  4425. GetNextInstruction(hp1, hp2) and
  4426. MatchInstruction(hp2,A_MOV,[]) and
  4427. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4428. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4429. (
  4430. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4431. {$ifdef x86_64}
  4432. or
  4433. (
  4434. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4435. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4436. )
  4437. {$endif x86_64}
  4438. ) then
  4439. begin
  4440. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4441. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4442. { change movsX/movzX reg/ref, reg2
  4443. add/sub/or/... reg3/$const, reg2
  4444. mov reg2 reg/ref
  4445. dealloc reg2
  4446. to
  4447. add/sub/or/... reg3/$const, reg/ref }
  4448. begin
  4449. TransferUsedRegs(TmpUsedRegs);
  4450. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4451. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4452. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4453. begin
  4454. { by example:
  4455. movswl %si,%eax movswl %si,%eax p
  4456. decl %eax addl %edx,%eax hp1
  4457. movw %ax,%si movw %ax,%si hp2
  4458. ->
  4459. movswl %si,%eax movswl %si,%eax p
  4460. decw %eax addw %edx,%eax hp1
  4461. movw %ax,%si movw %ax,%si hp2
  4462. }
  4463. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4464. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4465. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4466. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4467. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4468. {
  4469. ->
  4470. movswl %si,%eax movswl %si,%eax p
  4471. decw %si addw %dx,%si hp1
  4472. movw %ax,%si movw %ax,%si hp2
  4473. }
  4474. case taicpu(hp1).ops of
  4475. 1:
  4476. begin
  4477. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4478. if taicpu(hp1).oper[0]^.typ=top_reg then
  4479. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4480. end;
  4481. 2:
  4482. begin
  4483. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4484. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4485. (taicpu(hp1).opcode<>A_SHL) and
  4486. (taicpu(hp1).opcode<>A_SHR) and
  4487. (taicpu(hp1).opcode<>A_SAR) then
  4488. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4489. end;
  4490. else
  4491. internalerror(2008042701);
  4492. end;
  4493. {
  4494. ->
  4495. decw %si addw %dx,%si p
  4496. }
  4497. RemoveInstruction(hp2);
  4498. RemoveCurrentP(p, hp1);
  4499. Result:=True;
  4500. Exit;
  4501. end;
  4502. end;
  4503. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4504. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4505. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4506. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4507. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4508. )
  4509. {$ifdef i386}
  4510. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4511. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4512. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4513. {$endif i386}
  4514. then
  4515. { change movsX/movzX reg/ref, reg2
  4516. add/sub/or/... regX/$const, reg2
  4517. mov reg2, reg3
  4518. dealloc reg2
  4519. to
  4520. movsX/movzX reg/ref, reg3
  4521. add/sub/or/... reg3/$const, reg3
  4522. }
  4523. begin
  4524. TransferUsedRegs(TmpUsedRegs);
  4525. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4526. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4527. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4528. begin
  4529. { by example:
  4530. movswl %si,%eax movswl %si,%eax p
  4531. decl %eax addl %edx,%eax hp1
  4532. movw %ax,%si movw %ax,%si hp2
  4533. ->
  4534. movswl %si,%eax movswl %si,%eax p
  4535. decw %eax addw %edx,%eax hp1
  4536. movw %ax,%si movw %ax,%si hp2
  4537. }
  4538. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4539. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4540. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4541. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4542. { limit size of constants as well to avoid assembler errors, but
  4543. check opsize to avoid overflow when left shifting the 1 }
  4544. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4545. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4546. {$ifdef x86_64}
  4547. { Be careful of, for example:
  4548. movl %reg1,%reg2
  4549. addl %reg3,%reg2
  4550. movq %reg2,%reg4
  4551. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4552. }
  4553. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4554. begin
  4555. taicpu(hp2).changeopsize(S_L);
  4556. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4557. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4558. end;
  4559. {$endif x86_64}
  4560. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4561. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4562. if taicpu(p).oper[0]^.typ=top_reg then
  4563. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4564. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4565. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4566. {
  4567. ->
  4568. movswl %si,%eax movswl %si,%eax p
  4569. decw %si addw %dx,%si hp1
  4570. movw %ax,%si movw %ax,%si hp2
  4571. }
  4572. case taicpu(hp1).ops of
  4573. 1:
  4574. begin
  4575. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4576. if taicpu(hp1).oper[0]^.typ=top_reg then
  4577. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4578. end;
  4579. 2:
  4580. begin
  4581. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4582. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4583. (taicpu(hp1).opcode<>A_SHL) and
  4584. (taicpu(hp1).opcode<>A_SHR) and
  4585. (taicpu(hp1).opcode<>A_SAR) then
  4586. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4587. end;
  4588. else
  4589. internalerror(2018111801);
  4590. end;
  4591. {
  4592. ->
  4593. decw %si addw %dx,%si p
  4594. }
  4595. RemoveInstruction(hp2);
  4596. end;
  4597. end;
  4598. end;
  4599. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4600. GetNextInstruction(hp1, hp2) and
  4601. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4602. MatchOperand(Taicpu(p).oper[0]^,0) and
  4603. (Taicpu(p).oper[1]^.typ = top_reg) and
  4604. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4605. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4606. { mov reg1,0
  4607. bts reg1,operand1 --> mov reg1,operand2
  4608. or reg1,operand2 bts reg1,operand1}
  4609. begin
  4610. Taicpu(hp2).opcode:=A_MOV;
  4611. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4612. asml.remove(hp1);
  4613. insertllitem(hp2,hp2.next,hp1);
  4614. RemoveCurrentp(p, hp1);
  4615. Result:=true;
  4616. exit;
  4617. end;
  4618. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4619. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4620. GetNextInstruction(hp1, hp2) and
  4621. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4622. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4623. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4624. { change
  4625. mov reg1,reg2
  4626. sub reg3,reg2
  4627. cmp reg3,reg1
  4628. into
  4629. mov reg1,reg2
  4630. sub reg3,reg2
  4631. }
  4632. begin
  4633. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4634. RemoveInstruction(hp2);
  4635. Result:=true;
  4636. exit;
  4637. end;
  4638. {
  4639. mov ref,reg0
  4640. <op> reg0,reg1
  4641. dealloc reg0
  4642. to
  4643. <op> ref,reg1
  4644. }
  4645. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4646. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4647. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4648. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4649. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4650. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4651. begin
  4652. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4653. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4654. RemoveCurrentp(p, hp1);
  4655. Result:=true;
  4656. exit;
  4657. end;
  4658. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4659. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4660. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4661. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4662. begin
  4663. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4664. {$ifdef x86_64}
  4665. { Convert:
  4666. movq x(ref),%reg64
  4667. shrq y,%reg64
  4668. To:
  4669. movl x+4(ref),%reg32
  4670. shrl y-32,%reg32 (Remove if y = 32)
  4671. }
  4672. if (taicpu(p).opsize = S_Q) and
  4673. (taicpu(hp1).opcode = A_SHR) and
  4674. (taicpu(hp1).oper[0]^.val >= 32) then
  4675. begin
  4676. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4677. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4678. { Convert to 32-bit }
  4679. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4680. taicpu(p).opsize := S_L;
  4681. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4682. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4683. if (taicpu(hp1).oper[0]^.val = 32) then
  4684. begin
  4685. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4686. RemoveInstruction(hp1);
  4687. end
  4688. else
  4689. begin
  4690. { This will potentially open up more arithmetic operations since
  4691. the peephole optimizer now has a big hint that only the lower
  4692. 32 bits are currently in use (and opcodes are smaller in size) }
  4693. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4694. taicpu(hp1).opsize := S_L;
  4695. Dec(taicpu(hp1).oper[0]^.val, 32);
  4696. DebugMsg(SPeepholeOptimization + PreMessage +
  4697. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4698. end;
  4699. Result := True;
  4700. Exit;
  4701. end;
  4702. {$endif x86_64}
  4703. { Convert:
  4704. movl x(ref),%reg
  4705. shrl $24,%reg
  4706. To:
  4707. movzbl x+3(ref),%reg
  4708. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4709. Also accept sar instead of shr, but convert to movsx instead of movzx
  4710. }
  4711. if taicpu(hp1).opcode = A_SHR then
  4712. MovUnaligned := A_MOVZX
  4713. else
  4714. MovUnaligned := A_MOVSX;
  4715. NewSize := S_NO;
  4716. NewOffset := 0;
  4717. case taicpu(p).opsize of
  4718. S_B:
  4719. { No valid combinations };
  4720. S_W:
  4721. if (taicpu(hp1).oper[0]^.val = 8) then
  4722. begin
  4723. NewSize := S_BW;
  4724. NewOffset := 1;
  4725. end;
  4726. S_L:
  4727. case taicpu(hp1).oper[0]^.val of
  4728. 16:
  4729. begin
  4730. NewSize := S_WL;
  4731. NewOffset := 2;
  4732. end;
  4733. 24:
  4734. begin
  4735. NewSize := S_BL;
  4736. NewOffset := 3;
  4737. end;
  4738. else
  4739. ;
  4740. end;
  4741. {$ifdef x86_64}
  4742. S_Q:
  4743. case taicpu(hp1).oper[0]^.val of
  4744. 32:
  4745. begin
  4746. if taicpu(hp1).opcode = A_SAR then
  4747. begin
  4748. { 32-bit to 64-bit is a distinct instruction }
  4749. MovUnaligned := A_MOVSXD;
  4750. NewSize := S_LQ;
  4751. NewOffset := 4;
  4752. end
  4753. else
  4754. { Should have been handled by MovShr2Mov above }
  4755. InternalError(2022081811);
  4756. end;
  4757. 48:
  4758. begin
  4759. NewSize := S_WQ;
  4760. NewOffset := 6;
  4761. end;
  4762. 56:
  4763. begin
  4764. NewSize := S_BQ;
  4765. NewOffset := 7;
  4766. end;
  4767. else
  4768. ;
  4769. end;
  4770. {$endif x86_64}
  4771. else
  4772. InternalError(2022081810);
  4773. end;
  4774. if (NewSize <> S_NO) and
  4775. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4776. begin
  4777. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4778. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4779. debug_op2str(MovUnaligned);
  4780. {$ifdef x86_64}
  4781. if MovUnaligned <> A_MOVSXD then
  4782. { Don't add size suffix for MOVSXD }
  4783. {$endif x86_64}
  4784. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4785. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4786. taicpu(p).opcode := MovUnaligned;
  4787. taicpu(p).opsize := NewSize;
  4788. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4789. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4790. RemoveInstruction(hp1);
  4791. Result := True;
  4792. Exit;
  4793. end;
  4794. end;
  4795. { Backward optimisation shared with OptPass2MOV }
  4796. if FuncMov2Func(p, hp1) then
  4797. begin
  4798. Result := True;
  4799. Exit;
  4800. end;
  4801. end;
  4802. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4803. var
  4804. hp1 : tai;
  4805. begin
  4806. Result:=false;
  4807. if taicpu(p).ops <> 2 then
  4808. exit;
  4809. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4810. GetNextInstruction(p,hp1) then
  4811. begin
  4812. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4813. (taicpu(hp1).ops = 2) then
  4814. begin
  4815. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4816. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4817. { movXX reg1, mem1 or movXX mem1, reg1
  4818. movXX mem2, reg2 movXX reg2, mem2}
  4819. begin
  4820. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4821. { movXX reg1, mem1 or movXX mem1, reg1
  4822. movXX mem2, reg1 movXX reg2, mem1}
  4823. begin
  4824. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4825. begin
  4826. { Removes the second statement from
  4827. movXX reg1, mem1/reg2
  4828. movXX mem1/reg2, reg1
  4829. }
  4830. if taicpu(p).oper[0]^.typ=top_reg then
  4831. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4832. { Removes the second statement from
  4833. movXX mem1/reg1, reg2
  4834. movXX reg2, mem1/reg1
  4835. }
  4836. if (taicpu(p).oper[1]^.typ=top_reg) and
  4837. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4838. begin
  4839. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4840. RemoveInstruction(hp1);
  4841. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4842. Result:=true;
  4843. exit;
  4844. end
  4845. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4846. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4847. begin
  4848. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4849. RemoveInstruction(hp1);
  4850. Result:=true;
  4851. exit;
  4852. end;
  4853. end
  4854. end;
  4855. end;
  4856. end;
  4857. end;
  4858. end;
  4859. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4860. var
  4861. hp1 : tai;
  4862. begin
  4863. result:=false;
  4864. { replace
  4865. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4866. MovX %mreg2,%mreg1
  4867. dealloc %mreg2
  4868. by
  4869. <Op>X %mreg2,%mreg1
  4870. ?
  4871. }
  4872. if GetNextInstruction(p,hp1) and
  4873. { we mix single and double opperations here because we assume that the compiler
  4874. generates vmovapd only after double operations and vmovaps only after single operations }
  4875. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4876. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4877. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4878. (taicpu(p).oper[0]^.typ=top_reg) then
  4879. begin
  4880. TransferUsedRegs(TmpUsedRegs);
  4881. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4882. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4883. begin
  4884. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4885. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4886. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4887. RemoveInstruction(hp1);
  4888. result:=true;
  4889. end;
  4890. end;
  4891. end;
  4892. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4893. var
  4894. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4895. JumpLabel, JumpLabel_dist: TAsmLabel;
  4896. FirstValue, SecondValue: TCGInt;
  4897. function OptimizeJump(var InputP: tai): Boolean;
  4898. var
  4899. TempBool: Boolean;
  4900. begin
  4901. Result := False;
  4902. TempBool := True;
  4903. if DoJumpOptimizations(InputP, TempBool) or
  4904. not TempBool then
  4905. begin
  4906. Result := True;
  4907. if Assigned(InputP) then
  4908. begin
  4909. { CollapseZeroDistJump will be set to the label or an align
  4910. before it after the jump if it optimises, whether or not
  4911. the label is live or dead }
  4912. if (InputP.typ = ait_align) or
  4913. (
  4914. (InputP.typ = ait_label) and
  4915. not (tai_label(InputP).labsym.is_used)
  4916. ) then
  4917. GetNextInstruction(InputP, InputP);
  4918. end;
  4919. Exit;
  4920. end;
  4921. end;
  4922. begin
  4923. Result := False;
  4924. if (taicpu(p).oper[0]^.typ = top_const) and
  4925. (taicpu(p).oper[0]^.val <> -1) then
  4926. begin
  4927. { Convert unsigned maximum constants to -1 to aid optimisation }
  4928. case taicpu(p).opsize of
  4929. S_B:
  4930. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4931. begin
  4932. taicpu(p).oper[0]^.val := -1;
  4933. Result := True;
  4934. Exit;
  4935. end;
  4936. S_W:
  4937. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4938. begin
  4939. taicpu(p).oper[0]^.val := -1;
  4940. Result := True;
  4941. Exit;
  4942. end;
  4943. S_L:
  4944. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4945. begin
  4946. taicpu(p).oper[0]^.val := -1;
  4947. Result := True;
  4948. Exit;
  4949. end;
  4950. {$ifdef x86_64}
  4951. S_Q:
  4952. { Storing anything greater than $7FFFFFFF is not possible so do
  4953. nothing };
  4954. {$endif x86_64}
  4955. else
  4956. InternalError(2021121001);
  4957. end;
  4958. end;
  4959. if GetNextInstruction(p, hp1) and
  4960. TrySwapMovCmp(p, hp1) then
  4961. begin
  4962. Result := True;
  4963. Exit;
  4964. end;
  4965. p_label := nil;
  4966. JumpLabel := nil;
  4967. if MatchInstruction(hp1, A_Jcc, []) then
  4968. begin
  4969. if OptimizeJump(hp1) then
  4970. begin
  4971. Result := True;
  4972. if Assigned(hp1) then
  4973. begin
  4974. { CollapseZeroDistJump will be set to the label or an align
  4975. before it after the jump if it optimises, whether or not
  4976. the label is live or dead }
  4977. if (hp1.typ = ait_align) or
  4978. (
  4979. (hp1.typ = ait_label) and
  4980. not (tai_label(hp1).labsym.is_used)
  4981. ) then
  4982. GetNextInstruction(hp1, hp1);
  4983. end;
  4984. TransferUsedRegs(TmpUsedRegs);
  4985. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4986. if not Assigned(hp1) or
  4987. (
  4988. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4989. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4990. ) then
  4991. begin
  4992. { No more conditional jumps; conditional statement is no longer required }
  4993. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4994. RemoveCurrentP(p);
  4995. end;
  4996. Exit;
  4997. end;
  4998. if IsJumpToLabel(taicpu(hp1)) then
  4999. begin
  5000. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5001. if Assigned(JumpLabel) then
  5002. p_label := getlabelwithsym(JumpLabel);
  5003. end;
  5004. end;
  5005. { Search for:
  5006. test $x,(reg/ref)
  5007. jne @lbl1
  5008. test $y,(reg/ref) (same register or reference)
  5009. jne @lbl1
  5010. Change to:
  5011. test $(x or y),(reg/ref)
  5012. jne @lbl1
  5013. (Note, this doesn't work with je instead of jne)
  5014. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5015. Also search for:
  5016. test $x,(reg/ref)
  5017. je @lbl1
  5018. ...
  5019. test $y,(reg/ref)
  5020. je/jne @lbl2
  5021. If (x or y) = x, then the second jump is deterministic
  5022. }
  5023. if (
  5024. (
  5025. (taicpu(p).oper[0]^.typ = top_const) or
  5026. (
  5027. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5028. (taicpu(p).oper[0]^.typ = top_reg) and
  5029. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5030. )
  5031. ) and
  5032. MatchInstruction(hp1, A_JCC, [])
  5033. ) then
  5034. begin
  5035. if (taicpu(p).oper[0]^.typ = top_reg) and
  5036. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5037. FirstValue := -1
  5038. else
  5039. FirstValue := taicpu(p).oper[0]^.val;
  5040. { If we have several test/jne's in a row, it might be the case that
  5041. the second label doesn't go to the same location, but the one
  5042. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5043. so accommodate for this with a while loop.
  5044. }
  5045. hp1_last := hp1;
  5046. while (
  5047. (
  5048. (taicpu(p).oper[1]^.typ = top_reg) and
  5049. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5050. ) or GetNextInstruction(hp1_last, p_dist)
  5051. ) and (p_dist.typ = ait_instruction) do
  5052. begin
  5053. if (
  5054. (
  5055. (taicpu(p_dist).opcode = A_TEST) and
  5056. (
  5057. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5058. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5059. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5060. )
  5061. ) or
  5062. (
  5063. { cmp 0,%reg = test %reg,%reg }
  5064. (taicpu(p_dist).opcode = A_CMP) and
  5065. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5066. )
  5067. ) and
  5068. { Make sure the destination operands are actually the same }
  5069. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5070. GetNextInstruction(p_dist, hp1_dist) and
  5071. MatchInstruction(hp1_dist, A_JCC, []) then
  5072. begin
  5073. if OptimizeJump(hp1_dist) then
  5074. begin
  5075. Result := True;
  5076. Exit;
  5077. end;
  5078. if
  5079. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5080. (
  5081. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5082. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5083. ) then
  5084. SecondValue := -1
  5085. else
  5086. SecondValue := taicpu(p_dist).oper[0]^.val;
  5087. { If both of the TEST constants are identical, delete the
  5088. second TEST that is unnecessary (be careful though, just
  5089. in case the flags are modified in between) }
  5090. if (FirstValue = SecondValue) then
  5091. begin
  5092. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5093. begin
  5094. { Since the second jump's condition is a subset of the first, we
  5095. know it will never branch because the first jump dominates it.
  5096. Get it out of the way now rather than wait for the jump
  5097. optimisations for a speed boost. }
  5098. if IsJumpToLabel(taicpu(hp1_dist)) then
  5099. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5100. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5101. RemoveInstruction(hp1_dist);
  5102. Result := True;
  5103. end
  5104. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5105. begin
  5106. { If the inverse of the first condition is a subset of the second,
  5107. the second one will definitely branch if the first one doesn't }
  5108. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5109. { We can remove the TEST instruction too }
  5110. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5111. RemoveInstruction(p_dist);
  5112. MakeUnconditional(taicpu(hp1_dist));
  5113. RemoveDeadCodeAfterJump(hp1_dist);
  5114. { Since the jump is now unconditional, we can't
  5115. continue any further with this particular
  5116. optimisation. The original TEST is still intact
  5117. though, so there might be something else we can
  5118. do }
  5119. Include(OptsToCheck, aoc_ForceNewIteration);
  5120. Break;
  5121. end;
  5122. if Result or
  5123. { If a jump wasn't removed or made unconditional, only
  5124. remove the identical TEST instruction if the flags
  5125. weren't modified }
  5126. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5127. begin
  5128. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5129. RemoveInstruction(p_dist);
  5130. { If the jump was removed or made unconditional, we
  5131. don't need to allocate NR_DEFAULTFLAGS over the
  5132. entire range }
  5133. if not Result then
  5134. begin
  5135. { Mark the flags as 'in use' over the entire range }
  5136. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5137. { Speed gain - continue search from the Jcc instruction }
  5138. hp1_last := hp1_dist;
  5139. { Only the TEST instruction was removed, and the
  5140. original was unchanged, so we can safely do
  5141. another iteration of the while loop }
  5142. Include(OptsToCheck, aoc_ForceNewIteration);
  5143. Continue;
  5144. end;
  5145. Exit;
  5146. end;
  5147. end;
  5148. hp1_last := nil;
  5149. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5150. (
  5151. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5152. { Always adjacent under -O2 and under }
  5153. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5154. (
  5155. GetNextInstruction(hp1, hp1_last) and
  5156. (hp1_last = p_dist)
  5157. )
  5158. ) and
  5159. (
  5160. (
  5161. { Test the following variant:
  5162. test $x,(reg/ref)
  5163. jne @lbl1
  5164. test $y,(reg/ref)
  5165. je @lbl2
  5166. @lbl1:
  5167. Becomes:
  5168. test $(x or y),(reg/ref)
  5169. je @lbl2
  5170. @lbl1: (may become a dead label)
  5171. }
  5172. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5173. GetNextInstruction(hp1_dist, hp1_last) and
  5174. (hp1_last = p_label)
  5175. ) or
  5176. (
  5177. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5178. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5179. then the second jump will never branch, so it can also be
  5180. removed regardless of where it goes }
  5181. (
  5182. (FirstValue = -1) or
  5183. (SecondValue = -1) or
  5184. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5185. )
  5186. )
  5187. ) then
  5188. begin
  5189. { Same jump location... can be a register since nothing's changed }
  5190. { If any of the entries are equivalent to test %reg,%reg, then the
  5191. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5192. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5193. if (hp1_last = p_label) then
  5194. begin
  5195. { Variant }
  5196. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5197. RemoveInstruction(p_dist);
  5198. if Assigned(JumpLabel) then
  5199. JumpLabel.decrefs;
  5200. RemoveInstruction(hp1);
  5201. end
  5202. else
  5203. begin
  5204. { Only remove the second test if no jumps or other conditional instructions follow }
  5205. TransferUsedRegs(TmpUsedRegs);
  5206. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5207. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5208. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5209. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5210. begin
  5211. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5212. RemoveInstruction(p_dist);
  5213. { Remove the first jump, not the second, to keep
  5214. any register deallocations between the second
  5215. TEST/JNE pair in the same place. Aids future
  5216. optimisation. }
  5217. if Assigned(JumpLabel) then
  5218. JumpLabel.decrefs;
  5219. RemoveInstruction(hp1);
  5220. end
  5221. else
  5222. begin
  5223. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5224. if IsJumpToLabel(taicpu(hp1_dist)) then
  5225. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5226. { Remove second jump in this instance }
  5227. RemoveInstruction(hp1_dist);
  5228. end;
  5229. end;
  5230. Result := True;
  5231. Exit;
  5232. end;
  5233. end;
  5234. if { If -O2 and under, it may stop on any old instruction }
  5235. (cs_opt_level3 in current_settings.optimizerswitches) and
  5236. (taicpu(p).oper[1]^.typ = top_reg) and
  5237. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5238. begin
  5239. hp1_last := p_dist;
  5240. Continue;
  5241. end;
  5242. Break;
  5243. end;
  5244. end;
  5245. { Search for:
  5246. test %reg,%reg
  5247. j(c1) @lbl1
  5248. ...
  5249. @lbl:
  5250. test %reg,%reg (same register)
  5251. j(c2) @lbl2
  5252. If c2 is a subset of c1, change to:
  5253. test %reg,%reg
  5254. j(c1) @lbl2
  5255. (@lbl1 may become a dead label as a result)
  5256. }
  5257. if (taicpu(p).oper[1]^.typ = top_reg) and
  5258. (taicpu(p).oper[0]^.typ = top_reg) and
  5259. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5260. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5261. Assigned(p_label) and
  5262. GetNextInstruction(p_label, p_dist) and
  5263. MatchInstruction(p_dist, A_TEST, []) and
  5264. { It's fine if the second test uses smaller sub-registers }
  5265. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5266. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5267. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5268. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5269. GetNextInstruction(p_dist, hp1_dist) and
  5270. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5271. begin
  5272. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5273. if JumpLabel = JumpLabel_dist then
  5274. { This is an infinite loop }
  5275. Exit;
  5276. { Best optimisation when the first condition is a subset (or equal) of the second }
  5277. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5278. begin
  5279. { Any registers used here will already be allocated }
  5280. if Assigned(JumpLabel) then
  5281. JumpLabel.DecRefs;
  5282. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5283. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5284. Result := True;
  5285. Exit;
  5286. end;
  5287. end;
  5288. end;
  5289. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5290. var
  5291. hp1, hp2: tai;
  5292. ActiveReg: TRegister;
  5293. OldOffset: asizeint;
  5294. ThisConst: TCGInt;
  5295. function RegDeallocated: Boolean;
  5296. begin
  5297. TransferUsedRegs(TmpUsedRegs);
  5298. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5299. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5300. end;
  5301. begin
  5302. result:=false;
  5303. hp1 := nil;
  5304. { replace
  5305. addX const,%reg1
  5306. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5307. dealloc %reg1
  5308. by
  5309. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5310. }
  5311. if MatchOpType(taicpu(p),top_const,top_reg) then
  5312. begin
  5313. ActiveReg := taicpu(p).oper[1]^.reg;
  5314. { Ensures the entire register was updated }
  5315. if (taicpu(p).opsize >= S_L) and
  5316. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5317. MatchInstruction(hp1,A_LEA,[]) and
  5318. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5319. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5320. (
  5321. { Cover the case where the register in the reference is also the destination register }
  5322. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5323. (
  5324. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5325. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5326. RegDeallocated
  5327. )
  5328. ) then
  5329. begin
  5330. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5331. {$push}
  5332. {$R-}{$Q-}
  5333. { Explicitly disable overflow checking for these offset calculation
  5334. as those do not matter for the final result }
  5335. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5336. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5337. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5338. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5339. {$pop}
  5340. {$ifdef x86_64}
  5341. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5342. begin
  5343. { Overflow; abort }
  5344. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5345. end
  5346. else
  5347. {$endif x86_64}
  5348. begin
  5349. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5350. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5351. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5352. RemoveCurrentP(p, hp1)
  5353. else
  5354. RemoveCurrentP(p);
  5355. result:=true;
  5356. Exit;
  5357. end;
  5358. end;
  5359. if (
  5360. { Save calling GetNextInstructionUsingReg again }
  5361. Assigned(hp1) or
  5362. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5363. ) and
  5364. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5365. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5366. begin
  5367. if taicpu(hp1).oper[0]^.typ = top_const then
  5368. begin
  5369. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5370. if taicpu(hp1).opcode = A_ADD then
  5371. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5372. else
  5373. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5374. Result := True;
  5375. { Handle any overflows }
  5376. case taicpu(p).opsize of
  5377. S_B:
  5378. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5379. S_W:
  5380. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5381. S_L:
  5382. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5383. {$ifdef x86_64}
  5384. S_Q:
  5385. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5386. { Overflow; abort }
  5387. Result := False
  5388. else
  5389. taicpu(p).oper[0]^.val := ThisConst;
  5390. {$endif x86_64}
  5391. else
  5392. InternalError(2021102610);
  5393. end;
  5394. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5395. if Result then
  5396. begin
  5397. if (taicpu(p).oper[0]^.val < 0) and
  5398. (
  5399. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5400. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5401. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5402. ) then
  5403. begin
  5404. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5405. taicpu(p).opcode := A_SUB;
  5406. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5407. end
  5408. else
  5409. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5410. RemoveInstruction(hp1);
  5411. end;
  5412. end
  5413. else
  5414. begin
  5415. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5416. TransferUsedRegs(TmpUsedRegs);
  5417. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5418. hp2 := p;
  5419. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5420. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5421. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5422. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5423. begin
  5424. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5425. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5426. Asml.Remove(p);
  5427. Asml.InsertAfter(p, hp1);
  5428. p := hp1;
  5429. Result := True;
  5430. Exit;
  5431. end;
  5432. end;
  5433. end;
  5434. if DoArithCombineOpt(p) then
  5435. Result:=true;
  5436. end;
  5437. end;
  5438. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5439. var
  5440. hp1, hp2: tai;
  5441. ref: Integer;
  5442. saveref: treference;
  5443. offsetcalc: Int64;
  5444. TempReg: TRegister;
  5445. Multiple: TCGInt;
  5446. Adjacent, IntermediateRegDiscarded: Boolean;
  5447. begin
  5448. Result:=false;
  5449. { play save and throw an error if LEA uses a seg register prefix,
  5450. this is most likely an error somewhere else }
  5451. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5452. internalerror(2022022001);
  5453. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5454. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5455. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5456. (
  5457. { do not mess with leas accessing the stack pointer
  5458. unless it's a null operation }
  5459. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5460. (
  5461. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5462. (taicpu(p).oper[0]^.ref^.offset = 0)
  5463. )
  5464. ) and
  5465. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5466. begin
  5467. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5468. begin
  5469. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5470. begin
  5471. taicpu(p).opcode := A_MOV;
  5472. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5473. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5474. end
  5475. else
  5476. begin
  5477. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5478. RemoveCurrentP(p);
  5479. end;
  5480. Result:=true;
  5481. exit;
  5482. end
  5483. else if (
  5484. { continue to use lea to adjust the stack pointer,
  5485. it is the recommended way, but only if not optimizing for size }
  5486. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5487. (cs_opt_size in current_settings.optimizerswitches)
  5488. ) and
  5489. { If the flags register is in use, don't change the instruction
  5490. to an ADD otherwise this will scramble the flags. [Kit] }
  5491. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5492. ConvertLEA(taicpu(p)) then
  5493. begin
  5494. Result:=true;
  5495. exit;
  5496. end;
  5497. end;
  5498. { Don't optimise if the stack or frame pointer is the destination register }
  5499. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5500. Exit;
  5501. if GetNextInstruction(p,hp1) and
  5502. (hp1.typ=ait_instruction) then
  5503. begin
  5504. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5505. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5506. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5507. begin
  5508. TransferUsedRegs(TmpUsedRegs);
  5509. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5510. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5511. begin
  5512. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5513. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5514. RemoveInstruction(hp1);
  5515. result:=true;
  5516. exit;
  5517. end;
  5518. end;
  5519. { changes
  5520. lea <ref1>, reg1
  5521. <op> ...,<ref. with reg1>,...
  5522. to
  5523. <op> ...,<ref1>,... }
  5524. { find a reference which uses reg1 }
  5525. 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
  5526. ref:=0
  5527. 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
  5528. ref:=1
  5529. else
  5530. ref:=-1;
  5531. if (ref<>-1) and
  5532. { reg1 must be either the base or the index }
  5533. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5534. begin
  5535. { reg1 can be removed from the reference }
  5536. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5537. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5538. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5539. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5540. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5541. else
  5542. Internalerror(2019111201);
  5543. { check if the can insert all data of the lea into the second instruction }
  5544. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5545. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5546. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5547. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5548. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5549. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5550. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5551. {$ifdef x86_64}
  5552. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5553. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5554. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5555. )
  5556. {$endif x86_64}
  5557. then
  5558. begin
  5559. { reg1 might not used by the second instruction after it is remove from the reference }
  5560. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5561. begin
  5562. TransferUsedRegs(TmpUsedRegs);
  5563. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5564. { reg1 is not updated so it might not be used afterwards }
  5565. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5566. begin
  5567. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5568. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5569. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5570. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5571. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5572. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5573. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5574. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5575. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5576. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5577. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5578. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5579. RemoveCurrentP(p, hp1);
  5580. result:=true;
  5581. exit;
  5582. end
  5583. end;
  5584. end;
  5585. { recover }
  5586. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5587. end;
  5588. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5589. if Adjacent or
  5590. { Check further ahead (up to 2 instructions ahead for -O2) }
  5591. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5592. begin
  5593. { Check common LEA/LEA conditions }
  5594. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5595. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5596. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5597. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5598. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5599. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5600. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5601. (
  5602. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5603. calling it (since it calls GetNextInstruction) }
  5604. Adjacent or
  5605. (
  5606. (
  5607. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5608. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5609. ) and (
  5610. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5611. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5612. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5613. )
  5614. )
  5615. ) then
  5616. begin
  5617. TransferUsedRegs(TmpUsedRegs);
  5618. hp2 := p;
  5619. repeat
  5620. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5621. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5622. IntermediateRegDiscarded :=
  5623. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5624. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5625. { changes
  5626. lea offset1(regX,scale), reg1
  5627. lea offset2(reg1,reg1), reg2
  5628. to
  5629. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5630. and
  5631. lea offset1(regX,scale1), reg1
  5632. lea offset2(reg1,scale2), reg2
  5633. to
  5634. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5635. and
  5636. lea offset1(regX,scale1), reg1
  5637. lea offset2(reg3,reg1,scale2), reg2
  5638. to
  5639. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5640. ... so long as the final scale does not exceed 8
  5641. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5642. }
  5643. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5644. (
  5645. { Don't optimise if size is a concern and the intermediate register remains in use }
  5646. IntermediateRegDiscarded or
  5647. not (cs_opt_size in current_settings.optimizerswitches)
  5648. ) and
  5649. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5650. (
  5651. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5652. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5653. ) and (
  5654. (
  5655. { lea (reg1,scale2), reg2 variant }
  5656. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5657. (
  5658. Adjacent or
  5659. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5660. ) and
  5661. (
  5662. (
  5663. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5664. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5665. ) or (
  5666. { lea (regX,regX), reg1 variant }
  5667. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5668. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5669. )
  5670. )
  5671. ) or (
  5672. { lea (reg1,reg1), reg1 variant }
  5673. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5674. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5675. )
  5676. ) then
  5677. begin
  5678. { Make everything homogeneous to make calculations easier }
  5679. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5680. begin
  5681. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5682. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5683. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5684. else
  5685. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5686. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5687. end;
  5688. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5689. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5690. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5691. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5692. begin
  5693. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5694. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5695. begin
  5696. { Put the register to change in the index register }
  5697. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5698. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5699. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5700. end;
  5701. { Change lea (reg,reg) to lea(,reg,2) }
  5702. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5703. begin
  5704. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5705. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5706. end;
  5707. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5708. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5709. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5710. { Just to prevent miscalculations }
  5711. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5712. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5713. else
  5714. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5715. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5716. if IntermediateRegDiscarded then
  5717. begin
  5718. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5719. RemoveCurrentP(p);
  5720. end
  5721. else
  5722. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5723. result:=true;
  5724. exit;
  5725. end;
  5726. end;
  5727. { changes
  5728. lea offset1(regX), reg1
  5729. lea offset2(reg1), reg2
  5730. to
  5731. lea offset1+offset2(regX), reg2 }
  5732. if (
  5733. { Don't optimise if size is a concern and the intermediate register remains in use }
  5734. IntermediateRegDiscarded or
  5735. not (cs_opt_size in current_settings.optimizerswitches)
  5736. ) and
  5737. (
  5738. (
  5739. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5740. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5741. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5742. ) or (
  5743. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5744. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5745. (
  5746. (
  5747. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5748. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5749. ) or (
  5750. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5751. (
  5752. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5753. (
  5754. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5755. (
  5756. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5757. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5758. )
  5759. )
  5760. )
  5761. )
  5762. )
  5763. )
  5764. ) then
  5765. begin
  5766. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5767. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5768. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5769. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5770. begin
  5771. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5772. begin
  5773. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5774. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5775. { if the register is used as index and base, we have to increase for base as well
  5776. and adapt base }
  5777. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5778. begin
  5779. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5780. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5781. end;
  5782. end
  5783. else
  5784. begin
  5785. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5786. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5787. end;
  5788. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5789. begin
  5790. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5791. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5792. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  5793. { Catch the situation where the base = index
  5794. and treat this as *2. The scalefactor of
  5795. p will be 0 or 1 due to the conditional
  5796. checks above. Fixes i40647 }
  5797. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  5798. else
  5799. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  5800. end;
  5801. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5802. if IntermediateRegDiscarded then
  5803. begin
  5804. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5805. RemoveCurrentP(p);
  5806. end
  5807. else
  5808. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5809. result:=true;
  5810. exit;
  5811. end;
  5812. end;
  5813. end;
  5814. { Change:
  5815. leal/q $x(%reg1),%reg2
  5816. ...
  5817. shll/q $y,%reg2
  5818. To:
  5819. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5820. }
  5821. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5822. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5823. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5824. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5825. (taicpu(hp1).oper[0]^.val <= 3) then
  5826. begin
  5827. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5828. TransferUsedRegs(TmpUsedRegs);
  5829. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5830. if
  5831. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5832. (this works even if scalefactor is zero) }
  5833. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5834. { Ensure offset doesn't go out of bounds }
  5835. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5836. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5837. (
  5838. (
  5839. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5840. (
  5841. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5842. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5843. (
  5844. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5845. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5846. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5847. )
  5848. )
  5849. ) or (
  5850. (
  5851. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5852. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5853. ) and
  5854. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5855. )
  5856. ) then
  5857. begin
  5858. repeat
  5859. with taicpu(p).oper[0]^.ref^ do
  5860. begin
  5861. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5862. if index = base then
  5863. begin
  5864. if Multiple > 4 then
  5865. { Optimisation will no longer work because resultant
  5866. scale factor will exceed 8 }
  5867. Break;
  5868. base := NR_NO;
  5869. scalefactor := 2;
  5870. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5871. end
  5872. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5873. begin
  5874. { Scale factor only works on the index register }
  5875. index := base;
  5876. base := NR_NO;
  5877. end;
  5878. { For safety }
  5879. if scalefactor <= 1 then
  5880. begin
  5881. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5882. scalefactor := Multiple;
  5883. end
  5884. else
  5885. begin
  5886. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5887. scalefactor := scalefactor * Multiple;
  5888. end;
  5889. offset := offset * Multiple;
  5890. end;
  5891. RemoveInstruction(hp1);
  5892. Result := True;
  5893. Exit;
  5894. { This repeat..until loop exists for the benefit of Break }
  5895. until True;
  5896. end;
  5897. end;
  5898. end;
  5899. end;
  5900. end;
  5901. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5902. var
  5903. hp1 : tai;
  5904. SubInstr: Boolean;
  5905. ThisConst: TCGInt;
  5906. const
  5907. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5908. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5909. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5910. begin
  5911. Result := False;
  5912. if taicpu(p).oper[0]^.typ <> top_const then
  5913. { Should have been confirmed before calling }
  5914. InternalError(2021102601);
  5915. SubInstr := (taicpu(p).opcode = A_SUB);
  5916. if GetLastInstruction(p, hp1) and
  5917. (hp1.typ = ait_instruction) and
  5918. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5919. begin
  5920. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5921. { Bad size }
  5922. InternalError(2022042001);
  5923. case taicpu(hp1).opcode Of
  5924. A_INC:
  5925. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5926. begin
  5927. if SubInstr then
  5928. ThisConst := taicpu(p).oper[0]^.val - 1
  5929. else
  5930. ThisConst := taicpu(p).oper[0]^.val + 1;
  5931. end
  5932. else
  5933. Exit;
  5934. A_DEC:
  5935. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5936. begin
  5937. if SubInstr then
  5938. ThisConst := taicpu(p).oper[0]^.val + 1
  5939. else
  5940. ThisConst := taicpu(p).oper[0]^.val - 1;
  5941. end
  5942. else
  5943. Exit;
  5944. A_SUB:
  5945. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5946. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5947. begin
  5948. if SubInstr then
  5949. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5950. else
  5951. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5952. end
  5953. else
  5954. Exit;
  5955. A_ADD:
  5956. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5957. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5958. begin
  5959. if SubInstr then
  5960. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5961. else
  5962. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5963. end
  5964. else
  5965. Exit;
  5966. else
  5967. Exit;
  5968. end;
  5969. { Check that the values are in range }
  5970. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5971. { Overflow; abort }
  5972. Exit;
  5973. if (ThisConst = 0) then
  5974. begin
  5975. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5976. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5977. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5978. RemoveInstruction(hp1);
  5979. hp1 := tai(p.next);
  5980. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5981. if not GetLastInstruction(hp1, p) then
  5982. p := hp1;
  5983. end
  5984. else
  5985. begin
  5986. if taicpu(hp1).opercnt=1 then
  5987. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5988. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5989. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5990. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5991. else
  5992. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5993. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5994. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5995. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5996. RemoveInstruction(hp1);
  5997. taicpu(p).loadconst(0, ThisConst);
  5998. end;
  5999. Result := True;
  6000. end;
  6001. end;
  6002. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6003. begin
  6004. Result := False;
  6005. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6006. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6007. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6008. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6009. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6010. (
  6011. (
  6012. (taicpu(hp1).opcode = A_TEST)
  6013. ) or (
  6014. (taicpu(hp1).opcode = A_CMP) and
  6015. { A sanity check more than anything }
  6016. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6017. )
  6018. ) then
  6019. begin
  6020. { change
  6021. mov mem, %reg
  6022. ...
  6023. cmp/test x, %reg / test %reg,%reg
  6024. (reg deallocated)
  6025. to
  6026. cmp/test x, mem / cmp 0, mem
  6027. }
  6028. TransferUsedRegs(TmpUsedRegs);
  6029. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6030. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6031. begin
  6032. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6033. if (taicpu(hp1).opcode = A_TEST) and
  6034. (
  6035. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6036. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6037. ) then
  6038. begin
  6039. taicpu(hp1).opcode := A_CMP;
  6040. taicpu(hp1).loadconst(0, 0);
  6041. end;
  6042. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6043. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6044. RemoveCurrentP(p);
  6045. if (p <> hp1) then
  6046. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6047. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6048. { Make sure the flags are allocated across the CMP instruction }
  6049. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6050. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6051. Result := True;
  6052. Exit;
  6053. end;
  6054. end;
  6055. end;
  6056. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6057. var
  6058. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6059. ThisReg, SecondReg: TRegister;
  6060. JumpLoc: TAsmLabel;
  6061. NewSize: TOpSize;
  6062. begin
  6063. Result := False;
  6064. {
  6065. Convert:
  6066. j<c> .L1
  6067. .L2:
  6068. mov 1,reg
  6069. jmp .L3 (or ret, although it might not be a RET yet)
  6070. .L1:
  6071. mov 0,reg
  6072. jmp .L3 (or ret)
  6073. ( As long as .L3 <> .L1 or .L2)
  6074. To:
  6075. mov 0,reg
  6076. set<not(c)> reg
  6077. jmp .L3 (or ret)
  6078. .L2:
  6079. mov 1,reg
  6080. jmp .L3 (or ret)
  6081. .L1:
  6082. mov 0,reg
  6083. jmp .L3 (or ret)
  6084. }
  6085. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6086. Exit;
  6087. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6088. if GetNextInstruction(hp_label, hp2) and
  6089. MatchInstruction(hp2,A_MOV,[]) and
  6090. (taicpu(hp2).oper[0]^.typ = top_const) and
  6091. (
  6092. (
  6093. (taicpu(hp2).oper[1]^.typ = top_reg)
  6094. {$ifdef i386}
  6095. { Under i386, ESI, EDI, EBP and ESP
  6096. don't have an 8-bit representation }
  6097. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6098. {$endif i386}
  6099. ) or (
  6100. {$ifdef i386}
  6101. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6102. {$endif i386}
  6103. (taicpu(hp2).opsize = S_B)
  6104. )
  6105. ) and
  6106. GetNextInstruction(hp2, hp3) and
  6107. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6108. (
  6109. (taicpu(hp3).opcode=A_RET) or
  6110. (
  6111. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6112. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6113. )
  6114. ) and
  6115. GetNextInstruction(hp3, hp4) and
  6116. (hp4.typ=ait_label) and
  6117. (tai_label(hp4).labsym=JumpLoc) and
  6118. (
  6119. not (cs_opt_size in current_settings.optimizerswitches) or
  6120. { If the initial jump is the label's only reference, then it will
  6121. become a dead label if the other conditions are met and hence
  6122. remove at least 2 instructions, including a jump }
  6123. (JumpLoc.getrefs = 1)
  6124. ) and
  6125. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6126. that will be optimised out }
  6127. GetNextInstruction(hp4, hp5) and
  6128. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6129. (taicpu(hp5).oper[0]^.typ = top_const) and
  6130. (
  6131. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6132. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6133. ) and
  6134. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6135. GetNextInstruction(hp5,hp6) and
  6136. (
  6137. (hp6.typ<>ait_label) or
  6138. SkipLabels(hp6, hp6)
  6139. ) and
  6140. (hp6.typ=ait_instruction) then
  6141. begin
  6142. { First, let's look at the two jumps that are hp3 and hp6 }
  6143. if not
  6144. (
  6145. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6146. (
  6147. (taicpu(hp6).opcode=A_RET) or
  6148. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6149. )
  6150. ) then
  6151. { If condition is False, then the JMP/RET instructions matched conventionally }
  6152. begin
  6153. { See if one of the jumps can be instantly converted into a RET }
  6154. if (taicpu(hp3).opcode=A_JMP) then
  6155. begin
  6156. { Reuse hp5 }
  6157. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6158. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  6159. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  6160. Exit;
  6161. if MatchInstruction(hp5, A_RET, []) then
  6162. begin
  6163. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6164. ConvertJumpToRET(hp3, hp5);
  6165. Result := True;
  6166. end
  6167. else
  6168. Exit;
  6169. end;
  6170. if (taicpu(hp6).opcode=A_JMP) then
  6171. begin
  6172. { Reuse hp5 }
  6173. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6174. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6175. Exit;
  6176. if MatchInstruction(hp5, A_RET, []) then
  6177. begin
  6178. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6179. ConvertJumpToRET(hp6, hp5);
  6180. Result := True;
  6181. end
  6182. else
  6183. Exit;
  6184. end;
  6185. if not
  6186. (
  6187. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6188. (
  6189. (taicpu(hp6).opcode=A_RET) or
  6190. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6191. )
  6192. ) then
  6193. { Still doesn't match }
  6194. Exit;
  6195. end;
  6196. if (taicpu(hp2).oper[0]^.val = 1) then
  6197. begin
  6198. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6199. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6200. end
  6201. else
  6202. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6203. if taicpu(hp2).opsize=S_B then
  6204. begin
  6205. if taicpu(hp2).oper[1]^.typ = top_reg then
  6206. begin
  6207. SecondReg := taicpu(hp2).oper[1]^.reg;
  6208. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6209. end
  6210. else
  6211. begin
  6212. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6213. SecondReg := NR_NO;
  6214. end;
  6215. hp_pos := p;
  6216. hp_allocstart := hp4;
  6217. end
  6218. else
  6219. begin
  6220. { Will be a register because the size can't be S_B otherwise }
  6221. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6222. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6223. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6224. if (cs_opt_size in current_settings.optimizerswitches) then
  6225. begin
  6226. { Favour using MOVZX when optimising for size }
  6227. case taicpu(hp2).opsize of
  6228. S_W:
  6229. NewSize := S_BW;
  6230. S_L:
  6231. NewSize := S_BL;
  6232. {$ifdef x86_64}
  6233. S_Q:
  6234. begin
  6235. NewSize := S_BL;
  6236. { Will implicitly zero-extend to 64-bit }
  6237. setsubreg(SecondReg, R_SUBD);
  6238. end;
  6239. {$endif x86_64}
  6240. else
  6241. InternalError(2022101301);
  6242. end;
  6243. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6244. { Inserting it right before p will guarantee that the flags are also tracked }
  6245. Asml.InsertBefore(hp5, p);
  6246. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6247. hp_pos := hp5;
  6248. hp_allocstart := hp4;
  6249. end
  6250. else
  6251. begin
  6252. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6253. { Inserting it right before p will guarantee that the flags are also tracked }
  6254. Asml.InsertBefore(hp5, p);
  6255. hp_pos := p;
  6256. hp_allocstart := hp5;
  6257. end;
  6258. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6259. end;
  6260. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6261. taicpu(hp4).condition := taicpu(p).condition;
  6262. asml.InsertBefore(hp4, hp_pos);
  6263. if taicpu(hp3).is_jmp then
  6264. begin
  6265. JumpLoc.decrefs;
  6266. MakeUnconditional(taicpu(p));
  6267. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6268. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6269. end
  6270. else
  6271. ConvertJumpToRET(p, hp3);
  6272. if SecondReg <> NR_NO then
  6273. { Ensure the destination register is allocated over this region }
  6274. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6275. if (JumpLoc.getrefs = 0) then
  6276. RemoveDeadCodeAfterJump(hp3);
  6277. Result:=true;
  6278. exit;
  6279. end;
  6280. end;
  6281. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6282. var
  6283. hp1, hp2: tai;
  6284. ActiveReg: TRegister;
  6285. OldOffset: asizeint;
  6286. ThisConst: TCGInt;
  6287. function RegDeallocated: Boolean;
  6288. begin
  6289. TransferUsedRegs(TmpUsedRegs);
  6290. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6291. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6292. end;
  6293. begin
  6294. Result:=false;
  6295. hp1 := nil;
  6296. { replace
  6297. subX const,%reg1
  6298. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6299. dealloc %reg1
  6300. by
  6301. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6302. }
  6303. if MatchOpType(taicpu(p),top_const,top_reg) then
  6304. begin
  6305. ActiveReg := taicpu(p).oper[1]^.reg;
  6306. { Ensures the entire register was updated }
  6307. if (taicpu(p).opsize >= S_L) and
  6308. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6309. MatchInstruction(hp1,A_LEA,[]) and
  6310. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6311. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6312. (
  6313. { Cover the case where the register in the reference is also the destination register }
  6314. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6315. (
  6316. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6317. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6318. RegDeallocated
  6319. )
  6320. ) then
  6321. begin
  6322. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6323. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6324. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6325. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6326. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6327. {$ifdef x86_64}
  6328. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6329. begin
  6330. { Overflow; abort }
  6331. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6332. end
  6333. else
  6334. {$endif x86_64}
  6335. begin
  6336. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6337. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6338. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6339. RemoveCurrentP(p, hp1)
  6340. else
  6341. RemoveCurrentP(p);
  6342. result:=true;
  6343. Exit;
  6344. end;
  6345. end;
  6346. if (
  6347. { Save calling GetNextInstructionUsingReg again }
  6348. Assigned(hp1) or
  6349. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6350. ) and
  6351. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6352. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6353. begin
  6354. if taicpu(hp1).oper[0]^.typ = top_const then
  6355. begin
  6356. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6357. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6358. Result := True;
  6359. { Handle any overflows }
  6360. case taicpu(p).opsize of
  6361. S_B:
  6362. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6363. S_W:
  6364. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6365. S_L:
  6366. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6367. {$ifdef x86_64}
  6368. S_Q:
  6369. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6370. { Overflow; abort }
  6371. Result := False
  6372. else
  6373. taicpu(p).oper[0]^.val := ThisConst;
  6374. {$endif x86_64}
  6375. else
  6376. InternalError(2021102611);
  6377. end;
  6378. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6379. if Result then
  6380. begin
  6381. if (taicpu(p).oper[0]^.val < 0) and
  6382. (
  6383. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6384. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6385. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6386. ) then
  6387. begin
  6388. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6389. taicpu(p).opcode := A_SUB;
  6390. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6391. end
  6392. else
  6393. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6394. RemoveInstruction(hp1);
  6395. end;
  6396. end
  6397. else
  6398. begin
  6399. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6400. TransferUsedRegs(TmpUsedRegs);
  6401. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6402. hp2 := p;
  6403. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6404. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6405. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6406. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6407. begin
  6408. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6409. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6410. Asml.Remove(p);
  6411. Asml.InsertAfter(p, hp1);
  6412. p := hp1;
  6413. Result := True;
  6414. Exit;
  6415. end;
  6416. end;
  6417. end;
  6418. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6419. { * change "sub/add const1, reg" or "dec reg" followed by
  6420. "sub const2, reg" to one "sub ..., reg" }
  6421. {$ifdef i386}
  6422. if (taicpu(p).oper[0]^.val = 2) and
  6423. (ActiveReg = NR_ESP) and
  6424. { Don't do the sub/push optimization if the sub }
  6425. { comes from setting up the stack frame (JM) }
  6426. (not(GetLastInstruction(p,hp1)) or
  6427. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6428. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6429. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6430. begin
  6431. hp1 := tai(p.next);
  6432. while Assigned(hp1) and
  6433. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6434. not RegReadByInstruction(NR_ESP,hp1) and
  6435. not RegModifiedByInstruction(NR_ESP,hp1) do
  6436. hp1 := tai(hp1.next);
  6437. if Assigned(hp1) and
  6438. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6439. begin
  6440. taicpu(hp1).changeopsize(S_L);
  6441. if taicpu(hp1).oper[0]^.typ=top_reg then
  6442. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6443. hp1 := tai(p.next);
  6444. RemoveCurrentp(p, hp1);
  6445. Result:=true;
  6446. exit;
  6447. end;
  6448. end;
  6449. {$endif i386}
  6450. if DoArithCombineOpt(p) then
  6451. Result:=true;
  6452. end;
  6453. end;
  6454. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6455. var
  6456. TmpBool1,TmpBool2 : Boolean;
  6457. tmpref : treference;
  6458. hp1,hp2: tai;
  6459. mask, shiftval: tcgint;
  6460. begin
  6461. Result:=false;
  6462. { All these optimisations work on "shl/sal const,%reg" }
  6463. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6464. Exit;
  6465. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6466. (taicpu(p).oper[0]^.val <= 3) then
  6467. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6468. begin
  6469. { should we check the next instruction? }
  6470. TmpBool1 := True;
  6471. { have we found an add/sub which could be
  6472. integrated in the lea? }
  6473. TmpBool2 := False;
  6474. reference_reset(tmpref,2,[]);
  6475. TmpRef.index := taicpu(p).oper[1]^.reg;
  6476. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6477. while TmpBool1 and
  6478. GetNextInstruction(p, hp1) and
  6479. (tai(hp1).typ = ait_instruction) and
  6480. ((((taicpu(hp1).opcode = A_ADD) or
  6481. (taicpu(hp1).opcode = A_SUB)) and
  6482. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6483. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6484. (((taicpu(hp1).opcode = A_INC) or
  6485. (taicpu(hp1).opcode = A_DEC)) and
  6486. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6487. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6488. ((taicpu(hp1).opcode = A_LEA) and
  6489. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6490. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6491. (not GetNextInstruction(hp1,hp2) or
  6492. not instrReadsFlags(hp2)) Do
  6493. begin
  6494. TmpBool1 := False;
  6495. if taicpu(hp1).opcode=A_LEA then
  6496. begin
  6497. if (TmpRef.base = NR_NO) and
  6498. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6499. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6500. { Segment register isn't a concern here }
  6501. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6502. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6503. begin
  6504. TmpBool1 := True;
  6505. TmpBool2 := True;
  6506. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6507. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6508. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6509. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6510. RemoveInstruction(hp1);
  6511. end
  6512. end
  6513. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6514. begin
  6515. TmpBool1 := True;
  6516. TmpBool2 := True;
  6517. case taicpu(hp1).opcode of
  6518. A_ADD:
  6519. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6520. A_SUB:
  6521. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6522. else
  6523. internalerror(2019050536);
  6524. end;
  6525. RemoveInstruction(hp1);
  6526. end
  6527. else
  6528. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6529. (((taicpu(hp1).opcode = A_ADD) and
  6530. (TmpRef.base = NR_NO)) or
  6531. (taicpu(hp1).opcode = A_INC) or
  6532. (taicpu(hp1).opcode = A_DEC)) then
  6533. begin
  6534. TmpBool1 := True;
  6535. TmpBool2 := True;
  6536. case taicpu(hp1).opcode of
  6537. A_ADD:
  6538. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6539. A_INC:
  6540. inc(TmpRef.offset);
  6541. A_DEC:
  6542. dec(TmpRef.offset);
  6543. else
  6544. internalerror(2019050535);
  6545. end;
  6546. RemoveInstruction(hp1);
  6547. end;
  6548. end;
  6549. if TmpBool2
  6550. {$ifndef x86_64}
  6551. or
  6552. ((current_settings.optimizecputype < cpu_Pentium2) and
  6553. (taicpu(p).oper[0]^.val <= 3) and
  6554. not(cs_opt_size in current_settings.optimizerswitches))
  6555. {$endif x86_64}
  6556. then
  6557. begin
  6558. if not(TmpBool2) and
  6559. (taicpu(p).oper[0]^.val=1) then
  6560. begin
  6561. taicpu(p).opcode := A_ADD;
  6562. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6563. end
  6564. else
  6565. begin
  6566. taicpu(p).opcode := A_LEA;
  6567. taicpu(p).loadref(0, TmpRef);
  6568. end;
  6569. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6570. Result := True;
  6571. end;
  6572. end
  6573. {$ifndef x86_64}
  6574. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6575. begin
  6576. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6577. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6578. (unlike shl, which is only Tairable in the U pipe) }
  6579. if taicpu(p).oper[0]^.val=1 then
  6580. begin
  6581. taicpu(p).opcode := A_ADD;
  6582. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6583. Result := True;
  6584. end
  6585. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6586. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6587. else if (taicpu(p).opsize = S_L) and
  6588. (taicpu(p).oper[0]^.val<= 3) then
  6589. begin
  6590. reference_reset(tmpref,2,[]);
  6591. TmpRef.index := taicpu(p).oper[1]^.reg;
  6592. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6593. taicpu(p).opcode := A_LEA;
  6594. taicpu(p).loadref(0, TmpRef);
  6595. Result := True;
  6596. end;
  6597. end
  6598. {$endif x86_64}
  6599. else if
  6600. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6601. (
  6602. (
  6603. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6604. SetAndTest(hp1, hp2)
  6605. {$ifdef x86_64}
  6606. ) or
  6607. (
  6608. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6609. GetNextInstruction(hp1, hp2) and
  6610. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6611. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6612. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6613. {$endif x86_64}
  6614. )
  6615. ) and
  6616. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6617. begin
  6618. { Change:
  6619. shl x, %reg1
  6620. mov -(1<<x), %reg2
  6621. and %reg2, %reg1
  6622. Or:
  6623. shl x, %reg1
  6624. and -(1<<x), %reg1
  6625. To just:
  6626. shl x, %reg1
  6627. Since the and operation only zeroes bits that are already zero from the shl operation
  6628. }
  6629. case taicpu(p).oper[0]^.val of
  6630. 8:
  6631. mask:=$FFFFFFFFFFFFFF00;
  6632. 16:
  6633. mask:=$FFFFFFFFFFFF0000;
  6634. 32:
  6635. mask:=$FFFFFFFF00000000;
  6636. 63:
  6637. { Constant pre-calculated to prevent overflow errors with Int64 }
  6638. mask:=$8000000000000000;
  6639. else
  6640. begin
  6641. if taicpu(p).oper[0]^.val >= 64 then
  6642. { Shouldn't happen realistically, since the register
  6643. is guaranteed to be set to zero at this point }
  6644. mask := 0
  6645. else
  6646. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6647. end;
  6648. end;
  6649. if taicpu(hp1).oper[0]^.val = mask then
  6650. begin
  6651. { Everything checks out, perform the optimisation, as long as
  6652. the FLAGS register isn't being used}
  6653. TransferUsedRegs(TmpUsedRegs);
  6654. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6655. {$ifdef x86_64}
  6656. if (hp1 <> hp2) then
  6657. begin
  6658. { "shl/mov/and" version }
  6659. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6660. { Don't do the optimisation if the FLAGS register is in use }
  6661. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6662. begin
  6663. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6664. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6665. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6666. begin
  6667. RemoveInstruction(hp1);
  6668. Result := True;
  6669. end;
  6670. { Only set Result to True if the 'mov' instruction was removed }
  6671. RemoveInstruction(hp2);
  6672. end;
  6673. end
  6674. else
  6675. {$endif x86_64}
  6676. begin
  6677. { "shl/and" version }
  6678. { Don't do the optimisation if the FLAGS register is in use }
  6679. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6680. begin
  6681. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6682. RemoveInstruction(hp1);
  6683. Result := True;
  6684. end;
  6685. end;
  6686. Exit;
  6687. end
  6688. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6689. begin
  6690. { Even if the mask doesn't allow for its removal, we might be
  6691. able to optimise the mask for the "shl/and" version, which
  6692. may permit other peephole optimisations }
  6693. {$ifdef DEBUG_AOPTCPU}
  6694. mask := taicpu(hp1).oper[0]^.val and mask;
  6695. if taicpu(hp1).oper[0]^.val <> mask then
  6696. begin
  6697. DebugMsg(
  6698. SPeepholeOptimization +
  6699. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6700. ' to $' + debug_tostr(mask) +
  6701. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6702. taicpu(hp1).oper[0]^.val := mask;
  6703. end;
  6704. {$else DEBUG_AOPTCPU}
  6705. { If debugging is off, just set the operand even if it's the same }
  6706. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6707. {$endif DEBUG_AOPTCPU}
  6708. end;
  6709. end;
  6710. {
  6711. change
  6712. shl/sal const,reg
  6713. <op> ...(...,reg,1),...
  6714. into
  6715. <op> ...(...,reg,1 shl const),...
  6716. if const in 1..3
  6717. }
  6718. if MatchOpType(taicpu(p), top_const, top_reg) and
  6719. (taicpu(p).oper[0]^.val in [1..3]) and
  6720. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6721. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6722. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6723. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6724. MatchOpType(taicpu(hp1),top_ref))
  6725. ) and
  6726. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6727. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6728. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6729. begin
  6730. TransferUsedRegs(TmpUsedRegs);
  6731. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6732. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6733. begin
  6734. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6735. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6736. RemoveCurrentP(p);
  6737. Result:=true;
  6738. exit;
  6739. end;
  6740. end;
  6741. if MatchOpType(taicpu(p), top_const, top_reg) and
  6742. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6743. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6744. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6745. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6746. begin
  6747. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6748. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6749. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6750. {$ifdef x86_64}
  6751. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6752. {$endif x86_64}
  6753. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6754. begin
  6755. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6756. taicpu(hp1).opcode:=A_MOV;
  6757. taicpu(hp1).oper[0]^.val:=0;
  6758. end
  6759. else
  6760. begin
  6761. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6762. taicpu(hp1).oper[0]^.val:=shiftval;
  6763. end;
  6764. RemoveCurrentP(p);
  6765. Result:=true;
  6766. exit;
  6767. end;
  6768. end;
  6769. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6770. begin
  6771. case shr_size of
  6772. S_B:
  6773. { No valid combinations }
  6774. Result := False;
  6775. S_W:
  6776. Result := (Shift >= 8) and (movz_size = S_BW);
  6777. S_L:
  6778. Result :=
  6779. (Shift >= 24) { Any opsize is valid for this shift } or
  6780. ((Shift >= 16) and (movz_size = S_WL));
  6781. {$ifdef x86_64}
  6782. S_Q:
  6783. Result :=
  6784. (Shift >= 56) { Any opsize is valid for this shift } or
  6785. ((Shift >= 48) and (movz_size = S_WL));
  6786. {$endif x86_64}
  6787. else
  6788. InternalError(2022081510);
  6789. end;
  6790. end;
  6791. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6792. var
  6793. hp1, hp2: tai;
  6794. Shift: TCGInt;
  6795. LimitSize: Topsize;
  6796. DoNotMerge: Boolean;
  6797. begin
  6798. Result := False;
  6799. { All these optimisations work on "shr const,%reg" }
  6800. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6801. Exit;
  6802. DoNotMerge := False;
  6803. Shift := taicpu(p).oper[0]^.val;
  6804. LimitSize := taicpu(p).opsize;
  6805. hp1 := p;
  6806. repeat
  6807. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6808. Exit;
  6809. case taicpu(hp1).opcode of
  6810. A_TEST, A_CMP, A_Jcc:
  6811. { Skip over conditional jumps and relevant comparisons }
  6812. Continue;
  6813. A_MOVZX:
  6814. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6815. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6816. begin
  6817. { Since the original register is being read as is, subsequent
  6818. SHRs must not be merged at this point }
  6819. DoNotMerge := True;
  6820. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6821. begin
  6822. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6823. begin
  6824. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6825. taicpu(hp1).opcode := A_MOV;
  6826. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6827. case taicpu(hp1).opsize of
  6828. S_BW:
  6829. taicpu(hp1).opsize := S_W;
  6830. S_BL, S_WL:
  6831. taicpu(hp1).opsize := S_L;
  6832. else
  6833. InternalError(2022081503);
  6834. end;
  6835. { p itself hasn't changed, so no need to set Result to True }
  6836. Include(OptsToCheck, aoc_ForceNewIteration);
  6837. { See if there's anything afterwards that can be
  6838. optimised, since the input register hasn't changed }
  6839. Continue;
  6840. end;
  6841. { NOTE: If the MOVZX instruction reads and writes the same
  6842. register, defer this to the post-peephole optimisation stage }
  6843. Exit;
  6844. end;
  6845. end;
  6846. A_SHL, A_SAL, A_SHR:
  6847. if (taicpu(hp1).opsize <= LimitSize) and
  6848. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6849. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6850. begin
  6851. { Make sure the sizes don't exceed the register size limit
  6852. (measured by the shift value falling below the limit) }
  6853. if taicpu(hp1).opsize < LimitSize then
  6854. LimitSize := taicpu(hp1).opsize;
  6855. if taicpu(hp1).opcode = A_SHR then
  6856. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6857. else
  6858. begin
  6859. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6860. DoNotMerge := True;
  6861. end;
  6862. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6863. Exit;
  6864. { Since we've established that the combined shift is within
  6865. limits, we can actually combine the adjacent SHR
  6866. instructions even if they're different sizes }
  6867. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6868. begin
  6869. hp2 := tai(hp1.Previous);
  6870. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6871. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6872. RemoveInstruction(hp1);
  6873. hp1 := hp2;
  6874. { Though p has changed, only the constant has, and its
  6875. effects can still be detected on the next iteration of
  6876. the repeat..until loop }
  6877. Include(OptsToCheck, aoc_ForceNewIteration);
  6878. end;
  6879. { Move onto the next instruction }
  6880. Continue;
  6881. end;
  6882. else
  6883. ;
  6884. end;
  6885. Break;
  6886. until False;
  6887. end;
  6888. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6889. var
  6890. CurrentRef: TReference;
  6891. FullReg: TRegister;
  6892. hp1, hp2: tai;
  6893. begin
  6894. Result := False;
  6895. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6896. Exit;
  6897. { We assume you've checked if the operand is actually a reference by
  6898. this point. If it isn't, you'll most likely get an access violation }
  6899. CurrentRef := first_mov.oper[1]^.ref^;
  6900. { Memory must be aligned }
  6901. if (CurrentRef.offset mod 4) <> 0 then
  6902. Exit;
  6903. Inc(CurrentRef.offset);
  6904. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6905. if MatchOperand(second_mov.oper[0]^, 0) and
  6906. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6907. GetNextInstruction(second_mov, hp1) and
  6908. (hp1.typ = ait_instruction) and
  6909. (taicpu(hp1).opcode = A_MOV) and
  6910. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6911. (taicpu(hp1).oper[0]^.val = 0) then
  6912. begin
  6913. Inc(CurrentRef.offset);
  6914. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6915. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6916. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6917. begin
  6918. case taicpu(hp1).opsize of
  6919. S_B:
  6920. if GetNextInstruction(hp1, hp2) and
  6921. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6922. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6923. (taicpu(hp2).oper[0]^.val = 0) then
  6924. begin
  6925. Inc(CurrentRef.offset);
  6926. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6927. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6928. (taicpu(hp2).opsize = S_B) then
  6929. begin
  6930. RemoveInstruction(hp1);
  6931. RemoveInstruction(hp2);
  6932. first_mov.opsize := S_L;
  6933. if first_mov.oper[0]^.typ = top_reg then
  6934. begin
  6935. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6936. { Reuse second_mov as a MOVZX instruction }
  6937. second_mov.opcode := A_MOVZX;
  6938. second_mov.opsize := S_BL;
  6939. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6940. second_mov.loadreg(1, FullReg);
  6941. first_mov.oper[0]^.reg := FullReg;
  6942. asml.Remove(second_mov);
  6943. asml.InsertBefore(second_mov, first_mov);
  6944. end
  6945. else
  6946. { It's a value }
  6947. begin
  6948. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6949. RemoveInstruction(second_mov);
  6950. end;
  6951. Result := True;
  6952. Exit;
  6953. end;
  6954. end;
  6955. S_W:
  6956. begin
  6957. RemoveInstruction(hp1);
  6958. first_mov.opsize := S_L;
  6959. if first_mov.oper[0]^.typ = top_reg then
  6960. begin
  6961. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6962. { Reuse second_mov as a MOVZX instruction }
  6963. second_mov.opcode := A_MOVZX;
  6964. second_mov.opsize := S_BL;
  6965. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6966. second_mov.loadreg(1, FullReg);
  6967. first_mov.oper[0]^.reg := FullReg;
  6968. asml.Remove(second_mov);
  6969. asml.InsertBefore(second_mov, first_mov);
  6970. end
  6971. else
  6972. { It's a value }
  6973. begin
  6974. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6975. RemoveInstruction(second_mov);
  6976. end;
  6977. Result := True;
  6978. Exit;
  6979. end;
  6980. else
  6981. ;
  6982. end;
  6983. end;
  6984. end;
  6985. end;
  6986. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6987. { returns true if a "continue" should be done after this optimization }
  6988. var
  6989. hp1, hp2, hp3: tai;
  6990. begin
  6991. Result := false;
  6992. hp3 := nil;
  6993. if MatchOpType(taicpu(p),top_ref) and
  6994. GetNextInstruction(p, hp1) and
  6995. (hp1.typ = ait_instruction) and
  6996. (((taicpu(hp1).opcode = A_FLD) and
  6997. (taicpu(p).opcode = A_FSTP)) or
  6998. ((taicpu(p).opcode = A_FISTP) and
  6999. (taicpu(hp1).opcode = A_FILD))) and
  7000. MatchOpType(taicpu(hp1),top_ref) and
  7001. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7002. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7003. begin
  7004. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7005. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7006. GetNextInstruction(hp1, hp2) and
  7007. (((hp2.typ = ait_instruction) and
  7008. IsExitCode(hp2) and
  7009. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7010. not(assigned(current_procinfo.procdef.funcretsym) and
  7011. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7012. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7013. { fstp <temp>
  7014. fld <temp>
  7015. <dealloc> <temp>
  7016. }
  7017. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7018. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7019. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7020. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7021. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7022. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7023. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7024. )
  7025. )
  7026. ) then
  7027. begin
  7028. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7029. RemoveInstruction(hp1);
  7030. RemoveCurrentP(p, hp2);
  7031. { first case: exit code }
  7032. if hp2.typ = ait_instruction then
  7033. RemoveLastDeallocForFuncRes(p);
  7034. Result := true;
  7035. end
  7036. else
  7037. { we can do this only in fast math mode as fstp is rounding ...
  7038. ... still disabled as it breaks the compiler and/or rtl }
  7039. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7040. { ... or if another fstp equal to the first one follows }
  7041. GetNextInstruction(hp1,hp2) and
  7042. (hp2.typ = ait_instruction) and
  7043. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7044. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7045. begin
  7046. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7047. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7048. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7049. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7050. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7051. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7052. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7053. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7054. ) then
  7055. begin
  7056. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7057. RemoveCurrentP(p,hp2);
  7058. RemoveInstruction(hp1);
  7059. Result := true;
  7060. end
  7061. else if { fst can't store an extended/comp value }
  7062. (taicpu(p).opsize <> S_FX) and
  7063. (taicpu(p).opsize <> S_IQ) then
  7064. begin
  7065. if (taicpu(p).opcode = A_FSTP) then
  7066. taicpu(p).opcode := A_FST
  7067. else
  7068. taicpu(p).opcode := A_FIST;
  7069. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7070. RemoveInstruction(hp1);
  7071. Result := true;
  7072. end;
  7073. end;
  7074. end;
  7075. end;
  7076. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7077. var
  7078. hp1, hp2, hp3: tai;
  7079. begin
  7080. result:=false;
  7081. if MatchOpType(taicpu(p),top_reg) and
  7082. GetNextInstruction(p, hp1) and
  7083. (hp1.typ = Ait_Instruction) and
  7084. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7085. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7086. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7087. { change to
  7088. fld reg fxxx reg,st
  7089. fxxxp st, st1 (hp1)
  7090. Remark: non commutative operations must be reversed!
  7091. }
  7092. begin
  7093. case taicpu(hp1).opcode Of
  7094. A_FMULP,A_FADDP,
  7095. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7096. begin
  7097. case taicpu(hp1).opcode Of
  7098. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7099. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7100. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7101. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7102. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7103. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7104. else
  7105. internalerror(2019050534);
  7106. end;
  7107. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7108. taicpu(hp1).oper[1]^.reg := NR_ST;
  7109. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7110. RemoveCurrentP(p, hp1);
  7111. Result:=true;
  7112. exit;
  7113. end;
  7114. else
  7115. ;
  7116. end;
  7117. end
  7118. else
  7119. if MatchOpType(taicpu(p),top_ref) and
  7120. GetNextInstruction(p, hp2) and
  7121. (hp2.typ = Ait_Instruction) and
  7122. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7123. (taicpu(p).opsize in [S_FS, S_FL]) and
  7124. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7125. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7126. if GetLastInstruction(p, hp1) and
  7127. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7128. MatchOpType(taicpu(hp1),top_ref) and
  7129. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7130. if ((taicpu(hp2).opcode = A_FMULP) or
  7131. (taicpu(hp2).opcode = A_FADDP)) then
  7132. { change to
  7133. fld/fst mem1 (hp1) fld/fst mem1
  7134. fld mem1 (p) fadd/
  7135. faddp/ fmul st, st
  7136. fmulp st, st1 (hp2) }
  7137. begin
  7138. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7139. RemoveCurrentP(p, hp1);
  7140. if (taicpu(hp2).opcode = A_FADDP) then
  7141. taicpu(hp2).opcode := A_FADD
  7142. else
  7143. taicpu(hp2).opcode := A_FMUL;
  7144. taicpu(hp2).oper[1]^.reg := NR_ST;
  7145. end
  7146. else
  7147. { change to
  7148. fld/fst mem1 (hp1) fld/fst mem1
  7149. fld mem1 (p) fld st
  7150. }
  7151. begin
  7152. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7153. taicpu(p).changeopsize(S_FL);
  7154. taicpu(p).loadreg(0,NR_ST);
  7155. end
  7156. else
  7157. begin
  7158. case taicpu(hp2).opcode Of
  7159. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7160. { change to
  7161. fld/fst mem1 (hp1) fld/fst mem1
  7162. fld mem2 (p) fxxx mem2
  7163. fxxxp st, st1 (hp2) }
  7164. begin
  7165. case taicpu(hp2).opcode Of
  7166. A_FADDP: taicpu(p).opcode := A_FADD;
  7167. A_FMULP: taicpu(p).opcode := A_FMUL;
  7168. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7169. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7170. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7171. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7172. else
  7173. internalerror(2019050533);
  7174. end;
  7175. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7176. RemoveInstruction(hp2);
  7177. end
  7178. else
  7179. ;
  7180. end
  7181. end
  7182. end;
  7183. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7184. begin
  7185. Result := condition_in(cond1, cond2) or
  7186. { Not strictly subsets due to the actual flags checked, but because we're
  7187. comparing integers, E is a subset of AE and GE and their aliases }
  7188. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7189. end;
  7190. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7191. var
  7192. v: TCGInt;
  7193. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7194. FirstMatch, TempBool: Boolean;
  7195. NewReg: TRegister;
  7196. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7197. begin
  7198. Result:=false;
  7199. { All these optimisations need a next instruction }
  7200. if not GetNextInstruction(p, hp1) then
  7201. Exit;
  7202. true_hp1 := hp1;
  7203. { Search for:
  7204. cmp ###,###
  7205. j(c1) @lbl1
  7206. ...
  7207. @lbl:
  7208. cmp ###,### (same comparison as above)
  7209. j(c2) @lbl2
  7210. If c1 is a subset of c2, change to:
  7211. cmp ###,###
  7212. j(c1) @lbl2
  7213. (@lbl1 may become a dead label as a result)
  7214. }
  7215. { Also handle cases where there are multiple jumps in a row }
  7216. p_jump := hp1;
  7217. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7218. begin
  7219. Prefetch(p_jump.Next);
  7220. if IsJumpToLabel(taicpu(p_jump)) then
  7221. begin
  7222. { Do jump optimisations first in case the condition becomes
  7223. unnecessary }
  7224. TempBool := True;
  7225. if DoJumpOptimizations(p_jump, TempBool) or
  7226. not TempBool then
  7227. begin
  7228. if Assigned(p_jump) then
  7229. begin
  7230. { CollapseZeroDistJump will be set to the label or an align
  7231. before it after the jump if it optimises, whether or not
  7232. the label is live or dead }
  7233. if (p_jump.typ = ait_align) or
  7234. (
  7235. (p_jump.typ = ait_label) and
  7236. not (tai_label(p_jump).labsym.is_used)
  7237. ) then
  7238. GetNextInstruction(p_jump, p_jump);
  7239. end;
  7240. TransferUsedRegs(TmpUsedRegs);
  7241. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7242. if not Assigned(p_jump) or
  7243. (
  7244. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7245. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7246. ) then
  7247. begin
  7248. { No more conditional jumps; conditional statement is no longer required }
  7249. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7250. RemoveCurrentP(p);
  7251. Result := True;
  7252. Exit;
  7253. end;
  7254. hp1 := p_jump;
  7255. Include(OptsToCheck, aoc_ForceNewIteration);
  7256. Continue;
  7257. end;
  7258. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7259. if GetNextInstruction(p_jump, hp2) and
  7260. (
  7261. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7262. not TempBool
  7263. ) then
  7264. begin
  7265. hp1 := p_jump;
  7266. Include(OptsToCheck, aoc_ForceNewIteration);
  7267. Continue;
  7268. end;
  7269. p_label := nil;
  7270. if Assigned(JumpLabel) then
  7271. p_label := getlabelwithsym(JumpLabel);
  7272. if Assigned(p_label) and
  7273. GetNextInstruction(p_label, p_dist) and
  7274. MatchInstruction(p_dist, A_CMP, []) and
  7275. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7276. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7277. GetNextInstruction(p_dist, hp1_dist) and
  7278. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7279. begin
  7280. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7281. if JumpLabel = JumpLabel_dist then
  7282. { This is an infinite loop }
  7283. Exit;
  7284. { Best optimisation when the first condition is a subset (or equal) of the second }
  7285. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7286. begin
  7287. { Any registers used here will already be allocated }
  7288. if Assigned(JumpLabel) then
  7289. JumpLabel.DecRefs;
  7290. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7291. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7292. Include(OptsToCheck, aoc_ForceNewIteration);
  7293. { Don't exit yet. Since p and p_jump haven't actually been
  7294. removed, we can check for more on this iteration }
  7295. end
  7296. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7297. GetNextInstruction(hp1_dist, hp1_label) and
  7298. (hp1_label.typ = ait_label) then
  7299. begin
  7300. JumpLabel_far := tai_label(hp1_label).labsym;
  7301. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7302. { This is an infinite loop }
  7303. Exit;
  7304. if Assigned(JumpLabel_far) then
  7305. begin
  7306. { In this situation, if the first jump branches, the second one will never,
  7307. branch so change the destination label to after the second jump }
  7308. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7309. if Assigned(JumpLabel) then
  7310. JumpLabel.DecRefs;
  7311. JumpLabel_far.IncRefs;
  7312. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7313. Result := True;
  7314. { Don't exit yet. Since p and p_jump haven't actually been
  7315. removed, we can check for more on this iteration }
  7316. Continue;
  7317. end;
  7318. end;
  7319. end;
  7320. end;
  7321. { Search for:
  7322. cmp ###,###
  7323. j(c1) @lbl1
  7324. cmp ###,### (same as first)
  7325. Remove second cmp
  7326. }
  7327. if GetNextInstruction(p_jump, hp2) and
  7328. (
  7329. (
  7330. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7331. (
  7332. (
  7333. MatchOpType(taicpu(p), top_const, top_reg) and
  7334. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7335. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7336. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7337. ) or (
  7338. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7339. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7340. )
  7341. )
  7342. ) or (
  7343. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7344. MatchOperand(taicpu(p).oper[0]^, 0) and
  7345. (taicpu(p).oper[1]^.typ = top_reg) and
  7346. MatchInstruction(hp2, A_TEST, []) and
  7347. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7348. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7349. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7350. )
  7351. ) then
  7352. begin
  7353. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7354. TransferUsedRegs(TmpUsedRegs);
  7355. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7356. RemoveInstruction(hp2);
  7357. Result := True;
  7358. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7359. end
  7360. else
  7361. begin
  7362. { hp2 is the next instruction, so save time and just set p_jump
  7363. to it instead of calling GetNextInstruction below }
  7364. p_jump := hp2;
  7365. Continue;
  7366. end;
  7367. GetNextInstruction(p_jump, p_jump);
  7368. end;
  7369. if (
  7370. { Don't call GetNextInstruction again if we already have it }
  7371. (true_hp1 = p_jump) or
  7372. GetNextInstruction(p, hp1)
  7373. ) and
  7374. MatchInstruction(hp1, A_Jcc, []) and
  7375. IsJumpToLabel(taicpu(hp1)) and
  7376. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7377. GetNextInstruction(hp1, hp2) then
  7378. begin
  7379. {
  7380. cmp x, y (or "cmp y, x")
  7381. je @lbl
  7382. mov x, y
  7383. @lbl:
  7384. (x and y can be constants, registers or references)
  7385. Change to:
  7386. mov x, y (x and y will always be equal in the end)
  7387. @lbl: (may beceome a dead label)
  7388. Also:
  7389. cmp x, y (or "cmp y, x")
  7390. jne @lbl
  7391. mov x, y
  7392. @lbl:
  7393. (x and y can be constants, registers or references)
  7394. Change to:
  7395. Absolutely nothing! (Except @lbl if it's still live)
  7396. }
  7397. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7398. (
  7399. (
  7400. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7401. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7402. ) or (
  7403. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7404. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7405. )
  7406. ) and
  7407. GetNextInstruction(hp2, hp1_label) and
  7408. (hp1_label.typ = ait_label) and
  7409. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7410. begin
  7411. tai_label(hp1_label).labsym.DecRefs;
  7412. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7413. begin
  7414. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7415. RemoveInstruction(hp2);
  7416. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7417. end
  7418. else
  7419. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7420. RemoveInstruction(hp1);
  7421. RemoveCurrentp(p, hp2);
  7422. Result := True;
  7423. Exit;
  7424. end;
  7425. {
  7426. Try to optimise the following:
  7427. cmp $x,### ($x and $y can be registers or constants)
  7428. je @lbl1 (only reference)
  7429. cmp $y,### (### are identical)
  7430. @Lbl:
  7431. sete %reg1
  7432. Change to:
  7433. cmp $x,###
  7434. sete %reg2 (allocate new %reg2)
  7435. cmp $y,###
  7436. sete %reg1
  7437. orb %reg2,%reg1
  7438. (dealloc %reg2)
  7439. This adds an instruction (so don't perform under -Os), but it removes
  7440. a conditional branch.
  7441. }
  7442. if not (cs_opt_size in current_settings.optimizerswitches) and
  7443. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7444. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7445. { The first operand of CMP instructions can only be a register or
  7446. immediate anyway, so no need to check }
  7447. GetNextInstruction(hp2, p_label) and
  7448. (p_label.typ = ait_label) and
  7449. (tai_label(p_label).labsym.getrefs = 1) and
  7450. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7451. GetNextInstruction(p_label, p_dist) and
  7452. MatchInstruction(p_dist, A_SETcc, []) and
  7453. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7454. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7455. begin
  7456. TransferUsedRegs(TmpUsedRegs);
  7457. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7458. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7459. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7460. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7461. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7462. { Get the instruction after the SETcc instruction so we can
  7463. allocate a new register over the entire range }
  7464. GetNextInstruction(p_dist, hp1_dist) then
  7465. begin
  7466. { Register can appear in p if it's not used afterwards, so only
  7467. allocate between hp1 and hp1_dist }
  7468. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7469. if NewReg <> NR_NO then
  7470. begin
  7471. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7472. { Change the jump instruction into a SETcc instruction }
  7473. taicpu(hp1).opcode := A_SETcc;
  7474. taicpu(hp1).opsize := S_B;
  7475. taicpu(hp1).loadreg(0, NewReg);
  7476. { This is now a dead label }
  7477. tai_label(p_label).labsym.decrefs;
  7478. { Prefer adding before the next instruction so the FLAGS
  7479. register is deallicated first }
  7480. AsmL.InsertBefore(
  7481. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7482. hp1_dist
  7483. );
  7484. Result := True;
  7485. { Don't exit yet, as p wasn't changed and hp1, while
  7486. modified, is still intact and might be optimised by the
  7487. SETcc optimisation below }
  7488. end;
  7489. end;
  7490. end;
  7491. end;
  7492. if (taicpu(p).oper[0]^.typ = top_const) and
  7493. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7494. begin
  7495. if (taicpu(p).oper[0]^.val = 0) and
  7496. (taicpu(p).oper[1]^.typ = top_reg) then
  7497. begin
  7498. hp2 := p;
  7499. FirstMatch := True;
  7500. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7501. anything meaningful once it's converted to "test %reg,%reg";
  7502. additionally, some jumps will always (or never) branch, so
  7503. evaluate every jump immediately following the
  7504. comparison, optimising the conditions if possible.
  7505. Similarly with SETcc... those that are always set to 0 or 1
  7506. are changed to MOV instructions }
  7507. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7508. (
  7509. GetNextInstruction(hp2, hp1) and
  7510. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7511. ) do
  7512. begin
  7513. Prefetch(hp1.Next);
  7514. FirstMatch := False;
  7515. case taicpu(hp1).condition of
  7516. C_B, C_C, C_NAE, C_O:
  7517. { For B/NAE:
  7518. Will never branch since an unsigned integer can never be below zero
  7519. For C/O:
  7520. Result cannot overflow because 0 is being subtracted
  7521. }
  7522. begin
  7523. if taicpu(hp1).opcode = A_Jcc then
  7524. begin
  7525. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7526. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7527. RemoveInstruction(hp1);
  7528. { Since hp1 was deleted, hp2 must not be updated }
  7529. Continue;
  7530. end
  7531. else
  7532. begin
  7533. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7534. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7535. taicpu(hp1).opcode := A_MOV;
  7536. taicpu(hp1).ops := 2;
  7537. taicpu(hp1).condition := C_None;
  7538. taicpu(hp1).opsize := S_B;
  7539. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7540. taicpu(hp1).loadconst(0, 0);
  7541. end;
  7542. end;
  7543. C_BE, C_NA:
  7544. begin
  7545. { Will only branch if equal to zero }
  7546. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7547. taicpu(hp1).condition := C_E;
  7548. end;
  7549. C_A, C_NBE:
  7550. begin
  7551. { Will only branch if not equal to zero }
  7552. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7553. taicpu(hp1).condition := C_NE;
  7554. end;
  7555. C_AE, C_NB, C_NC, C_NO:
  7556. begin
  7557. { Will always branch }
  7558. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7559. if taicpu(hp1).opcode = A_Jcc then
  7560. begin
  7561. MakeUnconditional(taicpu(hp1));
  7562. { Any jumps/set that follow will now be dead code }
  7563. RemoveDeadCodeAfterJump(taicpu(hp1));
  7564. Break;
  7565. end
  7566. else
  7567. begin
  7568. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7569. taicpu(hp1).opcode := A_MOV;
  7570. taicpu(hp1).ops := 2;
  7571. taicpu(hp1).condition := C_None;
  7572. taicpu(hp1).opsize := S_B;
  7573. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7574. taicpu(hp1).loadconst(0, 1);
  7575. end;
  7576. end;
  7577. C_None:
  7578. InternalError(2020012201);
  7579. C_P, C_PE, C_NP, C_PO:
  7580. { We can't handle parity checks and they should never be generated
  7581. after a general-purpose CMP (it's used in some floating-point
  7582. comparisons that don't use CMP) }
  7583. InternalError(2020012202);
  7584. else
  7585. { Zero/Equality, Sign, their complements and all of the
  7586. signed comparisons do not need to be converted };
  7587. end;
  7588. hp2 := hp1;
  7589. end;
  7590. { Convert the instruction to a TEST }
  7591. taicpu(p).opcode := A_TEST;
  7592. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7593. Result := True;
  7594. Exit;
  7595. end
  7596. else
  7597. begin
  7598. TransferUsedRegs(TmpUsedRegs);
  7599. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7600. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7601. begin
  7602. if (taicpu(p).oper[0]^.val = 1) and
  7603. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7604. begin
  7605. { Convert; To:
  7606. cmp $1,r/m cmp $0,r/m
  7607. jl @lbl jle @lbl
  7608. (Also do inverted conditions)
  7609. }
  7610. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7611. taicpu(p).oper[0]^.val := 0;
  7612. if taicpu(hp1).condition in [C_L, C_NGE] then
  7613. taicpu(hp1).condition := C_LE
  7614. else
  7615. taicpu(hp1).condition := C_NLE;
  7616. { If the instruction is now "cmp $0,%reg", convert it to a
  7617. TEST (and effectively do the work of the "cmp $0,%reg" in
  7618. the block above)
  7619. }
  7620. if (taicpu(p).oper[1]^.typ = top_reg) then
  7621. begin
  7622. taicpu(p).opcode := A_TEST;
  7623. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7624. end;
  7625. Result := True;
  7626. Exit;
  7627. end
  7628. else if (taicpu(p).oper[1]^.typ = top_reg)
  7629. {$ifdef x86_64}
  7630. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7631. {$endif x86_64}
  7632. then
  7633. begin
  7634. { cmp register,$8000 neg register
  7635. je target --> jo target
  7636. .... only if register is deallocated before jump.}
  7637. case Taicpu(p).opsize of
  7638. S_B: v:=$80;
  7639. S_W: v:=$8000;
  7640. S_L: v:=qword($80000000);
  7641. else
  7642. internalerror(2013112905);
  7643. end;
  7644. if (taicpu(p).oper[0]^.val=v) and
  7645. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7646. begin
  7647. TransferUsedRegs(TmpUsedRegs);
  7648. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7649. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7650. begin
  7651. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7652. Taicpu(p).opcode:=A_NEG;
  7653. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7654. Taicpu(p).clearop(1);
  7655. Taicpu(p).ops:=1;
  7656. if Taicpu(hp1).condition=C_E then
  7657. Taicpu(hp1).condition:=C_O
  7658. else
  7659. Taicpu(hp1).condition:=C_NO;
  7660. Result:=true;
  7661. exit;
  7662. end;
  7663. end;
  7664. end;
  7665. end;
  7666. end;
  7667. end;
  7668. if TrySwapMovCmp(p, hp1) then
  7669. begin
  7670. Result := True;
  7671. Exit;
  7672. end;
  7673. end;
  7674. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7675. var
  7676. hp1: tai;
  7677. begin
  7678. {
  7679. remove the second (v)pxor from
  7680. pxor reg,reg
  7681. ...
  7682. pxor reg,reg
  7683. }
  7684. Result:=false;
  7685. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7686. MatchOpType(taicpu(p),top_reg,top_reg) and
  7687. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7688. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7689. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7690. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7691. begin
  7692. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7693. RemoveInstruction(hp1);
  7694. Result:=true;
  7695. Exit;
  7696. end
  7697. {
  7698. replace
  7699. pxor reg1,reg1
  7700. movapd/s reg1,reg2
  7701. dealloc reg1
  7702. by
  7703. pxor reg2,reg2
  7704. }
  7705. else if GetNextInstruction(p,hp1) and
  7706. { we mix single and double opperations here because we assume that the compiler
  7707. generates vmovapd only after double operations and vmovaps only after single operations }
  7708. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7709. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7710. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7711. (taicpu(p).oper[0]^.typ=top_reg) then
  7712. begin
  7713. TransferUsedRegs(TmpUsedRegs);
  7714. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7715. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7716. begin
  7717. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7718. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7719. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7720. RemoveInstruction(hp1);
  7721. result:=true;
  7722. end;
  7723. end;
  7724. end;
  7725. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7726. var
  7727. hp1: tai;
  7728. begin
  7729. {
  7730. remove the second (v)pxor from
  7731. (v)pxor reg,reg
  7732. ...
  7733. (v)pxor reg,reg
  7734. }
  7735. Result:=false;
  7736. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7737. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7738. begin
  7739. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7740. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7741. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7742. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7743. begin
  7744. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7745. RemoveInstruction(hp1);
  7746. Result:=true;
  7747. Exit;
  7748. end;
  7749. {$ifdef x86_64}
  7750. {
  7751. replace
  7752. vpxor reg1,reg1,reg1
  7753. vmov reg,mem
  7754. by
  7755. movq $0,mem
  7756. }
  7757. if GetNextInstruction(p,hp1) and
  7758. MatchInstruction(hp1,A_VMOVSD,[]) and
  7759. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7760. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7761. begin
  7762. TransferUsedRegs(TmpUsedRegs);
  7763. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7764. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7765. begin
  7766. taicpu(hp1).loadconst(0,0);
  7767. taicpu(hp1).opcode:=A_MOV;
  7768. taicpu(hp1).opsize:=S_Q;
  7769. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7770. RemoveCurrentP(p);
  7771. result:=true;
  7772. Exit;
  7773. end;
  7774. end;
  7775. {$endif x86_64}
  7776. end
  7777. {
  7778. replace
  7779. vpxor reg1,reg1,reg2
  7780. by
  7781. vpxor reg2,reg2,reg2
  7782. to avoid unncessary data dependencies
  7783. }
  7784. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7785. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7786. begin
  7787. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7788. { avoid unncessary data dependency }
  7789. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7790. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7791. result:=true;
  7792. exit;
  7793. end;
  7794. Result:=OptPass1VOP(p);
  7795. end;
  7796. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7797. var
  7798. hp1 : tai;
  7799. begin
  7800. result:=false;
  7801. { replace
  7802. IMul const,%mreg1,%mreg2
  7803. Mov %reg2,%mreg3
  7804. dealloc %mreg3
  7805. by
  7806. Imul const,%mreg1,%mreg23
  7807. }
  7808. if (taicpu(p).ops=3) and
  7809. GetNextInstruction(p,hp1) and
  7810. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7811. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7812. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7813. begin
  7814. TransferUsedRegs(TmpUsedRegs);
  7815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7816. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7817. begin
  7818. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7819. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7820. RemoveInstruction(hp1);
  7821. result:=true;
  7822. end;
  7823. end;
  7824. end;
  7825. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7826. var
  7827. hp1 : tai;
  7828. begin
  7829. result:=false;
  7830. { replace
  7831. IMul %reg0,%reg1,%reg2
  7832. Mov %reg2,%reg3
  7833. dealloc %reg2
  7834. by
  7835. Imul %reg0,%reg1,%reg3
  7836. }
  7837. if GetNextInstruction(p,hp1) and
  7838. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7839. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7840. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7841. begin
  7842. TransferUsedRegs(TmpUsedRegs);
  7843. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7844. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7845. begin
  7846. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7847. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7848. RemoveInstruction(hp1);
  7849. result:=true;
  7850. end;
  7851. end;
  7852. end;
  7853. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7854. var
  7855. hp1: tai;
  7856. begin
  7857. Result:=false;
  7858. { get rid of
  7859. (v)cvtss2sd reg0,<reg1,>reg2
  7860. (v)cvtss2sd reg2,<reg2,>reg0
  7861. }
  7862. if GetNextInstruction(p,hp1) and
  7863. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7864. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7865. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7866. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7867. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7868. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7869. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7870. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7871. )
  7872. ) then
  7873. begin
  7874. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7875. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7876. begin
  7877. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7878. RemoveCurrentP(p);
  7879. RemoveInstruction(hp1);
  7880. end
  7881. else
  7882. begin
  7883. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7884. if taicpu(hp1).opcode=A_CVTSD2SS then
  7885. begin
  7886. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7887. taicpu(p).opcode:=A_MOVAPS;
  7888. end
  7889. else
  7890. begin
  7891. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7892. taicpu(p).opcode:=A_VMOVAPS;
  7893. end;
  7894. taicpu(p).ops:=2;
  7895. RemoveInstruction(hp1);
  7896. end;
  7897. Result:=true;
  7898. Exit;
  7899. end;
  7900. end;
  7901. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7902. var
  7903. hp1, hp2, hp3, hp4, hp5: tai;
  7904. ThisReg: TRegister;
  7905. begin
  7906. Result := False;
  7907. if not GetNextInstruction(p,hp1) then
  7908. Exit;
  7909. {
  7910. convert
  7911. j<c> .L1
  7912. mov 1,reg
  7913. jmp .L2
  7914. .L1
  7915. mov 0,reg
  7916. .L2
  7917. into
  7918. mov 0,reg
  7919. set<not(c)> reg
  7920. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7921. would destroy the flag contents
  7922. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7923. executed at the same time as a previous comparison.
  7924. set<not(c)> reg
  7925. movzx reg, reg
  7926. }
  7927. if MatchInstruction(hp1,A_MOV,[]) and
  7928. (taicpu(hp1).oper[0]^.typ = top_const) and
  7929. (
  7930. (
  7931. (taicpu(hp1).oper[1]^.typ = top_reg)
  7932. {$ifdef i386}
  7933. { Under i386, ESI, EDI, EBP and ESP
  7934. don't have an 8-bit representation }
  7935. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7936. {$endif i386}
  7937. ) or (
  7938. {$ifdef i386}
  7939. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7940. {$endif i386}
  7941. (taicpu(hp1).opsize = S_B)
  7942. )
  7943. ) and
  7944. GetNextInstruction(hp1,hp2) and
  7945. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7946. GetNextInstruction(hp2,hp3) and
  7947. (hp3.typ=ait_label) and
  7948. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7949. GetNextInstruction(hp3,hp4) and
  7950. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7951. (taicpu(hp4).oper[0]^.typ = top_const) and
  7952. (
  7953. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7954. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7955. ) and
  7956. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7957. GetNextInstruction(hp4,hp5) and
  7958. (hp5.typ=ait_label) and
  7959. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7960. begin
  7961. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7962. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7963. tai_label(hp3).labsym.DecRefs;
  7964. { If this isn't the only reference to the middle label, we can
  7965. still make a saving - only that the first jump and everything
  7966. that follows will remain. }
  7967. if (tai_label(hp3).labsym.getrefs = 0) then
  7968. begin
  7969. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7970. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7971. else
  7972. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7973. { remove jump, first label and second MOV (also catching any aligns) }
  7974. repeat
  7975. if not GetNextInstruction(hp2, hp3) then
  7976. InternalError(2021040810);
  7977. RemoveInstruction(hp2);
  7978. hp2 := hp3;
  7979. until hp2 = hp5;
  7980. { Don't decrement reference count before the removal loop
  7981. above, otherwise GetNextInstruction won't stop on the
  7982. the label }
  7983. tai_label(hp5).labsym.DecRefs;
  7984. end
  7985. else
  7986. begin
  7987. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7988. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7989. else
  7990. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7991. end;
  7992. taicpu(p).opcode:=A_SETcc;
  7993. taicpu(p).opsize:=S_B;
  7994. taicpu(p).is_jmp:=False;
  7995. if taicpu(hp1).opsize=S_B then
  7996. begin
  7997. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7998. if taicpu(hp1).oper[1]^.typ = top_reg then
  7999. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8000. RemoveInstruction(hp1);
  8001. end
  8002. else
  8003. begin
  8004. { Will be a register because the size can't be S_B otherwise }
  8005. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8006. taicpu(p).loadreg(0, ThisReg);
  8007. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8008. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8009. begin
  8010. case taicpu(hp1).opsize of
  8011. S_W:
  8012. taicpu(hp1).opsize := S_BW;
  8013. S_L:
  8014. taicpu(hp1).opsize := S_BL;
  8015. {$ifdef x86_64}
  8016. S_Q:
  8017. begin
  8018. taicpu(hp1).opsize := S_BL;
  8019. { Change the destination register to 32-bit }
  8020. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8021. end;
  8022. {$endif x86_64}
  8023. else
  8024. InternalError(2021040820);
  8025. end;
  8026. taicpu(hp1).opcode := A_MOVZX;
  8027. taicpu(hp1).loadreg(0, ThisReg);
  8028. end
  8029. else
  8030. begin
  8031. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8032. { hp1 is already a MOV instruction with the correct register }
  8033. taicpu(hp1).loadconst(0, 0);
  8034. { Inserting it right before p will guarantee that the flags are also tracked }
  8035. asml.Remove(hp1);
  8036. asml.InsertBefore(hp1, p);
  8037. end;
  8038. end;
  8039. Result:=true;
  8040. exit;
  8041. end
  8042. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8043. Result := TryJccStcClcOpt(p, hp1)
  8044. else if (hp1.typ = ait_label) then
  8045. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8046. end;
  8047. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8048. var
  8049. hp1, hp2, hp3: tai;
  8050. SourceRef, TargetRef: TReference;
  8051. CurrentReg: TRegister;
  8052. begin
  8053. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8054. if not UseAVX then
  8055. InternalError(2021100501);
  8056. Result := False;
  8057. { Look for the following to simplify:
  8058. vmovdqa/u x(mem1), %xmmreg
  8059. vmovdqa/u %xmmreg, y(mem2)
  8060. vmovdqa/u x+16(mem1), %xmmreg
  8061. vmovdqa/u %xmmreg, y+16(mem2)
  8062. Change to:
  8063. vmovdqa/u x(mem1), %ymmreg
  8064. vmovdqa/u %ymmreg, y(mem2)
  8065. vpxor %ymmreg, %ymmreg, %ymmreg
  8066. ( The VPXOR instruction is to zero the upper half, thus removing the
  8067. need to call the potentially expensive VZEROUPPER instruction. Other
  8068. peephole optimisations can remove VPXOR if it's unnecessary )
  8069. }
  8070. TransferUsedRegs(TmpUsedRegs);
  8071. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8072. { NOTE: In the optimisations below, if the references dictate that an
  8073. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8074. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8075. if (taicpu(p).opsize = S_XMM) and
  8076. MatchOpType(taicpu(p), top_ref, top_reg) and
  8077. GetNextInstruction(p, hp1) and
  8078. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8079. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8080. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8081. begin
  8082. SourceRef := taicpu(p).oper[0]^.ref^;
  8083. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8084. if GetNextInstruction(hp1, hp2) and
  8085. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8086. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8087. begin
  8088. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8089. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8090. Inc(SourceRef.offset, 16);
  8091. { Reuse the register in the first block move }
  8092. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8093. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8094. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8095. begin
  8096. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8097. Inc(TargetRef.offset, 16);
  8098. if GetNextInstruction(hp2, hp3) and
  8099. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8100. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8101. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8102. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8103. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8104. begin
  8105. { Update the register tracking to the new size }
  8106. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8107. { Remember that the offsets are 16 ahead }
  8108. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8109. if not (
  8110. ((SourceRef.offset mod 32) = 16) and
  8111. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8112. ) then
  8113. taicpu(p).opcode := A_VMOVDQU;
  8114. taicpu(p).opsize := S_YMM;
  8115. taicpu(p).oper[1]^.reg := CurrentReg;
  8116. if not (
  8117. ((TargetRef.offset mod 32) = 16) and
  8118. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8119. ) then
  8120. taicpu(hp1).opcode := A_VMOVDQU;
  8121. taicpu(hp1).opsize := S_YMM;
  8122. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8123. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8124. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8125. if (pi_uses_ymm in current_procinfo.flags) then
  8126. RemoveInstruction(hp2)
  8127. else
  8128. begin
  8129. taicpu(hp2).opcode := A_VPXOR;
  8130. taicpu(hp2).opsize := S_YMM;
  8131. taicpu(hp2).loadreg(0, CurrentReg);
  8132. taicpu(hp2).loadreg(1, CurrentReg);
  8133. taicpu(hp2).loadreg(2, CurrentReg);
  8134. taicpu(hp2).ops := 3;
  8135. end;
  8136. RemoveInstruction(hp3);
  8137. Result := True;
  8138. Exit;
  8139. end;
  8140. end
  8141. else
  8142. begin
  8143. { See if the next references are 16 less rather than 16 greater }
  8144. Dec(SourceRef.offset, 32); { -16 the other way }
  8145. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8146. begin
  8147. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8148. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8149. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8150. GetNextInstruction(hp2, hp3) and
  8151. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8152. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8153. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8154. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8155. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8156. begin
  8157. { Update the register tracking to the new size }
  8158. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8159. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8160. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8161. if not(
  8162. ((SourceRef.offset mod 32) = 0) and
  8163. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8164. ) then
  8165. taicpu(hp2).opcode := A_VMOVDQU;
  8166. taicpu(hp2).opsize := S_YMM;
  8167. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8168. if not (
  8169. ((TargetRef.offset mod 32) = 0) and
  8170. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8171. ) then
  8172. taicpu(hp3).opcode := A_VMOVDQU;
  8173. taicpu(hp3).opsize := S_YMM;
  8174. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8175. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8176. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8177. if (pi_uses_ymm in current_procinfo.flags) then
  8178. RemoveInstruction(hp1)
  8179. else
  8180. begin
  8181. taicpu(hp1).opcode := A_VPXOR;
  8182. taicpu(hp1).opsize := S_YMM;
  8183. taicpu(hp1).loadreg(0, CurrentReg);
  8184. taicpu(hp1).loadreg(1, CurrentReg);
  8185. taicpu(hp1).loadreg(2, CurrentReg);
  8186. taicpu(hp1).ops := 3;
  8187. Asml.Remove(hp1);
  8188. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8189. end;
  8190. RemoveCurrentP(p, hp2);
  8191. Result := True;
  8192. Exit;
  8193. end;
  8194. end;
  8195. end;
  8196. end;
  8197. end;
  8198. end;
  8199. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8200. var
  8201. hp2, hp3, first_assignment: tai;
  8202. IncCount, OperIdx: Integer;
  8203. OrigLabel: TAsmLabel;
  8204. begin
  8205. Count := 0;
  8206. Result := False;
  8207. first_assignment := nil;
  8208. if (LoopCount >= 20) then
  8209. begin
  8210. { Guard against infinite loops }
  8211. Exit;
  8212. end;
  8213. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8214. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8215. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8216. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8217. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8218. Exit;
  8219. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8220. {
  8221. change
  8222. jmp .L1
  8223. ...
  8224. .L1:
  8225. mov ##, ## ( multiple movs possible )
  8226. jmp/ret
  8227. into
  8228. mov ##, ##
  8229. jmp/ret
  8230. }
  8231. if not Assigned(hp1) then
  8232. begin
  8233. hp1 := GetLabelWithSym(OrigLabel);
  8234. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8235. Exit;
  8236. end;
  8237. hp2 := hp1;
  8238. while Assigned(hp2) do
  8239. begin
  8240. if Assigned(hp2) and (hp2.typ = ait_label) then
  8241. SkipLabels(hp2,hp2);
  8242. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8243. Break;
  8244. case taicpu(hp2).opcode of
  8245. A_MOVSD:
  8246. begin
  8247. if taicpu(hp2).ops = 0 then
  8248. { Wrong MOVSD }
  8249. Break;
  8250. Inc(Count);
  8251. if Count >= 5 then
  8252. { Too many to be worthwhile }
  8253. Break;
  8254. GetNextInstruction(hp2, hp2);
  8255. Continue;
  8256. end;
  8257. A_MOV,
  8258. A_MOVD,
  8259. A_MOVQ,
  8260. A_MOVSX,
  8261. {$ifdef x86_64}
  8262. A_MOVSXD,
  8263. {$endif x86_64}
  8264. A_MOVZX,
  8265. A_MOVAPS,
  8266. A_MOVUPS,
  8267. A_MOVSS,
  8268. A_MOVAPD,
  8269. A_MOVUPD,
  8270. A_MOVDQA,
  8271. A_MOVDQU,
  8272. A_VMOVSS,
  8273. A_VMOVAPS,
  8274. A_VMOVUPS,
  8275. A_VMOVSD,
  8276. A_VMOVAPD,
  8277. A_VMOVUPD,
  8278. A_VMOVDQA,
  8279. A_VMOVDQU:
  8280. begin
  8281. Inc(Count);
  8282. if Count >= 5 then
  8283. { Too many to be worthwhile }
  8284. Break;
  8285. GetNextInstruction(hp2, hp2);
  8286. Continue;
  8287. end;
  8288. A_JMP:
  8289. begin
  8290. { Guard against infinite loops }
  8291. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8292. Exit;
  8293. { Analyse this jump first in case it also duplicates assignments }
  8294. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8295. begin
  8296. { Something did change! }
  8297. Result := True;
  8298. Inc(Count, IncCount);
  8299. if Count >= 5 then
  8300. begin
  8301. { Too many to be worthwhile }
  8302. Exit;
  8303. end;
  8304. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8305. Break;
  8306. end;
  8307. Result := True;
  8308. Break;
  8309. end;
  8310. A_RET:
  8311. begin
  8312. Result := True;
  8313. Break;
  8314. end;
  8315. else
  8316. Break;
  8317. end;
  8318. end;
  8319. if Result then
  8320. begin
  8321. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8322. if Count = 0 then
  8323. begin
  8324. Result := False;
  8325. Exit;
  8326. end;
  8327. hp3 := p;
  8328. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8329. while True do
  8330. begin
  8331. if Assigned(hp1) and (hp1.typ = ait_label) then
  8332. SkipLabels(hp1,hp1);
  8333. if (hp1.typ <> ait_instruction) then
  8334. InternalError(2021040720);
  8335. case taicpu(hp1).opcode of
  8336. A_JMP:
  8337. begin
  8338. { Change the original jump to the new destination }
  8339. OrigLabel.decrefs;
  8340. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8341. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8342. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8343. if not Assigned(first_assignment) then
  8344. InternalError(2021040810)
  8345. else
  8346. p := first_assignment;
  8347. Exit;
  8348. end;
  8349. A_RET:
  8350. begin
  8351. { Now change the jump into a RET instruction }
  8352. ConvertJumpToRET(p, hp1);
  8353. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8354. if not Assigned(first_assignment) then
  8355. InternalError(2021040811)
  8356. else
  8357. p := first_assignment;
  8358. Exit;
  8359. end;
  8360. else
  8361. begin
  8362. { Duplicate the MOV instruction }
  8363. hp3:=tai(hp1.getcopy);
  8364. if first_assignment = nil then
  8365. first_assignment := hp3;
  8366. asml.InsertBefore(hp3, p);
  8367. { Make sure the compiler knows about any final registers written here }
  8368. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8369. with taicpu(hp3).oper[OperIdx]^ do
  8370. begin
  8371. case typ of
  8372. top_ref:
  8373. begin
  8374. if (ref^.base <> NR_NO) and
  8375. (getsupreg(ref^.base) <> RS_ESP) and
  8376. (getsupreg(ref^.base) <> RS_EBP)
  8377. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8378. then
  8379. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8380. if (ref^.index <> NR_NO) and
  8381. (getsupreg(ref^.index) <> RS_ESP) and
  8382. (getsupreg(ref^.index) <> RS_EBP)
  8383. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8384. (ref^.index <> ref^.base) then
  8385. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8386. end;
  8387. top_reg:
  8388. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8389. else
  8390. ;
  8391. end;
  8392. end;
  8393. end;
  8394. end;
  8395. if not GetNextInstruction(hp1, hp1) then
  8396. { Should have dropped out earlier }
  8397. InternalError(2021040710);
  8398. end;
  8399. end;
  8400. end;
  8401. const
  8402. WriteOp: array[0..3] of set of TInsChange = (
  8403. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8404. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8405. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8406. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8407. RegWriteFlags: array[0..7] of set of TInsChange = (
  8408. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8409. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8410. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8411. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8412. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8413. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8414. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8415. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8416. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8417. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8418. var
  8419. hp2: tai;
  8420. X: Integer;
  8421. begin
  8422. { If we have something like:
  8423. op ###,###
  8424. mov ###,###
  8425. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8426. interfere in regards to what they write to.
  8427. NOTE: p must be a 2-operand instruction
  8428. }
  8429. Result := False;
  8430. if (hp1.typ <> ait_instruction) or
  8431. taicpu(hp1).is_jmp or
  8432. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8433. Exit;
  8434. { NOP is a pipeline fence, likely marking the beginning of the function
  8435. epilogue, so drop out. Similarly, drop out if POP or RET are
  8436. encountered }
  8437. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8438. Exit;
  8439. if (taicpu(hp1).opcode = A_MOVSD) and
  8440. (taicpu(hp1).ops = 0) then
  8441. { Wrong MOVSD }
  8442. Exit;
  8443. { Check for writes to specific registers first }
  8444. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8445. for X := 0 to 7 do
  8446. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8447. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8448. Exit;
  8449. for X := 0 to taicpu(hp1).ops - 1 do
  8450. begin
  8451. { Check to see if this operand writes to something }
  8452. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8453. { And matches something in the CMP/TEST instruction }
  8454. (
  8455. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8456. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8457. (
  8458. { If it's a register, make sure the register written to doesn't
  8459. appear in the cmp instruction as part of a reference }
  8460. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8461. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8462. )
  8463. ) then
  8464. Exit;
  8465. end;
  8466. { Check p to make sure it doesn't write to something that affects hp1 }
  8467. { Check for writes to specific registers first }
  8468. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8469. for X := 0 to 7 do
  8470. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8471. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8472. Exit;
  8473. for X := 0 to taicpu(p).ops - 1 do
  8474. begin
  8475. { Check to see if this operand writes to something }
  8476. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8477. { And matches something in hp1 }
  8478. (taicpu(p).oper[X]^.typ = top_reg) and
  8479. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8480. Exit;
  8481. end;
  8482. { The instruction can be safely moved }
  8483. asml.Remove(hp1);
  8484. { Try to insert after the last instructions where the FLAGS register is not
  8485. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8486. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8487. asml.InsertBefore(hp1, hp2)
  8488. { Failing that, try to insert after the last instructions where the
  8489. FLAGS register is not yet in use }
  8490. else if GetLastInstruction(p, hp2) and
  8491. (
  8492. (hp2.typ <> ait_instruction) or
  8493. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8494. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8495. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8496. ) then
  8497. asml.InsertAfter(hp1, hp2)
  8498. else
  8499. { Note, if p.Previous is nil (even if it should logically never be the
  8500. case), FindRegAllocBackward immediately exits with False and so we
  8501. safely land here (we can't just pass p because FindRegAllocBackward
  8502. immediately exits on an instruction). [Kit] }
  8503. asml.InsertBefore(hp1, p);
  8504. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8505. { We can't trust UsedRegs because we're looking backwards, although we
  8506. know the registers are allocated after p at the very least, so manually
  8507. create tai_regalloc objects if needed }
  8508. for X := 0 to taicpu(hp1).ops - 1 do
  8509. case taicpu(hp1).oper[X]^.typ of
  8510. top_reg:
  8511. begin
  8512. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8513. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8514. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8515. end;
  8516. top_ref:
  8517. begin
  8518. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8519. begin
  8520. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8521. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8522. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8523. end;
  8524. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8525. begin
  8526. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8527. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8528. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8529. end;
  8530. end;
  8531. else
  8532. ;
  8533. end;
  8534. Result := True;
  8535. end;
  8536. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8537. var
  8538. hp2: tai;
  8539. X: Integer;
  8540. begin
  8541. { If we have something like:
  8542. cmp ###,%reg1
  8543. mov 0,%reg2
  8544. And no modified registers are shared, move the instruction to before
  8545. the comparison as this means it can be optimised without worrying
  8546. about the FLAGS register. (CMP/MOV is generated by
  8547. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8548. As long as the second instruction doesn't use the flags or one of the
  8549. registers used by CMP or TEST (also check any references that use the
  8550. registers), then it can be moved prior to the comparison.
  8551. }
  8552. Result := False;
  8553. if not TrySwapMovOp(p, hp1) then
  8554. Exit;
  8555. if taicpu(hp1).opcode = A_LEA then
  8556. { The flags will be overwritten by the CMP/TEST instruction }
  8557. ConvertLEA(taicpu(hp1));
  8558. Result := True;
  8559. { Can we move it one further back? }
  8560. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8561. { Check to see if CMP/TEST is a comparison against zero }
  8562. (
  8563. (
  8564. (taicpu(p).opcode = A_CMP) and
  8565. MatchOperand(taicpu(p).oper[0]^, 0)
  8566. ) or
  8567. (
  8568. (taicpu(p).opcode = A_TEST) and
  8569. (
  8570. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8571. MatchOperand(taicpu(p).oper[0]^, -1)
  8572. )
  8573. )
  8574. ) and
  8575. { These instructions set the zero flag if the result is zero }
  8576. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8577. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8578. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8579. TrySwapMovOp(hp2, hp1);
  8580. end;
  8581. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  8582. var
  8583. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  8584. JumpLabel: TAsmLabel;
  8585. TmpBool: Boolean;
  8586. begin
  8587. Result := False;
  8588. { Look for:
  8589. stc/clc
  8590. j(c) .L1
  8591. ...
  8592. .L1:
  8593. set(n)cb %reg
  8594. (flags deallocated)
  8595. j(c) .L2
  8596. Change to:
  8597. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  8598. j(c) .L2
  8599. }
  8600. p_last := p;
  8601. while GetNextInstruction(p_last, hp1) and
  8602. (hp1.typ = ait_instruction) and
  8603. IsJumpToLabel(taicpu(hp1)) do
  8604. begin
  8605. if DoJumpOptimizations(hp1, TmpBool) then
  8606. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8607. Continue;
  8608. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  8609. if not Assigned(JumpLabel) then
  8610. InternalError(2024012801);
  8611. { Optimise the J(c); stc/clc optimisation first since this will
  8612. get missed if the main optimisation takes place }
  8613. if (taicpu(hp1).opcode = A_JCC) then
  8614. begin
  8615. if GetNextInstruction(hp1, hp2) and
  8616. MatchInstruction(hp2, A_CLC, A_STC, []) and
  8617. TryJccStcClcOpt(hp1, hp2) then
  8618. begin
  8619. Result := True;
  8620. Exit;
  8621. end;
  8622. hp2 := nil; { Suppress compiler warning }
  8623. if (taicpu(hp1).condition in [C_C, C_NC]) and
  8624. { Make sure the flags aren't used again }
  8625. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  8626. begin
  8627. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8628. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  8629. begin
  8630. if (taicpu(p).opcode = A_STC) then
  8631. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  8632. else
  8633. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  8634. MakeUnconditional(taicpu(hp1));
  8635. { Move the jump to after the flag deallocations }
  8636. Asml.Remove(hp1);
  8637. Asml.InsertAfter(hp1, hp2);
  8638. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8639. Result := True;
  8640. Exit;
  8641. end
  8642. else
  8643. begin
  8644. if (taicpu(p).opcode = A_STC) then
  8645. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  8646. else
  8647. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  8648. { In this case, the jump is deterministic in that it will never be taken }
  8649. JumpLabel.DecRefs;
  8650. RemoveInstruction(hp1);
  8651. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  8652. Result := True;
  8653. Exit;
  8654. end;
  8655. end;
  8656. end;
  8657. hp2 := nil; { Suppress compiler warning }
  8658. if
  8659. { Make sure the carry flag doesn't appear in the jump conditions }
  8660. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8661. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  8662. GetNextInstruction(hp2, p_dist) and
  8663. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  8664. (taicpu(p_dist).condition in [C_C, C_NC]) then
  8665. begin
  8666. case taicpu(p_dist).opcode of
  8667. A_Jcc:
  8668. begin
  8669. if DoJumpOptimizations(p_dist, TmpBool) then
  8670. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  8671. Continue;
  8672. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  8673. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  8674. begin
  8675. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  8676. JumpLabel.decrefs;
  8677. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  8678. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8679. Result := True;
  8680. Exit;
  8681. end
  8682. else if GetNextInstruction(p_dist, hp1_dist) and
  8683. (hp1_dist.typ = ait_label) then
  8684. begin
  8685. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  8686. JumpLabel.decrefs;
  8687. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  8688. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  8689. Result := True;
  8690. Exit;
  8691. end;
  8692. end;
  8693. A_SETcc:
  8694. if { Make sure the flags aren't used again }
  8695. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  8696. GetNextInstruction(hp2, hp1_dist) and
  8697. (hp1_dist.typ = ait_instruction) and
  8698. IsJumpToLabel(taicpu(hp1_dist)) and
  8699. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  8700. { This works if hp1_dist or both are regular JMP instructions }
  8701. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  8702. (
  8703. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  8704. { Make sure the register isn't still in use, otherwise it
  8705. may get corrupted (fixes #40659) }
  8706. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  8707. ) then
  8708. begin
  8709. taicpu(p).allocate_oper(2);
  8710. taicpu(p).ops := 2;
  8711. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  8712. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  8713. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  8714. taicpu(p).opcode := A_MOV;
  8715. taicpu(p).opsize := S_B;
  8716. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  8717. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  8718. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  8719. JumpLabel.decrefs;
  8720. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  8721. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  8722. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  8723. (tai_regalloc(hp2).ratype = ra_alloc) then
  8724. begin
  8725. Asml.Remove(hp2);
  8726. Asml.InsertAfter(hp2, p);
  8727. end;
  8728. Result := True;
  8729. Exit;
  8730. end;
  8731. else
  8732. ;
  8733. end;
  8734. end;
  8735. p_last := hp1;
  8736. end;
  8737. end;
  8738. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  8739. var
  8740. hp2, hp3: tai;
  8741. TempBool: Boolean;
  8742. begin
  8743. Result := False;
  8744. {
  8745. j(c) .L1
  8746. stc/clc
  8747. .L1:
  8748. jc/jnc .L2
  8749. (Flags deallocated)
  8750. Change to:
  8751. j)c) .L1
  8752. jmp .L2
  8753. .L1:
  8754. jc/jnc .L2
  8755. Then call DoJumpOptimizations to convert to:
  8756. j(nc) .L2
  8757. .L1: (may become a dead label)
  8758. jc/jnc .L2
  8759. }
  8760. if GetNextInstruction(hp1, hp2) and
  8761. (hp2.typ = ait_label) and
  8762. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  8763. GetNextInstruction(hp2, hp3) and
  8764. MatchInstruction(hp3, A_Jcc, []) and
  8765. (
  8766. (
  8767. (taicpu(hp3).condition = C_C) and
  8768. (taicpu(hp1).opcode = A_STC)
  8769. ) or (
  8770. (taicpu(hp3).condition = C_NC) and
  8771. (taicpu(hp1).opcode = A_CLC)
  8772. )
  8773. ) and
  8774. { Make sure the flags aren't used again }
  8775. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  8776. begin
  8777. taicpu(hp1).allocate_oper(1);
  8778. taicpu(hp1).ops := 1;
  8779. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  8780. taicpu(hp1).opcode := A_JMP;
  8781. taicpu(hp1).is_jmp := True;
  8782. TempBool := True; { Prevent compiler warnings }
  8783. if DoJumpOptimizations(p, TempBool) then
  8784. Result := True
  8785. else
  8786. Include(OptsToCheck, aoc_ForceNewIteration);
  8787. end;
  8788. end;
  8789. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  8790. begin
  8791. { This generally only executes under -O3 and above }
  8792. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  8793. end;
  8794. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  8795. var
  8796. hp1, hp2: tai;
  8797. FoundComparison: Boolean;
  8798. begin
  8799. { Run the pass 1 optimisations as well, since they may have some effect
  8800. after the CMOV blocks are created in OptPass2Jcc }
  8801. Result := False;
  8802. { Result := OptPass1CMOVcc(p);
  8803. if Result then
  8804. Exit;}
  8805. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  8806. and make a slightly inefficent result on branching-type blocks, notably
  8807. when setting a function result then jumping to the function epilogue.
  8808. In this case, change:
  8809. cmov(c) %reg1,%reg2
  8810. j(c) @lbl
  8811. (%reg2 deallocated)
  8812. To:
  8813. mov %reg11,%reg2
  8814. j(c) @lbl
  8815. Note, we can't use GetNextInstructionUsingReg to find the conditional
  8816. jump because if it's not present, we may end up with a jump that's
  8817. completely unrelated.
  8818. }
  8819. hp1 := p;
  8820. while GetNextInstruction(hp1, hp1) and
  8821. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  8822. if (hp1.typ = ait_instruction) and
  8823. (taicpu(hp1).opcode = A_Jcc) and
  8824. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  8825. begin
  8826. TransferUsedRegs(TmpUsedRegs);
  8827. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  8828. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  8829. (
  8830. { See if we can find a more distant instruction that overwrites
  8831. the destination register }
  8832. (cs_opt_level3 in current_settings.optimizerswitches) and
  8833. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8834. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  8835. ) then
  8836. begin
  8837. if (taicpu(p).oper[0]^.typ = top_reg) then
  8838. begin
  8839. { Search backwards to see if the source register is set to a
  8840. constant }
  8841. FoundComparison := False;
  8842. hp1 := p;
  8843. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  8844. begin
  8845. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  8846. begin
  8847. FoundComparison := True;
  8848. Continue;
  8849. end;
  8850. { Once we find the CMP, TEST or similar instruction, we
  8851. have to stop if we find anything other than a MOV }
  8852. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  8853. Break;
  8854. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  8855. { Destination register was modified }
  8856. Break;
  8857. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  8858. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  8859. begin
  8860. { Found a constant! }
  8861. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  8862. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  8863. { The source register is no longer in use }
  8864. RemoveInstruction(hp1);
  8865. Break;
  8866. end;
  8867. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  8868. { Some other instruction has modified the source register }
  8869. Break;
  8870. end;
  8871. end;
  8872. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  8873. taicpu(p).opcode := A_MOV;
  8874. taicpu(p).condition := C_None;
  8875. { Rely on the post peephole stage to put the MOV before the
  8876. CMP/TEST instruction that appears prior }
  8877. Result := True;
  8878. Exit;
  8879. end;
  8880. end;
  8881. end;
  8882. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8883. function IsXCHGAcceptable: Boolean; inline;
  8884. begin
  8885. { Always accept if optimising for size }
  8886. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8887. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8888. than 3, so it becomes a saving compared to three MOVs with two of
  8889. them able to execute simultaneously. [Kit] }
  8890. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8891. end;
  8892. var
  8893. NewRef: TReference;
  8894. hp1, hp2, hp3, hp4: Tai;
  8895. {$ifndef x86_64}
  8896. OperIdx: Integer;
  8897. {$endif x86_64}
  8898. NewInstr : Taicpu;
  8899. NewAligh : Tai_align;
  8900. DestLabel: TAsmLabel;
  8901. TempTracking: TAllUsedRegs;
  8902. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8903. var
  8904. NextInstr: tai;
  8905. begin
  8906. Result := False;
  8907. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8908. if not GetNextInstruction(InputInstr, NextInstr) or
  8909. (
  8910. { The FLAGS register isn't always tracked properly, so do not
  8911. perform this optimisation if a conditional statement follows }
  8912. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8913. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8914. ) then
  8915. begin
  8916. reference_reset(NewRef, 1, []);
  8917. NewRef.base := taicpu(p).oper[0]^.reg;
  8918. NewRef.scalefactor := 1;
  8919. if taicpu(InputInstr).opcode = A_ADD then
  8920. begin
  8921. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8922. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8923. end
  8924. else
  8925. begin
  8926. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8927. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8928. end;
  8929. taicpu(p).opcode := A_LEA;
  8930. taicpu(p).loadref(0, NewRef);
  8931. RemoveInstruction(InputInstr);
  8932. Result := True;
  8933. end;
  8934. end;
  8935. begin
  8936. Result:=false;
  8937. { This optimisation adds an instruction, so only do it for speed }
  8938. if not (cs_opt_size in current_settings.optimizerswitches) and
  8939. MatchOpType(taicpu(p), top_const, top_reg) and
  8940. (taicpu(p).oper[0]^.val = 0) then
  8941. begin
  8942. { To avoid compiler warning }
  8943. DestLabel := nil;
  8944. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8945. InternalError(2021040750);
  8946. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8947. Exit;
  8948. case hp1.typ of
  8949. ait_label:
  8950. begin
  8951. { Change:
  8952. mov $0,%reg mov $0,%reg
  8953. @Lbl1: @Lbl1:
  8954. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8955. je @Lbl2 jne @Lbl2
  8956. To: To:
  8957. mov $0,%reg mov $0,%reg
  8958. jmp @Lbl2 jmp @Lbl3
  8959. (align) (align)
  8960. @Lbl1: @Lbl1:
  8961. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8962. je @Lbl2 je @Lbl2
  8963. @Lbl3: <-- Only if label exists
  8964. (Not if it's optimised for size)
  8965. }
  8966. if not GetNextInstruction(hp1, hp2) then
  8967. Exit;
  8968. if (hp2.typ = ait_instruction) and
  8969. (
  8970. { Register sizes must exactly match }
  8971. (
  8972. (taicpu(hp2).opcode = A_CMP) and
  8973. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8974. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8975. ) or (
  8976. (taicpu(hp2).opcode = A_TEST) and
  8977. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8978. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8979. )
  8980. ) and GetNextInstruction(hp2, hp3) and
  8981. (hp3.typ = ait_instruction) and
  8982. (taicpu(hp3).opcode = A_JCC) and
  8983. (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
  8984. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8985. begin
  8986. { Check condition of jump }
  8987. { Always true? }
  8988. if condition_in(C_E, taicpu(hp3).condition) then
  8989. begin
  8990. { Copy label symbol and obtain matching label entry for the
  8991. conditional jump, as this will be our destination}
  8992. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8993. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8994. Result := True;
  8995. end
  8996. { Always false? }
  8997. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8998. begin
  8999. { This is only worth it if there's a jump to take }
  9000. case hp2.typ of
  9001. ait_instruction:
  9002. begin
  9003. if taicpu(hp2).opcode = A_JMP then
  9004. begin
  9005. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9006. { An unconditional jump follows the conditional jump which will always be false,
  9007. so use this jump's destination for the new jump }
  9008. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9009. Result := True;
  9010. end
  9011. else if taicpu(hp2).opcode = A_JCC then
  9012. begin
  9013. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9014. if condition_in(C_E, taicpu(hp2).condition) then
  9015. begin
  9016. { A second conditional jump follows the conditional jump which will always be false,
  9017. while the second jump is always True, so use this jump's destination for the new jump }
  9018. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9019. Result := True;
  9020. end;
  9021. { Don't risk it if the jump isn't always true (Result remains False) }
  9022. end;
  9023. end;
  9024. else
  9025. { If anything else don't optimise };
  9026. end;
  9027. end;
  9028. if Result then
  9029. begin
  9030. { Just so we have something to insert as a paremeter}
  9031. reference_reset(NewRef, 1, []);
  9032. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9033. { Now actually load the correct parameter (this also
  9034. increases the reference count) }
  9035. NewInstr.loadsymbol(0, DestLabel, 0);
  9036. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9037. begin
  9038. { Get instruction before original label (may not be p under -O3) }
  9039. if not GetLastInstruction(hp1, hp2) then
  9040. { Shouldn't fail here }
  9041. InternalError(2021040701);
  9042. end
  9043. else
  9044. hp2 := p;
  9045. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9046. AsmL.InsertAfter(NewInstr, hp2);
  9047. { Add new alignment field }
  9048. (* AsmL.InsertAfter(
  9049. cai_align.create_max(
  9050. current_settings.alignment.jumpalign,
  9051. current_settings.alignment.jumpalignskipmax
  9052. ),
  9053. NewInstr
  9054. ); *)
  9055. end;
  9056. Exit;
  9057. end;
  9058. end;
  9059. else
  9060. ;
  9061. end;
  9062. end;
  9063. if not GetNextInstruction(p, hp1) then
  9064. Exit;
  9065. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9066. begin
  9067. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9068. begin
  9069. Result := True;
  9070. Exit;
  9071. end;
  9072. { This optimisation is only effective on a second run of Pass 2,
  9073. hence -O3 or above.
  9074. Change:
  9075. mov %reg1,%reg2
  9076. cmp/test (contains %reg1)
  9077. mov x, %reg1
  9078. (another mov or a j(c))
  9079. To:
  9080. mov %reg1,%reg2
  9081. mov x, %reg1
  9082. cmp (%reg1 replaced with %reg2)
  9083. (another mov or a j(c))
  9084. The requirement of an additional MOV or a jump ensures there
  9085. isn't performance loss, since a j(c) will permit macro-fusion
  9086. with the cmp instruction, while another MOV likely means it's
  9087. not all being executed in a single cycle due to parallelisation.
  9088. }
  9089. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9090. MatchOpType(taicpu(p), top_reg, top_reg) and
  9091. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9092. GetNextInstruction(hp1, hp2) and
  9093. MatchInstruction(hp2, A_MOV, []) and
  9094. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9095. { Registers don't have to be the same size in this case }
  9096. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9097. GetNextInstruction(hp2, hp3) and
  9098. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9099. { Make sure the operands in the camparison can be safely replaced }
  9100. (
  9101. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9102. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9103. ) and
  9104. (
  9105. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9106. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9107. ) then
  9108. begin
  9109. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9110. AsmL.Remove(hp2);
  9111. AsmL.InsertAfter(hp2, p);
  9112. Result := True;
  9113. Exit;
  9114. end;
  9115. end;
  9116. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9117. begin
  9118. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9119. further, but we can't just put this jump optimisation in pass 1
  9120. because it tends to perform worse when conditional jumps are
  9121. nearby (e.g. when converting CMOV instructions). [Kit] }
  9122. CopyUsedRegs(TempTracking);
  9123. UpdateUsedRegs(tai(p.Next));
  9124. if OptPass2JMP(hp1) then
  9125. begin
  9126. { Restore register state }
  9127. RestoreUsedRegs(TempTracking);
  9128. ReleaseUsedRegs(TempTracking);
  9129. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9130. OptPass1MOV(p);
  9131. Result := True;
  9132. Exit;
  9133. end;
  9134. { If OptPass2JMP returned False, no optimisations were done to
  9135. the jump and there are no further optimisations that can be done
  9136. to the MOV instruction on this pass other than FuncMov2Func }
  9137. { Restore register state }
  9138. RestoreUsedRegs(TempTracking);
  9139. ReleaseUsedRegs(TempTracking);
  9140. Result := FuncMov2Func(p, hp1);
  9141. Exit;
  9142. end;
  9143. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9144. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9145. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9146. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9147. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9148. begin
  9149. { Change:
  9150. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9151. addl/q $x,%reg2 subl/q $x,%reg2
  9152. To:
  9153. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9154. }
  9155. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9156. { be lazy, checking separately for sub would be slightly better }
  9157. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9158. begin
  9159. TransferUsedRegs(TmpUsedRegs);
  9160. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9161. if TryMovArith2Lea(hp1) then
  9162. begin
  9163. Result := True;
  9164. Exit;
  9165. end
  9166. end
  9167. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9168. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9169. { Same as above, but also adds or subtracts to %reg2 in between.
  9170. It's still valid as long as the flags aren't in use }
  9171. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9172. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9173. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9174. { be lazy, checking separately for sub would be slightly better }
  9175. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9176. begin
  9177. TransferUsedRegs(TmpUsedRegs);
  9178. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9179. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9180. if TryMovArith2Lea(hp2) then
  9181. begin
  9182. Result := True;
  9183. Exit;
  9184. end;
  9185. end;
  9186. end;
  9187. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9188. {$ifdef x86_64}
  9189. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9190. {$else x86_64}
  9191. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9192. {$endif x86_64}
  9193. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9194. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9195. { mov reg1, reg2 mov reg1, reg2
  9196. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9197. begin
  9198. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9199. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9200. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9201. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9202. TransferUsedRegs(TmpUsedRegs);
  9203. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9204. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9205. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9206. then
  9207. begin
  9208. RemoveCurrentP(p, hp1);
  9209. Result:=true;
  9210. end;
  9211. Exit;
  9212. end;
  9213. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9214. IsXCHGAcceptable and
  9215. { XCHG doesn't support 8-bit registers }
  9216. (taicpu(p).opsize <> S_B) and
  9217. MatchInstruction(hp1, A_MOV, []) and
  9218. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9219. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9220. GetNextInstruction(hp1, hp2) and
  9221. MatchInstruction(hp2, A_MOV, []) and
  9222. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9223. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9224. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9225. begin
  9226. { mov %reg1,%reg2
  9227. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9228. mov %reg2,%reg3
  9229. (%reg2 not used afterwards)
  9230. Note that xchg takes 3 cycles to execute, and generally mov's take
  9231. only one cycle apiece, but the first two mov's can be executed in
  9232. parallel, only taking 2 cycles overall. Older processors should
  9233. therefore only optimise for size. [Kit]
  9234. }
  9235. TransferUsedRegs(TmpUsedRegs);
  9236. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9237. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9238. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9239. begin
  9240. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9241. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9242. taicpu(hp1).opcode := A_XCHG;
  9243. RemoveCurrentP(p, hp1);
  9244. RemoveInstruction(hp2);
  9245. Result := True;
  9246. Exit;
  9247. end;
  9248. end;
  9249. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9250. MatchInstruction(hp1, A_SAR, []) then
  9251. begin
  9252. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9253. begin
  9254. { the use of %edx also covers the opsize being S_L }
  9255. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9256. begin
  9257. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9258. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9259. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9260. begin
  9261. { Change:
  9262. movl %eax,%edx
  9263. sarl $31,%edx
  9264. To:
  9265. cltd
  9266. }
  9267. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9268. RemoveInstruction(hp1);
  9269. taicpu(p).opcode := A_CDQ;
  9270. taicpu(p).opsize := S_NO;
  9271. taicpu(p).clearop(1);
  9272. taicpu(p).clearop(0);
  9273. taicpu(p).ops:=0;
  9274. Result := True;
  9275. Exit;
  9276. end
  9277. else if (cs_opt_size in current_settings.optimizerswitches) and
  9278. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9279. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9280. begin
  9281. { Change:
  9282. movl %edx,%eax
  9283. sarl $31,%edx
  9284. To:
  9285. movl %edx,%eax
  9286. cltd
  9287. Note that this creates a dependency between the two instructions,
  9288. so only perform if optimising for size.
  9289. }
  9290. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9291. taicpu(hp1).opcode := A_CDQ;
  9292. taicpu(hp1).opsize := S_NO;
  9293. taicpu(hp1).clearop(1);
  9294. taicpu(hp1).clearop(0);
  9295. taicpu(hp1).ops:=0;
  9296. Include(OptsToCheck, aoc_ForceNewIteration);
  9297. Exit;
  9298. end;
  9299. {$ifndef x86_64}
  9300. end
  9301. { Don't bother if CMOV is supported, because a more optimal
  9302. sequence would have been generated for the Abs() intrinsic }
  9303. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9304. { the use of %eax also covers the opsize being S_L }
  9305. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9306. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9307. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9308. GetNextInstruction(hp1, hp2) and
  9309. MatchInstruction(hp2, A_XOR, [S_L]) and
  9310. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9311. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9312. GetNextInstruction(hp2, hp3) and
  9313. MatchInstruction(hp3, A_SUB, [S_L]) and
  9314. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9315. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9316. begin
  9317. { Change:
  9318. movl %eax,%edx
  9319. sarl $31,%eax
  9320. xorl %eax,%edx
  9321. subl %eax,%edx
  9322. (Instruction that uses %edx)
  9323. (%eax deallocated)
  9324. (%edx deallocated)
  9325. To:
  9326. cltd
  9327. xorl %edx,%eax <-- Note the registers have swapped
  9328. subl %edx,%eax
  9329. (Instruction that uses %eax) <-- %eax rather than %edx
  9330. }
  9331. TransferUsedRegs(TmpUsedRegs);
  9332. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9333. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9334. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9335. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9336. begin
  9337. if GetNextInstruction(hp3, hp4) and
  9338. not RegModifiedByInstruction(NR_EDX, hp4) and
  9339. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9340. begin
  9341. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9342. taicpu(p).opcode := A_CDQ;
  9343. taicpu(p).clearop(1);
  9344. taicpu(p).clearop(0);
  9345. taicpu(p).ops:=0;
  9346. RemoveInstruction(hp1);
  9347. taicpu(hp2).loadreg(0, NR_EDX);
  9348. taicpu(hp2).loadreg(1, NR_EAX);
  9349. taicpu(hp3).loadreg(0, NR_EDX);
  9350. taicpu(hp3).loadreg(1, NR_EAX);
  9351. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9352. { Convert references in the following instruction (hp4) from %edx to %eax }
  9353. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9354. with taicpu(hp4).oper[OperIdx]^ do
  9355. case typ of
  9356. top_reg:
  9357. if getsupreg(reg) = RS_EDX then
  9358. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9359. top_ref:
  9360. begin
  9361. if getsupreg(reg) = RS_EDX then
  9362. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9363. if getsupreg(reg) = RS_EDX then
  9364. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9365. end;
  9366. else
  9367. ;
  9368. end;
  9369. Result := True;
  9370. Exit;
  9371. end;
  9372. end;
  9373. {$else x86_64}
  9374. end;
  9375. end
  9376. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9377. { the use of %rdx also covers the opsize being S_Q }
  9378. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9379. begin
  9380. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9381. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9382. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9383. begin
  9384. { Change:
  9385. movq %rax,%rdx
  9386. sarq $63,%rdx
  9387. To:
  9388. cqto
  9389. }
  9390. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9391. RemoveInstruction(hp1);
  9392. taicpu(p).opcode := A_CQO;
  9393. taicpu(p).opsize := S_NO;
  9394. taicpu(p).clearop(1);
  9395. taicpu(p).clearop(0);
  9396. taicpu(p).ops:=0;
  9397. Result := True;
  9398. Exit;
  9399. end
  9400. else if (cs_opt_size in current_settings.optimizerswitches) and
  9401. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9402. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9403. begin
  9404. { Change:
  9405. movq %rdx,%rax
  9406. sarq $63,%rdx
  9407. To:
  9408. movq %rdx,%rax
  9409. cqto
  9410. Note that this creates a dependency between the two instructions,
  9411. so only perform if optimising for size.
  9412. }
  9413. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9414. taicpu(hp1).opcode := A_CQO;
  9415. taicpu(hp1).opsize := S_NO;
  9416. taicpu(hp1).clearop(1);
  9417. taicpu(hp1).clearop(0);
  9418. taicpu(hp1).ops:=0;
  9419. Include(OptsToCheck, aoc_ForceNewIteration);
  9420. Exit;
  9421. {$endif x86_64}
  9422. end;
  9423. end;
  9424. end;
  9425. if MatchInstruction(hp1, A_MOV, []) and
  9426. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9427. { Though "GetNextInstruction" could be factored out, along with
  9428. the instructions that depend on hp2, it is an expensive call that
  9429. should be delayed for as long as possible, hence we do cheaper
  9430. checks first that are likely to be False. [Kit] }
  9431. begin
  9432. if (
  9433. (
  9434. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9435. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9436. (
  9437. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9438. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9439. )
  9440. ) or
  9441. (
  9442. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9443. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9444. (
  9445. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9446. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9447. )
  9448. )
  9449. ) and
  9450. GetNextInstruction(hp1, hp2) and
  9451. MatchInstruction(hp2, A_SAR, []) and
  9452. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9453. begin
  9454. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9455. begin
  9456. { Change:
  9457. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9458. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9459. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9460. To:
  9461. movl r/m,%eax <- Note the change in register
  9462. cltd
  9463. }
  9464. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9465. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9466. taicpu(p).loadreg(1, NR_EAX);
  9467. taicpu(hp1).opcode := A_CDQ;
  9468. taicpu(hp1).clearop(1);
  9469. taicpu(hp1).clearop(0);
  9470. taicpu(hp1).ops:=0;
  9471. RemoveInstruction(hp2);
  9472. Include(OptsToCheck, aoc_ForceNewIteration);
  9473. (*
  9474. {$ifdef x86_64}
  9475. end
  9476. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9477. { This code sequence does not get generated - however it might become useful
  9478. if and when 128-bit signed integer types make an appearance, so the code
  9479. is kept here for when it is eventually needed. [Kit] }
  9480. (
  9481. (
  9482. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9483. (
  9484. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9485. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9486. )
  9487. ) or
  9488. (
  9489. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9490. (
  9491. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9492. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9493. )
  9494. )
  9495. ) and
  9496. GetNextInstruction(hp1, hp2) and
  9497. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9498. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9499. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9500. begin
  9501. { Change:
  9502. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9503. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9504. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9505. To:
  9506. movq r/m,%rax <- Note the change in register
  9507. cqto
  9508. }
  9509. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9510. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9511. taicpu(p).loadreg(1, NR_RAX);
  9512. taicpu(hp1).opcode := A_CQO;
  9513. taicpu(hp1).clearop(1);
  9514. taicpu(hp1).clearop(0);
  9515. taicpu(hp1).ops:=0;
  9516. RemoveInstruction(hp2);
  9517. Include(OptsToCheck, aoc_ForceNewIteration);
  9518. {$endif x86_64}
  9519. *)
  9520. end;
  9521. end;
  9522. {$ifdef x86_64}
  9523. end;
  9524. if (taicpu(p).opsize = S_L) and
  9525. (taicpu(p).oper[1]^.typ = top_reg) and
  9526. (
  9527. MatchInstruction(hp1, A_MOV,[]) and
  9528. (taicpu(hp1).opsize = S_L) and
  9529. (taicpu(hp1).oper[1]^.typ = top_reg)
  9530. ) and (
  9531. GetNextInstruction(hp1, hp2) and
  9532. (tai(hp2).typ=ait_instruction) and
  9533. (taicpu(hp2).opsize = S_Q) and
  9534. (
  9535. (
  9536. MatchInstruction(hp2, A_ADD,[]) and
  9537. (taicpu(hp2).opsize = S_Q) and
  9538. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9539. (
  9540. (
  9541. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9542. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9543. ) or (
  9544. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9545. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9546. )
  9547. )
  9548. ) or (
  9549. MatchInstruction(hp2, A_LEA,[]) and
  9550. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9551. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9552. (
  9553. (
  9554. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9555. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9556. ) or (
  9557. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9558. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9559. )
  9560. ) and (
  9561. (
  9562. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9563. ) or (
  9564. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9565. )
  9566. )
  9567. )
  9568. )
  9569. ) and (
  9570. GetNextInstruction(hp2, hp3) and
  9571. MatchInstruction(hp3, A_SHR,[]) and
  9572. (taicpu(hp3).opsize = S_Q) and
  9573. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9574. (taicpu(hp3).oper[0]^.val = 1) and
  9575. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9576. ) then
  9577. begin
  9578. { Change movl x, reg1d movl x, reg1d
  9579. movl y, reg2d movl y, reg2d
  9580. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9581. shrq $1, reg1q shrq $1, reg1q
  9582. ( reg1d and reg2d can be switched around in the first two instructions )
  9583. To movl x, reg1d
  9584. addl y, reg1d
  9585. rcrl $1, reg1d
  9586. This corresponds to the common expression (x + y) shr 1, where
  9587. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9588. smaller code, but won't account for x + y causing an overflow). [Kit]
  9589. }
  9590. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9591. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9592. begin
  9593. { Change first MOV command to have the same register as the final output }
  9594. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  9595. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  9596. Result := True;
  9597. end
  9598. else
  9599. begin
  9600. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9601. Include(OptsToCheck, aoc_ForceNewIteration);
  9602. end;
  9603. { Change second MOV command to an ADD command. This is easier than
  9604. converting the existing command because it means we don't have to
  9605. touch 'y', which might be a complicated reference, and also the
  9606. fact that the third command might either be ADD or LEA. [Kit] }
  9607. taicpu(hp1).opcode := A_ADD;
  9608. { Delete old ADD/LEA instruction }
  9609. RemoveInstruction(hp2);
  9610. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9611. taicpu(hp3).opcode := A_RCR;
  9612. taicpu(hp3).changeopsize(S_L);
  9613. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9614. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  9615. called, so FuncMov2Func below is safe to call }
  9616. {$endif x86_64}
  9617. end;
  9618. if FuncMov2Func(p, hp1) then
  9619. begin
  9620. Result := True;
  9621. Exit;
  9622. end;
  9623. end;
  9624. {$push}
  9625. {$q-}{$r-}
  9626. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9627. var
  9628. ThisReg: TRegister;
  9629. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9630. TargetSubReg: TSubRegister;
  9631. hp1, hp2: tai;
  9632. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9633. { Store list of found instructions so we don't have to call
  9634. GetNextInstructionUsingReg multiple times }
  9635. InstrList: array of taicpu;
  9636. InstrMax, Index: Integer;
  9637. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9638. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9639. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9640. WorkingValue: TCgInt;
  9641. PreMessage: string;
  9642. { Data flow analysis }
  9643. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9644. BitwiseOnly, OrXorUsed,
  9645. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9646. function CheckOverflowConditions: Boolean;
  9647. begin
  9648. Result := True;
  9649. if (TestValSignedMax > SignedUpperLimit) then
  9650. UpperSignedOverflow := True;
  9651. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9652. LowerSignedOverflow := True;
  9653. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9654. LowerUnsignedOverflow := True;
  9655. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9656. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9657. begin
  9658. { Absolute overflow }
  9659. Result := False;
  9660. Exit;
  9661. end;
  9662. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9663. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9664. ShiftDownOverflow := True;
  9665. if (TestValMin < 0) or (TestValMax < 0) then
  9666. begin
  9667. LowerUnsignedOverflow := True;
  9668. UpperUnsignedOverflow := True;
  9669. end;
  9670. end;
  9671. function AdjustInitialLoadAndSize: Boolean;
  9672. begin
  9673. Result := False;
  9674. if not p_removed then
  9675. begin
  9676. if TargetSize = MinSize then
  9677. begin
  9678. { Convert the input MOVZX to a MOV }
  9679. if (taicpu(p).oper[0]^.typ = top_reg) and
  9680. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9681. begin
  9682. { Or remove it completely! }
  9683. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9684. RemoveCurrentP(p);
  9685. p_removed := True;
  9686. end
  9687. else
  9688. begin
  9689. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9690. taicpu(p).opcode := A_MOV;
  9691. taicpu(p).oper[1]^.reg := ThisReg;
  9692. taicpu(p).opsize := TargetSize;
  9693. end;
  9694. Result := True;
  9695. end
  9696. else if TargetSize <> MaxSize then
  9697. begin
  9698. case MaxSize of
  9699. S_L:
  9700. if TargetSize = S_W then
  9701. begin
  9702. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9703. taicpu(p).opsize := S_BW;
  9704. taicpu(p).oper[1]^.reg := ThisReg;
  9705. Result := True;
  9706. end
  9707. else
  9708. InternalError(2020112341);
  9709. S_W:
  9710. if TargetSize = S_L then
  9711. begin
  9712. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9713. taicpu(p).opsize := S_BL;
  9714. taicpu(p).oper[1]^.reg := ThisReg;
  9715. Result := True;
  9716. end
  9717. else
  9718. InternalError(2020112342);
  9719. else
  9720. ;
  9721. end;
  9722. end
  9723. else if not hp1_removed and not RegInUse then
  9724. begin
  9725. { If we have something like:
  9726. movzbl (oper),%regd
  9727. add x, %regd
  9728. movzbl %regb, %regd
  9729. We can reduce the register size to the input of the final
  9730. movzbl instruction. Overflows won't have any effect.
  9731. }
  9732. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9733. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9734. begin
  9735. TargetSize := S_B;
  9736. setsubreg(ThisReg, R_SUBL);
  9737. Result := True;
  9738. end
  9739. else if (taicpu(p).opsize = S_WL) and
  9740. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9741. begin
  9742. TargetSize := S_W;
  9743. setsubreg(ThisReg, R_SUBW);
  9744. Result := True;
  9745. end;
  9746. if Result then
  9747. begin
  9748. { Convert the input MOVZX to a MOV }
  9749. if (taicpu(p).oper[0]^.typ = top_reg) and
  9750. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9751. begin
  9752. { Or remove it completely! }
  9753. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9754. RemoveCurrentP(p);
  9755. p_removed := True;
  9756. end
  9757. else
  9758. begin
  9759. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9760. taicpu(p).opcode := A_MOV;
  9761. taicpu(p).oper[1]^.reg := ThisReg;
  9762. taicpu(p).opsize := TargetSize;
  9763. end;
  9764. end;
  9765. end;
  9766. end;
  9767. end;
  9768. procedure AdjustFinalLoad;
  9769. begin
  9770. if not LowerUnsignedOverflow then
  9771. begin
  9772. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9773. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9774. begin
  9775. { Convert the output MOVZX to a MOV }
  9776. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9777. begin
  9778. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9779. if (MinSize = S_B) or
  9780. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9781. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9782. begin
  9783. { Remove it completely! }
  9784. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9785. { Be careful; if p = hp1 and p was also removed, p
  9786. will become a dangling pointer }
  9787. if p = hp1 then
  9788. begin
  9789. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9790. p_removed := True;
  9791. end
  9792. else
  9793. RemoveInstruction(hp1);
  9794. hp1_removed := True;
  9795. end;
  9796. end
  9797. else
  9798. begin
  9799. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9800. taicpu(hp1).opcode := A_MOV;
  9801. taicpu(hp1).oper[0]^.reg := ThisReg;
  9802. taicpu(hp1).opsize := TargetSize;
  9803. end;
  9804. end
  9805. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9806. begin
  9807. { Need to change the size of the output }
  9808. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9809. taicpu(hp1).oper[0]^.reg := ThisReg;
  9810. taicpu(hp1).opsize := S_BL;
  9811. end;
  9812. end;
  9813. end;
  9814. function CompressInstructions: Boolean;
  9815. var
  9816. LocalIndex: Integer;
  9817. begin
  9818. Result := False;
  9819. { The objective here is to try to find a combination that
  9820. removes one of the MOV/Z instructions. }
  9821. if (
  9822. (taicpu(p).oper[0]^.typ <> top_reg) or
  9823. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9824. ) and
  9825. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9826. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9827. begin
  9828. { Make a preference to remove the second MOVZX instruction }
  9829. case taicpu(hp1).opsize of
  9830. S_BL, S_WL:
  9831. begin
  9832. TargetSize := S_L;
  9833. TargetSubReg := R_SUBD;
  9834. end;
  9835. S_BW:
  9836. begin
  9837. TargetSize := S_W;
  9838. TargetSubReg := R_SUBW;
  9839. end;
  9840. else
  9841. InternalError(2020112302);
  9842. end;
  9843. end
  9844. else
  9845. begin
  9846. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9847. begin
  9848. { Exceeded lower bound but not upper bound }
  9849. TargetSize := MaxSize;
  9850. end
  9851. else if not LowerUnsignedOverflow then
  9852. begin
  9853. { Size didn't exceed lower bound }
  9854. TargetSize := MinSize;
  9855. end
  9856. else
  9857. Exit;
  9858. end;
  9859. case TargetSize of
  9860. S_B:
  9861. TargetSubReg := R_SUBL;
  9862. S_W:
  9863. TargetSubReg := R_SUBW;
  9864. S_L:
  9865. TargetSubReg := R_SUBD;
  9866. else
  9867. InternalError(2020112350);
  9868. end;
  9869. { Update the register to its new size }
  9870. setsubreg(ThisReg, TargetSubReg);
  9871. RegInUse := False;
  9872. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9873. begin
  9874. { Check to see if the active register is used afterwards;
  9875. if not, we can change it and make a saving. }
  9876. TransferUsedRegs(TmpUsedRegs);
  9877. { The target register may be marked as in use to cross
  9878. a jump to a distant label, so exclude it }
  9879. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9880. hp2 := p;
  9881. repeat
  9882. { Explicitly check for the excluded register (don't include the first
  9883. instruction as it may be reading from here }
  9884. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9885. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9886. begin
  9887. RegInUse := True;
  9888. Break;
  9889. end;
  9890. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9891. if not GetNextInstruction(hp2, hp2) then
  9892. InternalError(2020112340);
  9893. until (hp2 = hp1);
  9894. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9895. { We might still be able to get away with this }
  9896. RegInUse := not
  9897. (
  9898. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9899. (hp2.typ = ait_instruction) and
  9900. (
  9901. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9902. instruction that doesn't actually contain ThisReg }
  9903. (cs_opt_level3 in current_settings.optimizerswitches) or
  9904. RegInInstruction(ThisReg, hp2)
  9905. ) and
  9906. RegLoadedWithNewValue(ThisReg, hp2)
  9907. );
  9908. if not RegInUse then
  9909. begin
  9910. { Force the register size to the same as this instruction so it can be removed}
  9911. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9912. begin
  9913. TargetSize := S_L;
  9914. TargetSubReg := R_SUBD;
  9915. end
  9916. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9917. begin
  9918. TargetSize := S_W;
  9919. TargetSubReg := R_SUBW;
  9920. end;
  9921. ThisReg := taicpu(hp1).oper[1]^.reg;
  9922. setsubreg(ThisReg, TargetSubReg);
  9923. RegChanged := True;
  9924. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9925. TransferUsedRegs(TmpUsedRegs);
  9926. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9927. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9928. if p = hp1 then
  9929. begin
  9930. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9931. p_removed := True;
  9932. end
  9933. else
  9934. RemoveInstruction(hp1);
  9935. hp1_removed := True;
  9936. { Instruction will become "mov %reg,%reg" }
  9937. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9938. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9939. begin
  9940. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9941. RemoveCurrentP(p);
  9942. p_removed := True;
  9943. end
  9944. else
  9945. taicpu(p).oper[1]^.reg := ThisReg;
  9946. Result := True;
  9947. end
  9948. else
  9949. begin
  9950. if TargetSize <> MaxSize then
  9951. begin
  9952. { Since the register is in use, we have to force it to
  9953. MaxSize otherwise part of it may become undefined later on }
  9954. TargetSize := MaxSize;
  9955. case TargetSize of
  9956. S_B:
  9957. TargetSubReg := R_SUBL;
  9958. S_W:
  9959. TargetSubReg := R_SUBW;
  9960. S_L:
  9961. TargetSubReg := R_SUBD;
  9962. else
  9963. InternalError(2020112351);
  9964. end;
  9965. setsubreg(ThisReg, TargetSubReg);
  9966. end;
  9967. AdjustFinalLoad;
  9968. end;
  9969. end
  9970. else
  9971. AdjustFinalLoad;
  9972. Result := AdjustInitialLoadAndSize or Result;
  9973. { Now go through every instruction we found and change the
  9974. size. If TargetSize = MaxSize, then almost no changes are
  9975. needed and Result can remain False if it hasn't been set
  9976. yet.
  9977. If RegChanged is True, then the register requires changing
  9978. and so the point about TargetSize = MaxSize doesn't apply. }
  9979. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9980. begin
  9981. for LocalIndex := 0 to InstrMax do
  9982. begin
  9983. { If p_removed is true, then the original MOV/Z was removed
  9984. and removing the AND instruction may not be safe if it
  9985. appears first }
  9986. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9987. InternalError(2020112310);
  9988. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9989. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9990. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9991. InstrList[LocalIndex].opsize := TargetSize;
  9992. end;
  9993. Result := True;
  9994. end;
  9995. end;
  9996. begin
  9997. Result := False;
  9998. p_removed := False;
  9999. hp1_removed := False;
  10000. ThisReg := taicpu(p).oper[1]^.reg;
  10001. { Check for:
  10002. movs/z ###,%ecx (or %cx or %rcx)
  10003. ...
  10004. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10005. (dealloc %ecx)
  10006. Change to:
  10007. mov ###,%cl (if ### = %cl, then remove completely)
  10008. ...
  10009. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10010. }
  10011. if (getsupreg(ThisReg) = RS_ECX) and
  10012. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10013. (hp1.typ = ait_instruction) and
  10014. (
  10015. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10016. instruction that doesn't actually contain ECX }
  10017. (cs_opt_level3 in current_settings.optimizerswitches) or
  10018. RegInInstruction(NR_ECX, hp1) or
  10019. (
  10020. { It's common for the shift/rotate's read/write register to be
  10021. initialised in between, so under -O2 and under, search ahead
  10022. one more instruction
  10023. }
  10024. GetNextInstruction(hp1, hp1) and
  10025. (hp1.typ = ait_instruction) and
  10026. RegInInstruction(NR_ECX, hp1)
  10027. )
  10028. ) and
  10029. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10030. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10031. begin
  10032. TransferUsedRegs(TmpUsedRegs);
  10033. hp2 := p;
  10034. repeat
  10035. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10036. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10037. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10038. begin
  10039. case taicpu(p).opsize of
  10040. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10041. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10042. begin
  10043. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10044. RemoveCurrentP(p);
  10045. end
  10046. else
  10047. begin
  10048. taicpu(p).opcode := A_MOV;
  10049. taicpu(p).opsize := S_B;
  10050. taicpu(p).oper[1]^.reg := NR_CL;
  10051. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10052. end;
  10053. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10054. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10055. begin
  10056. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10057. RemoveCurrentP(p);
  10058. end
  10059. else
  10060. begin
  10061. taicpu(p).opcode := A_MOV;
  10062. taicpu(p).opsize := S_W;
  10063. taicpu(p).oper[1]^.reg := NR_CX;
  10064. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10065. end;
  10066. {$ifdef x86_64}
  10067. S_LQ:
  10068. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10069. begin
  10070. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10071. RemoveCurrentP(p);
  10072. end
  10073. else
  10074. begin
  10075. taicpu(p).opcode := A_MOV;
  10076. taicpu(p).opsize := S_L;
  10077. taicpu(p).oper[1]^.reg := NR_ECX;
  10078. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10079. end;
  10080. {$endif x86_64}
  10081. else
  10082. InternalError(2021120401);
  10083. end;
  10084. Result := True;
  10085. Exit;
  10086. end;
  10087. end;
  10088. { This is anything but quick! }
  10089. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10090. Exit;
  10091. SetLength(InstrList, 0);
  10092. InstrMax := -1;
  10093. case taicpu(p).opsize of
  10094. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10095. begin
  10096. {$if defined(i386) or defined(i8086)}
  10097. { If the target size is 8-bit, make sure we can actually encode it }
  10098. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10099. Exit;
  10100. {$endif i386 or i8086}
  10101. LowerLimit := $FF;
  10102. SignedLowerLimit := $7F;
  10103. SignedLowerLimitBottom := -128;
  10104. MinSize := S_B;
  10105. if taicpu(p).opsize = S_BW then
  10106. begin
  10107. MaxSize := S_W;
  10108. UpperLimit := $FFFF;
  10109. SignedUpperLimit := $7FFF;
  10110. SignedUpperLimitBottom := -32768;
  10111. end
  10112. else
  10113. begin
  10114. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10115. MaxSize := S_L;
  10116. UpperLimit := $FFFFFFFF;
  10117. SignedUpperLimit := $7FFFFFFF;
  10118. SignedUpperLimitBottom := -2147483648;
  10119. end;
  10120. end;
  10121. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10122. begin
  10123. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10124. LowerLimit := $FFFF;
  10125. SignedLowerLimit := $7FFF;
  10126. SignedLowerLimitBottom := -32768;
  10127. UpperLimit := $FFFFFFFF;
  10128. SignedUpperLimit := $7FFFFFFF;
  10129. SignedUpperLimitBottom := -2147483648;
  10130. MinSize := S_W;
  10131. MaxSize := S_L;
  10132. end;
  10133. {$ifdef x86_64}
  10134. S_LQ:
  10135. begin
  10136. { Both the lower and upper limits are set to 32-bit. If a limit
  10137. is breached, then optimisation is impossible }
  10138. LowerLimit := $FFFFFFFF;
  10139. SignedLowerLimit := $7FFFFFFF;
  10140. SignedLowerLimitBottom := -2147483648;
  10141. UpperLimit := $FFFFFFFF;
  10142. SignedUpperLimit := $7FFFFFFF;
  10143. SignedUpperLimitBottom := -2147483648;
  10144. MinSize := S_L;
  10145. MaxSize := S_L;
  10146. end;
  10147. {$endif x86_64}
  10148. else
  10149. InternalError(2020112301);
  10150. end;
  10151. TestValMin := 0;
  10152. TestValMax := LowerLimit;
  10153. TestValSignedMax := SignedLowerLimit;
  10154. TryShiftDownLimit := LowerLimit;
  10155. TryShiftDown := S_NO;
  10156. ShiftDownOverflow := False;
  10157. RegChanged := False;
  10158. BitwiseOnly := True;
  10159. OrXorUsed := False;
  10160. UpperSignedOverflow := False;
  10161. LowerSignedOverflow := False;
  10162. UpperUnsignedOverflow := False;
  10163. LowerUnsignedOverflow := False;
  10164. hp1 := p;
  10165. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10166. (hp1.typ = ait_instruction) and
  10167. (
  10168. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10169. instruction that doesn't actually contain ThisReg }
  10170. (cs_opt_level3 in current_settings.optimizerswitches) or
  10171. { This allows this Movx optimisation to work through the SETcc instructions
  10172. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10173. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10174. skip over these SETcc instructions). }
  10175. (taicpu(hp1).opcode = A_SETcc) or
  10176. RegInInstruction(ThisReg, hp1)
  10177. ) do
  10178. begin
  10179. case taicpu(hp1).opcode of
  10180. A_INC,A_DEC:
  10181. begin
  10182. { Has to be an exact match on the register }
  10183. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10184. Break;
  10185. if taicpu(hp1).opcode = A_INC then
  10186. begin
  10187. Inc(TestValMin);
  10188. Inc(TestValMax);
  10189. Inc(TestValSignedMax);
  10190. end
  10191. else
  10192. begin
  10193. Dec(TestValMin);
  10194. Dec(TestValMax);
  10195. Dec(TestValSignedMax);
  10196. end;
  10197. end;
  10198. A_TEST, A_CMP:
  10199. begin
  10200. if (
  10201. { Too high a risk of non-linear behaviour that breaks DFA
  10202. here, unless it's cmp $0,%reg, which is equivalent to
  10203. test %reg,%reg }
  10204. OrXorUsed and
  10205. (taicpu(hp1).opcode = A_CMP) and
  10206. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10207. ) or
  10208. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10209. { Has to be an exact match on the register }
  10210. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10211. (
  10212. { Permit "test %reg,%reg" }
  10213. (taicpu(hp1).opcode = A_TEST) and
  10214. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10215. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10216. ) or
  10217. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10218. { Make sure the comparison value is not smaller than the
  10219. smallest allowed signed value for the minimum size (e.g.
  10220. -128 for 8-bit) }
  10221. not (
  10222. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10223. { Is it in the negative range? }
  10224. (
  10225. (taicpu(hp1).oper[0]^.val < 0) and
  10226. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10227. )
  10228. ) then
  10229. Break;
  10230. { Check to see if the active register is used afterwards }
  10231. TransferUsedRegs(TmpUsedRegs);
  10232. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10233. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10234. begin
  10235. { Make sure the comparison or any previous instructions
  10236. hasn't pushed the test values outside of the range of
  10237. MinSize }
  10238. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10239. begin
  10240. { Exceeded lower bound but not upper bound }
  10241. Exit;
  10242. end
  10243. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10244. begin
  10245. { Size didn't exceed lower bound }
  10246. TargetSize := MinSize;
  10247. end
  10248. else
  10249. Break;
  10250. case TargetSize of
  10251. S_B:
  10252. TargetSubReg := R_SUBL;
  10253. S_W:
  10254. TargetSubReg := R_SUBW;
  10255. S_L:
  10256. TargetSubReg := R_SUBD;
  10257. else
  10258. InternalError(2021051002);
  10259. end;
  10260. if TargetSize <> MaxSize then
  10261. begin
  10262. { Update the register to its new size }
  10263. setsubreg(ThisReg, TargetSubReg);
  10264. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10265. taicpu(hp1).oper[1]^.reg := ThisReg;
  10266. taicpu(hp1).opsize := TargetSize;
  10267. { Convert the input MOVZX to a MOV if necessary }
  10268. AdjustInitialLoadAndSize;
  10269. if (InstrMax >= 0) then
  10270. begin
  10271. for Index := 0 to InstrMax do
  10272. begin
  10273. { If p_removed is true, then the original MOV/Z was removed
  10274. and removing the AND instruction may not be safe if it
  10275. appears first }
  10276. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10277. InternalError(2020112311);
  10278. if InstrList[Index].oper[0]^.typ = top_reg then
  10279. InstrList[Index].oper[0]^.reg := ThisReg;
  10280. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10281. InstrList[Index].opsize := MinSize;
  10282. end;
  10283. end;
  10284. Result := True;
  10285. end;
  10286. Exit;
  10287. end;
  10288. end;
  10289. A_SETcc:
  10290. begin
  10291. { This allows this Movx optimisation to work through the SETcc instructions
  10292. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10293. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10294. skip over these SETcc instructions). }
  10295. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10296. { Of course, break out if the current register is used }
  10297. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10298. Break
  10299. else
  10300. { We must use Continue so the instruction doesn't get added
  10301. to InstrList }
  10302. Continue;
  10303. end;
  10304. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10305. begin
  10306. if
  10307. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10308. { Has to be an exact match on the register }
  10309. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10310. (
  10311. (
  10312. (taicpu(hp1).oper[0]^.typ = top_const) and
  10313. (
  10314. (
  10315. (taicpu(hp1).opcode = A_SHL) and
  10316. (
  10317. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10318. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10319. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10320. )
  10321. ) or (
  10322. (taicpu(hp1).opcode <> A_SHL) and
  10323. (
  10324. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10325. { Is it in the negative range? }
  10326. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10327. )
  10328. )
  10329. )
  10330. ) or (
  10331. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10332. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10333. )
  10334. ) then
  10335. Break;
  10336. { Only process OR and XOR if there are only bitwise operations,
  10337. since otherwise they can too easily fool the data flow
  10338. analysis (they can cause non-linear behaviour) }
  10339. case taicpu(hp1).opcode of
  10340. A_ADD:
  10341. begin
  10342. if OrXorUsed then
  10343. { Too high a risk of non-linear behaviour that breaks DFA here }
  10344. Break
  10345. else
  10346. BitwiseOnly := False;
  10347. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10348. begin
  10349. TestValMin := TestValMin * 2;
  10350. TestValMax := TestValMax * 2;
  10351. TestValSignedMax := TestValSignedMax * 2;
  10352. end
  10353. else
  10354. begin
  10355. WorkingValue := taicpu(hp1).oper[0]^.val;
  10356. TestValMin := TestValMin + WorkingValue;
  10357. TestValMax := TestValMax + WorkingValue;
  10358. TestValSignedMax := TestValSignedMax + WorkingValue;
  10359. end;
  10360. end;
  10361. A_SUB:
  10362. begin
  10363. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10364. begin
  10365. TestValMin := 0;
  10366. TestValMax := 0;
  10367. TestValSignedMax := 0;
  10368. end
  10369. else
  10370. begin
  10371. if OrXorUsed then
  10372. { Too high a risk of non-linear behaviour that breaks DFA here }
  10373. Break
  10374. else
  10375. BitwiseOnly := False;
  10376. WorkingValue := taicpu(hp1).oper[0]^.val;
  10377. TestValMin := TestValMin - WorkingValue;
  10378. TestValMax := TestValMax - WorkingValue;
  10379. TestValSignedMax := TestValSignedMax - WorkingValue;
  10380. end;
  10381. end;
  10382. A_AND:
  10383. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10384. begin
  10385. { we might be able to go smaller if AND appears first }
  10386. if InstrMax = -1 then
  10387. case MinSize of
  10388. S_B:
  10389. ;
  10390. S_W:
  10391. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10392. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10393. begin
  10394. TryShiftDown := S_B;
  10395. TryShiftDownLimit := $FF;
  10396. end;
  10397. S_L:
  10398. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10399. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10400. begin
  10401. TryShiftDown := S_B;
  10402. TryShiftDownLimit := $FF;
  10403. end
  10404. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10405. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10406. begin
  10407. TryShiftDown := S_W;
  10408. TryShiftDownLimit := $FFFF;
  10409. end;
  10410. else
  10411. InternalError(2020112320);
  10412. end;
  10413. WorkingValue := taicpu(hp1).oper[0]^.val;
  10414. TestValMin := TestValMin and WorkingValue;
  10415. TestValMax := TestValMax and WorkingValue;
  10416. TestValSignedMax := TestValSignedMax and WorkingValue;
  10417. end;
  10418. A_OR:
  10419. begin
  10420. if not BitwiseOnly then
  10421. Break;
  10422. OrXorUsed := True;
  10423. WorkingValue := taicpu(hp1).oper[0]^.val;
  10424. TestValMin := TestValMin or WorkingValue;
  10425. TestValMax := TestValMax or WorkingValue;
  10426. TestValSignedMax := TestValSignedMax or WorkingValue;
  10427. end;
  10428. A_XOR:
  10429. begin
  10430. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10431. begin
  10432. TestValMin := 0;
  10433. TestValMax := 0;
  10434. TestValSignedMax := 0;
  10435. end
  10436. else
  10437. begin
  10438. if not BitwiseOnly then
  10439. Break;
  10440. OrXorUsed := True;
  10441. WorkingValue := taicpu(hp1).oper[0]^.val;
  10442. TestValMin := TestValMin xor WorkingValue;
  10443. TestValMax := TestValMax xor WorkingValue;
  10444. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10445. end;
  10446. end;
  10447. A_SHL:
  10448. begin
  10449. BitwiseOnly := False;
  10450. WorkingValue := taicpu(hp1).oper[0]^.val;
  10451. TestValMin := TestValMin shl WorkingValue;
  10452. TestValMax := TestValMax shl WorkingValue;
  10453. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10454. end;
  10455. A_SHR,
  10456. { The first instruction was MOVZX, so the value won't be negative }
  10457. A_SAR:
  10458. begin
  10459. if InstrMax <> -1 then
  10460. BitwiseOnly := False
  10461. else
  10462. { we might be able to go smaller if SHR appears first }
  10463. case MinSize of
  10464. S_B:
  10465. ;
  10466. S_W:
  10467. if (taicpu(hp1).oper[0]^.val >= 8) then
  10468. begin
  10469. TryShiftDown := S_B;
  10470. TryShiftDownLimit := $FF;
  10471. TryShiftDownSignedLimit := $7F;
  10472. TryShiftDownSignedLimitLower := -128;
  10473. end;
  10474. S_L:
  10475. if (taicpu(hp1).oper[0]^.val >= 24) then
  10476. begin
  10477. TryShiftDown := S_B;
  10478. TryShiftDownLimit := $FF;
  10479. TryShiftDownSignedLimit := $7F;
  10480. TryShiftDownSignedLimitLower := -128;
  10481. end
  10482. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10483. begin
  10484. TryShiftDown := S_W;
  10485. TryShiftDownLimit := $FFFF;
  10486. TryShiftDownSignedLimit := $7FFF;
  10487. TryShiftDownSignedLimitLower := -32768;
  10488. end;
  10489. else
  10490. InternalError(2020112321);
  10491. end;
  10492. WorkingValue := taicpu(hp1).oper[0]^.val;
  10493. if taicpu(hp1).opcode = A_SAR then
  10494. begin
  10495. TestValMin := SarInt64(TestValMin, WorkingValue);
  10496. TestValMax := SarInt64(TestValMax, WorkingValue);
  10497. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10498. end
  10499. else
  10500. begin
  10501. TestValMin := TestValMin shr WorkingValue;
  10502. TestValMax := TestValMax shr WorkingValue;
  10503. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10504. end;
  10505. end;
  10506. else
  10507. InternalError(2020112303);
  10508. end;
  10509. end;
  10510. (*
  10511. A_IMUL:
  10512. case taicpu(hp1).ops of
  10513. 2:
  10514. begin
  10515. if not MatchOpType(hp1, top_reg, top_reg) or
  10516. { Has to be an exact match on the register }
  10517. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10518. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10519. Break;
  10520. TestValMin := TestValMin * TestValMin;
  10521. TestValMax := TestValMax * TestValMax;
  10522. TestValSignedMax := TestValSignedMax * TestValMax;
  10523. end;
  10524. 3:
  10525. begin
  10526. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10527. { Has to be an exact match on the register }
  10528. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10529. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10530. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10531. { Is it in the negative range? }
  10532. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10533. Break;
  10534. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10535. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10536. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10537. end;
  10538. else
  10539. Break;
  10540. end;
  10541. A_IDIV:
  10542. case taicpu(hp1).ops of
  10543. 3:
  10544. begin
  10545. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10546. { Has to be an exact match on the register }
  10547. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10548. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10549. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10550. { Is it in the negative range? }
  10551. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10552. Break;
  10553. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10554. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10555. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10556. end;
  10557. else
  10558. Break;
  10559. end;
  10560. *)
  10561. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10562. begin
  10563. { If there are no instructions in between, then we might be able to make a saving }
  10564. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10565. Break;
  10566. { We have something like:
  10567. movzbw %dl,%dx
  10568. ...
  10569. movswl %dx,%edx
  10570. Change the latter to a zero-extension then enter the
  10571. A_MOVZX case branch.
  10572. }
  10573. {$ifdef x86_64}
  10574. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10575. begin
  10576. { this becomes a zero extension from 32-bit to 64-bit, but
  10577. the upper 32 bits are already zero, so just delete the
  10578. instruction }
  10579. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10580. RemoveInstruction(hp1);
  10581. Result := True;
  10582. Exit;
  10583. end
  10584. else
  10585. {$endif x86_64}
  10586. begin
  10587. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10588. taicpu(hp1).opcode := A_MOVZX;
  10589. {$ifdef x86_64}
  10590. case taicpu(hp1).opsize of
  10591. S_BQ:
  10592. begin
  10593. taicpu(hp1).opsize := S_BL;
  10594. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10595. end;
  10596. S_WQ:
  10597. begin
  10598. taicpu(hp1).opsize := S_WL;
  10599. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10600. end;
  10601. S_LQ:
  10602. begin
  10603. taicpu(hp1).opcode := A_MOV;
  10604. taicpu(hp1).opsize := S_L;
  10605. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10606. { In this instance, we need to break out because the
  10607. instruction is no longer MOVZX or MOVSXD }
  10608. Result := True;
  10609. Exit;
  10610. end;
  10611. else
  10612. ;
  10613. end;
  10614. {$endif x86_64}
  10615. Result := CompressInstructions;
  10616. Exit;
  10617. end;
  10618. end;
  10619. A_MOVZX:
  10620. begin
  10621. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10622. Break;
  10623. if (InstrMax = -1) then
  10624. begin
  10625. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10626. begin
  10627. { Optimise around i40003 }
  10628. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10629. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10630. {$ifndef x86_64}
  10631. and (
  10632. (taicpu(p).oper[0]^.typ <> top_reg) or
  10633. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10634. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10635. )
  10636. {$endif not x86_64}
  10637. then
  10638. begin
  10639. if (taicpu(p).oper[0]^.typ = top_reg) then
  10640. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10641. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10642. taicpu(p).opsize := S_BL;
  10643. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10644. RemoveInstruction(hp1);
  10645. Result := True;
  10646. Exit;
  10647. end;
  10648. end
  10649. else
  10650. begin
  10651. { Will return false if the second parameter isn't ThisReg
  10652. (can happen on -O2 and under) }
  10653. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10654. begin
  10655. { The two MOVZX instructions are adjacent, so remove the first one }
  10656. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10657. RemoveCurrentP(p);
  10658. Result := True;
  10659. Exit;
  10660. end;
  10661. Break;
  10662. end;
  10663. end;
  10664. Result := CompressInstructions;
  10665. Exit;
  10666. end;
  10667. else
  10668. { This includes ADC, SBB and IDIV }
  10669. Break;
  10670. end;
  10671. if not CheckOverflowConditions then
  10672. Break;
  10673. { Contains highest index (so instruction count - 1) }
  10674. Inc(InstrMax);
  10675. if InstrMax > High(InstrList) then
  10676. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10677. InstrList[InstrMax] := taicpu(hp1);
  10678. end;
  10679. end;
  10680. {$pop}
  10681. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10682. var
  10683. hp1 : tai;
  10684. begin
  10685. Result:=false;
  10686. if (taicpu(p).ops >= 2) and
  10687. ((taicpu(p).oper[0]^.typ = top_const) or
  10688. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10689. (taicpu(p).oper[1]^.typ = top_reg) and
  10690. ((taicpu(p).ops = 2) or
  10691. ((taicpu(p).oper[2]^.typ = top_reg) and
  10692. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10693. GetLastInstruction(p,hp1) and
  10694. MatchInstruction(hp1,A_MOV,[]) and
  10695. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10696. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10697. begin
  10698. TransferUsedRegs(TmpUsedRegs);
  10699. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10700. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10701. { change
  10702. mov reg1,reg2
  10703. imul y,reg2 to imul y,reg1,reg2 }
  10704. begin
  10705. taicpu(p).ops := 3;
  10706. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10707. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10708. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10709. RemoveInstruction(hp1);
  10710. result:=true;
  10711. end;
  10712. end;
  10713. end;
  10714. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10715. var
  10716. ThisLabel: TAsmLabel;
  10717. begin
  10718. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10719. ThisLabel.decrefs;
  10720. taicpu(p).condition := C_None;
  10721. taicpu(p).opcode := A_RET;
  10722. taicpu(p).is_jmp := false;
  10723. taicpu(p).ops := taicpu(ret_p).ops;
  10724. case taicpu(ret_p).ops of
  10725. 0:
  10726. taicpu(p).clearop(0);
  10727. 1:
  10728. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10729. else
  10730. internalerror(2016041301);
  10731. end;
  10732. { If the original label is now dead, it might turn out that the label
  10733. immediately follows p. As a result, everything beyond it, which will
  10734. be just some final register configuration and a RET instruction, is
  10735. now dead code. [Kit] }
  10736. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10737. running RemoveDeadCodeAfterJump for each RET instruction, because
  10738. this optimisation rarely happens and most RETs appear at the end of
  10739. routines where there is nothing that can be stripped. [Kit] }
  10740. if not ThisLabel.is_used then
  10741. RemoveDeadCodeAfterJump(p);
  10742. end;
  10743. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10744. var
  10745. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10746. Unconditional, PotentialModified: Boolean;
  10747. OperPtr: POper;
  10748. NewRef: TReference;
  10749. InstrList: array of taicpu;
  10750. InstrMax, Index: Integer;
  10751. const
  10752. {$ifdef DEBUG_AOPTCPU}
  10753. SNoFlags: shortstring = ' so the flags aren''t modified';
  10754. {$else DEBUG_AOPTCPU}
  10755. SNoFlags = '';
  10756. {$endif DEBUG_AOPTCPU}
  10757. begin
  10758. Result:=false;
  10759. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10760. begin
  10761. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10762. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10763. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10764. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10765. GetNextInstruction(hp1, hp2) and
  10766. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10767. { Change from: To:
  10768. set(C) %reg j(~C) label
  10769. test %reg,%reg/cmp $0,%reg
  10770. je label
  10771. set(C) %reg j(C) label
  10772. test %reg,%reg/cmp $0,%reg
  10773. jne label
  10774. (Also do something similar with sete/setne instead of je/jne)
  10775. }
  10776. begin
  10777. { Before we do anything else, we need to check the instructions
  10778. in between SETcc and TEST to make sure they don't modify the
  10779. FLAGS register - if -O2 or under, there won't be any
  10780. instructions between SET and TEST }
  10781. TransferUsedRegs(TmpUsedRegs);
  10782. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10783. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10784. begin
  10785. next := p;
  10786. SetLength(InstrList, 0);
  10787. InstrMax := -1;
  10788. PotentialModified := False;
  10789. { Make a note of every instruction that modifies the FLAGS
  10790. register }
  10791. while GetNextInstruction(next, next) and (next <> hp1) do
  10792. begin
  10793. if next.typ <> ait_instruction then
  10794. { GetNextInstructionUsingReg should have returned False }
  10795. InternalError(2021051701);
  10796. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10797. begin
  10798. case taicpu(next).opcode of
  10799. A_SETcc,
  10800. A_CMOVcc,
  10801. A_Jcc:
  10802. begin
  10803. if PotentialModified then
  10804. { Not safe because the flags were modified earlier }
  10805. Exit
  10806. else
  10807. { Condition is the same as the initial SETcc, so this is safe
  10808. (don't add to instruction list though) }
  10809. Continue;
  10810. end;
  10811. A_ADD:
  10812. begin
  10813. if (taicpu(next).opsize = S_B) or
  10814. { LEA doesn't support 8-bit operands }
  10815. (taicpu(next).oper[1]^.typ <> top_reg) or
  10816. { Must write to a register }
  10817. (taicpu(next).oper[0]^.typ = top_ref) then
  10818. { Require a constant or a register }
  10819. Exit;
  10820. PotentialModified := True;
  10821. end;
  10822. A_SUB:
  10823. begin
  10824. if (taicpu(next).opsize = S_B) or
  10825. { LEA doesn't support 8-bit operands }
  10826. (taicpu(next).oper[1]^.typ <> top_reg) or
  10827. { Must write to a register }
  10828. (taicpu(next).oper[0]^.typ <> top_const) or
  10829. (taicpu(next).oper[0]^.val = $80000000) then
  10830. { Can't subtract a register with LEA - also
  10831. check that the value isn't -2^31, as this
  10832. can't be negated }
  10833. Exit;
  10834. PotentialModified := True;
  10835. end;
  10836. A_SAL,
  10837. A_SHL:
  10838. begin
  10839. if (taicpu(next).opsize = S_B) or
  10840. { LEA doesn't support 8-bit operands }
  10841. (taicpu(next).oper[1]^.typ <> top_reg) or
  10842. { Must write to a register }
  10843. (taicpu(next).oper[0]^.typ <> top_const) or
  10844. (taicpu(next).oper[0]^.val < 0) or
  10845. (taicpu(next).oper[0]^.val > 3) then
  10846. Exit;
  10847. PotentialModified := True;
  10848. end;
  10849. A_IMUL:
  10850. begin
  10851. if (taicpu(next).ops <> 3) or
  10852. (taicpu(next).oper[1]^.typ <> top_reg) or
  10853. { Must write to a register }
  10854. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10855. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10856. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10857. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10858. Exit
  10859. else
  10860. PotentialModified := True;
  10861. end;
  10862. else
  10863. { Don't know how to change this, so abort }
  10864. Exit;
  10865. end;
  10866. { Contains highest index (so instruction count - 1) }
  10867. Inc(InstrMax);
  10868. if InstrMax > High(InstrList) then
  10869. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10870. InstrList[InstrMax] := taicpu(next);
  10871. end;
  10872. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10873. end;
  10874. if not Assigned(next) or (next <> hp1) then
  10875. { It should be equal to hp1 }
  10876. InternalError(2021051702);
  10877. { Cycle through each instruction and check to see if we can
  10878. change them to versions that don't modify the flags }
  10879. if (InstrMax >= 0) then
  10880. begin
  10881. for Index := 0 to InstrMax do
  10882. case InstrList[Index].opcode of
  10883. A_ADD:
  10884. begin
  10885. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10886. InstrList[Index].opcode := A_LEA;
  10887. reference_reset(NewRef, 1, []);
  10888. NewRef.base := InstrList[Index].oper[1]^.reg;
  10889. if InstrList[Index].oper[0]^.typ = top_reg then
  10890. begin
  10891. NewRef.index := InstrList[Index].oper[0]^.reg;
  10892. NewRef.scalefactor := 1;
  10893. end
  10894. else
  10895. NewRef.offset := InstrList[Index].oper[0]^.val;
  10896. InstrList[Index].loadref(0, NewRef);
  10897. end;
  10898. A_SUB:
  10899. begin
  10900. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10901. InstrList[Index].opcode := A_LEA;
  10902. reference_reset(NewRef, 1, []);
  10903. NewRef.base := InstrList[Index].oper[1]^.reg;
  10904. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10905. InstrList[Index].loadref(0, NewRef);
  10906. end;
  10907. A_SHL,
  10908. A_SAL:
  10909. begin
  10910. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10911. InstrList[Index].opcode := A_LEA;
  10912. reference_reset(NewRef, 1, []);
  10913. NewRef.index := InstrList[Index].oper[1]^.reg;
  10914. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10915. InstrList[Index].loadref(0, NewRef);
  10916. end;
  10917. A_IMUL:
  10918. begin
  10919. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10920. InstrList[Index].opcode := A_LEA;
  10921. reference_reset(NewRef, 1, []);
  10922. NewRef.index := InstrList[Index].oper[1]^.reg;
  10923. case InstrList[Index].oper[0]^.val of
  10924. 2, 4, 8:
  10925. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10926. else {3, 5 and 9}
  10927. begin
  10928. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10929. NewRef.base := InstrList[Index].oper[1]^.reg;
  10930. end;
  10931. end;
  10932. InstrList[Index].loadref(0, NewRef);
  10933. end;
  10934. else
  10935. InternalError(2021051710);
  10936. end;
  10937. end;
  10938. { Mark the FLAGS register as used across this whole block }
  10939. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10940. end;
  10941. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10942. JumpC := taicpu(hp2).condition;
  10943. Unconditional := False;
  10944. if conditions_equal(JumpC, C_E) then
  10945. SetC := inverse_cond(taicpu(p).condition)
  10946. else if conditions_equal(JumpC, C_NE) then
  10947. SetC := taicpu(p).condition
  10948. else
  10949. { We've got something weird here (and inefficent) }
  10950. begin
  10951. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10952. SetC := C_NONE;
  10953. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10954. if condition_in(C_AE, JumpC) then
  10955. Unconditional := True
  10956. else
  10957. { Not sure what to do with this jump - drop out }
  10958. Exit;
  10959. end;
  10960. RemoveInstruction(hp1);
  10961. if Unconditional then
  10962. MakeUnconditional(taicpu(hp2))
  10963. else
  10964. begin
  10965. if SetC = C_NONE then
  10966. InternalError(2018061402);
  10967. taicpu(hp2).SetCondition(SetC);
  10968. end;
  10969. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10970. TmpUsedRegs }
  10971. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10972. begin
  10973. RemoveCurrentp(p, hp2);
  10974. if taicpu(hp2).opcode = A_SETcc then
  10975. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10976. else
  10977. begin
  10978. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10979. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10980. Include(OptsToCheck, aoc_DoPass2JccOpts);
  10981. end;
  10982. end
  10983. else
  10984. if taicpu(hp2).opcode = A_SETcc then
  10985. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10986. else
  10987. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10988. Result := True;
  10989. end
  10990. else if
  10991. { Make sure the instructions are adjacent }
  10992. (
  10993. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10994. GetNextInstruction(p, hp1)
  10995. ) and
  10996. MatchInstruction(hp1, A_MOV, [S_B]) and
  10997. { Writing to memory is allowed }
  10998. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10999. begin
  11000. {
  11001. Watch out for sequences such as:
  11002. set(c)b %regb
  11003. movb %regb,(ref)
  11004. movb $0,1(ref)
  11005. movb $0,2(ref)
  11006. movb $0,3(ref)
  11007. Much more efficient to turn it into:
  11008. movl $0,%regl
  11009. set(c)b %regb
  11010. movl %regl,(ref)
  11011. Or:
  11012. set(c)b %regb
  11013. movzbl %regb,%regl
  11014. movl %regl,(ref)
  11015. }
  11016. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11017. GetNextInstruction(hp1, hp2) and
  11018. MatchInstruction(hp2, A_MOV, [S_B]) and
  11019. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11020. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11021. begin
  11022. { Don't do anything else except set Result to True }
  11023. end
  11024. else
  11025. begin
  11026. if taicpu(p).oper[0]^.typ = top_reg then
  11027. begin
  11028. TransferUsedRegs(TmpUsedRegs);
  11029. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11030. end;
  11031. { If it's not a register, it's a memory address }
  11032. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11033. begin
  11034. { Even if the register is still in use, we can minimise the
  11035. pipeline stall by changing the MOV into another SETcc. }
  11036. taicpu(hp1).opcode := A_SETcc;
  11037. taicpu(hp1).condition := taicpu(p).condition;
  11038. if taicpu(hp1).oper[1]^.typ = top_ref then
  11039. begin
  11040. { Swapping the operand pointers like this is probably a
  11041. bit naughty, but it is far faster than using loadoper
  11042. to transfer the reference from oper[1] to oper[0] if
  11043. you take into account the extra procedure calls and
  11044. the memory allocation and deallocation required }
  11045. OperPtr := taicpu(hp1).oper[1];
  11046. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11047. taicpu(hp1).oper[0] := OperPtr;
  11048. end
  11049. else
  11050. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11051. taicpu(hp1).clearop(1);
  11052. taicpu(hp1).ops := 1;
  11053. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11054. end
  11055. else
  11056. begin
  11057. if taicpu(hp1).oper[1]^.typ = top_reg then
  11058. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11059. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11060. RemoveInstruction(hp1);
  11061. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11062. end
  11063. end;
  11064. Result := True;
  11065. end;
  11066. end;
  11067. end;
  11068. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11069. var
  11070. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11071. TargetReg: TRegister;
  11072. condition, inverted_condition: TAsmCond;
  11073. FoundMOV: Boolean;
  11074. begin
  11075. Result := False;
  11076. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11077. create the most optimial instructions possible due to limited
  11078. register availability, and there are situations where two
  11079. complementary "simple" CMOV blocks are created which, after the fact
  11080. can be merged into a "double" block. For example:
  11081. movw $257,%ax
  11082. movw $2,%r8w
  11083. xorl r9d,%r9d
  11084. testw $16,18(%rcx)
  11085. cmovew %ax,%dx
  11086. cmovew %r8w,%bx
  11087. cmovel %r9d,%r14d
  11088. movw $1283,%ax
  11089. movw $4,%r8w
  11090. movl $9,%r9d
  11091. cmovnew %ax,%dx
  11092. cmovnew %r8w,%bx
  11093. cmovnel %r9d,%r14d
  11094. The CMOVNE instructions at the end can be removed, and the
  11095. destination registers copied into the MOV instructions directly
  11096. above them, before finally being moved to before the first CMOVE
  11097. instructions, to produce:
  11098. movw $257,%ax
  11099. movw $2,%r8w
  11100. xorl r9d,%r9d
  11101. testw $16,18(%rcx)
  11102. movw $1283,%dx
  11103. movw $4,%bx
  11104. movl $9,%r14d
  11105. cmovew %ax,%dx
  11106. cmovew %r8w,%bx
  11107. cmovel %r9d,%r14d
  11108. Which can then be later optimised to:
  11109. movw $257,%ax
  11110. movw $2,%r8w
  11111. xorl r9d,%r9d
  11112. movw $1283,%dx
  11113. movw $4,%bx
  11114. movl $9,%r14d
  11115. testw $16,18(%rcx)
  11116. cmovew %ax,%dx
  11117. cmovew %r8w,%bx
  11118. cmovel %r9d,%r14d
  11119. }
  11120. TargetReg := taicpu(hp1).oper[1]^.reg;
  11121. condition := taicpu(hp1).condition;
  11122. inverted_condition := inverse_cond(condition);
  11123. pFirstMov := nil;
  11124. pLastMov := nil;
  11125. pCMOV := nil;
  11126. if (p.typ = ait_instruction) then
  11127. pCond := p
  11128. else if not GetNextInstruction(p, pCond) then
  11129. InternalError(2024012501);
  11130. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11131. { We should get the CMP or TEST instructeion }
  11132. InternalError(2024012502);
  11133. if (
  11134. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11135. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11136. ) then
  11137. begin
  11138. { We have to tread carefully here, hence why we're not using
  11139. GetNextInstructionUsingReg... we can only accept MOV and other
  11140. CMOV instructions. Anything else and we must drop out}
  11141. hp2 := hp1;
  11142. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11143. begin
  11144. if (hp2.typ <> ait_instruction) then
  11145. Exit;
  11146. case taicpu(hp2).opcode of
  11147. A_MOV:
  11148. begin
  11149. if not Assigned(pFirstMov) then
  11150. pFirstMov := hp2;
  11151. pLastMOV := hp2;
  11152. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11153. { Something different - drop out }
  11154. Exit;
  11155. { Otherwise, leave it for now }
  11156. end;
  11157. A_CMOVcc:
  11158. begin
  11159. if taicpu(hp2).condition = inverted_condition then
  11160. begin
  11161. { We found what we're looking for }
  11162. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11163. begin
  11164. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11165. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11166. begin
  11167. pCMOV := hp2;
  11168. Break;
  11169. end
  11170. else
  11171. { Unsafe reference - drop out }
  11172. Exit;
  11173. end;
  11174. end
  11175. else if taicpu(hp2).condition <> condition then
  11176. { Something weird - drop out }
  11177. Exit;
  11178. end;
  11179. else
  11180. { Invalid }
  11181. Exit;
  11182. end;
  11183. end;
  11184. if not Assigned(pCMOV) then
  11185. { No complementary CMOV found }
  11186. Exit;
  11187. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11188. begin
  11189. { Don't need to do anything special or search for a matching MOV }
  11190. Asml.Remove(pCMOV);
  11191. if RegInInstruction(TargetReg, pCond) then
  11192. { Make sure we don't overwrite the register if it's being used in the condition }
  11193. Asml.InsertAfter(pCMOV, pCond)
  11194. else
  11195. Asml.InsertBefore(pCMOV, pCond);
  11196. taicpu(pCMOV).opcode := A_MOV;
  11197. taicpu(pCMOV).condition := C_None;
  11198. { Don't need to worry about allocating new registers in these cases }
  11199. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11200. Result := True;
  11201. Exit;
  11202. end
  11203. else
  11204. begin
  11205. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11206. FoundMOV := False;
  11207. { Search for the MOV that sets the target register }
  11208. hp2 := pFirstMov;
  11209. repeat
  11210. if (taicpu(hp2).opcode = A_MOV) and
  11211. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11212. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11213. begin
  11214. { Change the destination }
  11215. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11216. if not FoundMOV then
  11217. begin
  11218. FoundMOV := True;
  11219. { Make sure the register is allocated }
  11220. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11221. end;
  11222. hp1 := tai(hp2.Previous);
  11223. Asml.Remove(hp2);
  11224. if RegInInstruction(TargetReg, pCond) then
  11225. { Make sure we don't overwrite the register if it's being used in the condition }
  11226. Asml.InsertAfter(hp2, pCond)
  11227. else
  11228. Asml.InsertBefore(hp2, pCond);
  11229. if (hp2 = pLastMov) then
  11230. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11231. Break;
  11232. hp2 := hp1;
  11233. end;
  11234. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11235. if FoundMOV then
  11236. { Delete the CMOV }
  11237. RemoveInstruction(pCMOV)
  11238. else
  11239. begin
  11240. { If no MOV was found, we have to actually move and transmute the CMOV }
  11241. Asml.Remove(pCMOV);
  11242. if RegInInstruction(TargetReg, pCond) then
  11243. { Make sure we don't overwrite the register if it's being used in the condition }
  11244. Asml.InsertAfter(pCMOV, pCond)
  11245. else
  11246. Asml.InsertBefore(pCMOV, pCond);
  11247. taicpu(pCMOV).opcode := A_MOV;
  11248. taicpu(pCMOV).condition := C_None;
  11249. end;
  11250. Result := True;
  11251. Exit;
  11252. end;
  11253. end;
  11254. end;
  11255. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11256. var
  11257. hp1, hp2, pCond: tai;
  11258. begin
  11259. Result := False;
  11260. { Search ahead for CMOV instructions }
  11261. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11262. begin
  11263. hp1 := p;
  11264. hp2 := p;
  11265. pCond := nil; { To prevent compiler warnings }
  11266. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11267. DEFAULTFLAGS }
  11268. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11269. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11270. pCond := p;
  11271. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11272. begin
  11273. if (hp1.typ <> ait_instruction) then
  11274. { Break out on markers and labels etc. }
  11275. Break;
  11276. case taicpu(hp1).opcode of
  11277. A_MOV:
  11278. { Ignore regular MOVs unless they are obviously not related
  11279. to a CMOV block }
  11280. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11281. Break;
  11282. A_CMOVcc:
  11283. if TryCmpCMovOpts(pCond, hp1) then
  11284. begin
  11285. hp1 := hp2;
  11286. { p itself isn't changed, and we're still inside a
  11287. while loop to catch subsequent CMOVs, so just flag
  11288. a new iteration }
  11289. Include(OptsToCheck, aoc_ForceNewIteration);
  11290. Continue;
  11291. end;
  11292. else
  11293. { Drop out if we find anything else }
  11294. Break;
  11295. end;
  11296. hp2 := hp1;
  11297. end;
  11298. end;
  11299. end;
  11300. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11301. var
  11302. hp1, hp2, pCond: tai;
  11303. SourceReg, TargetReg: TRegister;
  11304. begin
  11305. Result := False;
  11306. { In some situations, we end up with an inefficient arrangement of
  11307. instructions in the form of:
  11308. or %reg1,%reg2
  11309. (%reg1 deallocated)
  11310. test %reg2,%reg2
  11311. mov x,%reg2
  11312. we may be able to swap and rearrange the registers to produce:
  11313. or %reg2,%reg1
  11314. mov x,%reg2
  11315. test %reg1,%reg1
  11316. (%reg1 deallocated)
  11317. }
  11318. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11319. (taicpu(p).oper[1]^.typ = top_reg) and
  11320. (
  11321. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11322. MatchOperand(taicpu(p).oper[0]^, -1)
  11323. ) and
  11324. GetNextInstruction(p, hp1) and
  11325. MatchInstruction(hp1, A_MOV, []) and
  11326. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11327. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11328. begin
  11329. TargetReg := taicpu(p).oper[1]^.reg;
  11330. { Now look backwards to find a simple commutative operation: ADD,
  11331. IMUL (2-register version), OR, AND or XOR - whose destination
  11332. register is the same as TEST }
  11333. hp2 := p;
  11334. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11335. if RegInInstruction(TargetReg, hp2) then
  11336. begin
  11337. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11338. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11339. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11340. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11341. begin
  11342. SourceReg := taicpu(hp2).oper[0]^.reg;
  11343. if
  11344. { Make sure the MOV doesn't use the other register }
  11345. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11346. { And make sure the source register is not used afterwards }
  11347. not RegInUsedRegs(SourceReg, UsedRegs) then
  11348. begin
  11349. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11350. taicpu(hp2).oper[0]^.reg := TargetReg;
  11351. taicpu(hp2).oper[1]^.reg := SourceReg;
  11352. if taicpu(p).oper[0]^.typ = top_reg then
  11353. taicpu(p).oper[0]^.reg := SourceReg;
  11354. taicpu(p).oper[1]^.reg := SourceReg;
  11355. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11356. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11357. Include(OptsToCheck, aoc_ForceNewIteration);
  11358. { We can still check the following optimisations since
  11359. the instruction is still a TEST }
  11360. end;
  11361. end;
  11362. Break;
  11363. end;
  11364. end;
  11365. { Search ahead3 for CMOV instructions }
  11366. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11367. begin
  11368. hp1 := p;
  11369. hp2 := p;
  11370. pCond := nil; { To prevent compiler warnings }
  11371. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11372. DEFAULTFLAGS }
  11373. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11374. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11375. pCond := p;
  11376. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11377. begin
  11378. if (hp1.typ <> ait_instruction) then
  11379. { Break out on markers and labels etc. }
  11380. Break;
  11381. case taicpu(hp1).opcode of
  11382. A_MOV:
  11383. { Ignore regular MOVs unless they are obviously not related
  11384. to a CMOV block }
  11385. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11386. Break;
  11387. A_CMOVcc:
  11388. if TryCmpCMovOpts(pCond, hp1) then
  11389. begin
  11390. hp1 := hp2;
  11391. { p itself isn't changed, and we're still inside a
  11392. while loop to catch subsequent CMOVs, so just flag
  11393. a new iteration }
  11394. Include(OptsToCheck, aoc_ForceNewIteration);
  11395. Continue;
  11396. end;
  11397. else
  11398. { Drop out if we find anything else }
  11399. Break;
  11400. end;
  11401. hp2 := hp1;
  11402. end;
  11403. end;
  11404. end;
  11405. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11406. var
  11407. hp1: tai;
  11408. Count: Integer;
  11409. OrigLabel: TAsmLabel;
  11410. begin
  11411. result := False;
  11412. { Sometimes, the optimisations below can permit this }
  11413. RemoveDeadCodeAfterJump(p);
  11414. 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
  11415. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11416. begin
  11417. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11418. { Also a side-effect of optimisations }
  11419. if CollapseZeroDistJump(p, OrigLabel) then
  11420. begin
  11421. Result := True;
  11422. Exit;
  11423. end;
  11424. hp1 := GetLabelWithSym(OrigLabel);
  11425. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11426. begin
  11427. if taicpu(hp1).opcode = A_RET then
  11428. begin
  11429. {
  11430. change
  11431. jmp .L1
  11432. ...
  11433. .L1:
  11434. ret
  11435. into
  11436. ret
  11437. }
  11438. begin
  11439. ConvertJumpToRET(p, hp1);
  11440. result:=true;
  11441. end;
  11442. end
  11443. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11444. not (cs_opt_size in current_settings.optimizerswitches) and
  11445. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11446. begin
  11447. Result := True;
  11448. Exit;
  11449. end;
  11450. end;
  11451. end;
  11452. end;
  11453. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11454. begin
  11455. Result := assigned(p) and
  11456. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11457. (taicpu(p).oper[1]^.typ = top_reg) and
  11458. (
  11459. (taicpu(p).oper[0]^.typ = top_reg) or
  11460. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11461. it is not expected that this can cause a seg. violation }
  11462. (
  11463. (taicpu(p).oper[0]^.typ = top_ref) and
  11464. { TODO: Can we detect which references become constants at this
  11465. stage so we don't have to do a blanket ban? }
  11466. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11467. (
  11468. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11469. (
  11470. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11471. not RefModified and
  11472. { If the reference also appears in the condition, then we know it's safe, otherwise
  11473. any kind of access violation would have occurred already }
  11474. Assigned(cond_p) and
  11475. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11476. (cond_p.typ = ait_instruction) and
  11477. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11478. { Just consider 2-operand comparison instructions for now to be safe }
  11479. (taicpu(cond_p).ops = 2) and
  11480. (
  11481. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11482. (
  11483. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11484. { Don't risk identical registers but different offsets, as we may have constructs
  11485. such as buffer streams with things like length fields that indicate whether
  11486. any more data follows. And there are probably some contrived examples where
  11487. writing to offsets behind the one being read also lead to access violations }
  11488. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11489. (
  11490. { Check that we're not modifying a register that appears in the reference }
  11491. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11492. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11493. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11494. )
  11495. )
  11496. )
  11497. )
  11498. )
  11499. )
  11500. );
  11501. end;
  11502. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11503. begin
  11504. { Update integer registers, ignoring deallocations }
  11505. repeat
  11506. while assigned(p) and
  11507. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11508. (p.typ = ait_label) or
  11509. ((p.typ = ait_marker) and
  11510. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11511. p := tai(p.next);
  11512. while assigned(p) and
  11513. (p.typ=ait_RegAlloc) Do
  11514. begin
  11515. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11516. begin
  11517. case tai_regalloc(p).ratype of
  11518. ra_alloc :
  11519. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11520. else
  11521. ;
  11522. end;
  11523. end;
  11524. p := tai(p.next);
  11525. end;
  11526. until not(assigned(p)) or
  11527. (not(p.typ in SkipInstr) and
  11528. not((p.typ = ait_label) and
  11529. labelCanBeSkipped(tai_label(p))));
  11530. end;
  11531. {$ifndef 8086}
  11532. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11533. begin
  11534. Result := False;
  11535. EndJump := nil;
  11536. BlockStop := nil;
  11537. while (BlockStart <> fOptimizer.BlockEnd) and
  11538. { stop on labels }
  11539. (BlockStart.typ <> ait_label) do
  11540. begin
  11541. { Keep track of all integer registers that are used }
  11542. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11543. if BlockStart.typ = ait_instruction then
  11544. begin
  11545. if (taicpu(BlockStart).opcode = A_JMP) then
  11546. begin
  11547. if not IsJumpToLabel(taicpu(BlockStart)) or
  11548. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11549. Exit;
  11550. EndJump := BlockStart;
  11551. Break;
  11552. end
  11553. { Check to see if we have a valid MOV instruction instead }
  11554. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11555. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11556. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11557. begin
  11558. Exit;
  11559. end
  11560. else
  11561. { This will be a valid MOV }
  11562. fAllocationRange := BlockStart;
  11563. end;
  11564. OneBeforeBlock := BlockStart;
  11565. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11566. end;
  11567. if (BlockStart = fOptimizer.BlockEnd) then
  11568. Exit;
  11569. BlockStop := BlockStart;
  11570. Result := True;
  11571. end;
  11572. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  11573. var
  11574. hp1: tai;
  11575. RefModified: Boolean;
  11576. begin
  11577. Result := 0;
  11578. hp1 := BlockStart;
  11579. RefModified := False; { As long as the condition is inverted, this can be reset }
  11580. while assigned(hp1) and
  11581. (hp1 <> BlockStop) do
  11582. begin
  11583. case hp1.typ of
  11584. ait_instruction:
  11585. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11586. begin
  11587. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  11588. begin
  11589. Inc(Result);
  11590. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11591. Assigned(fCondition) and
  11592. { Will have 2 operands }
  11593. (
  11594. (
  11595. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  11596. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  11597. ) or
  11598. (
  11599. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  11600. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  11601. )
  11602. ) then
  11603. { It is no longer safe to use the reference in the condition.
  11604. this prevents problems such as:
  11605. mov (%reg),%reg
  11606. mov (%reg),...
  11607. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11608. (fixes #40165)
  11609. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11610. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11611. }
  11612. RefModified := True;
  11613. end
  11614. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11615. { CMOV with constants grows the code size }
  11616. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  11617. begin
  11618. { Register was reserved by TryCMOVConst and
  11619. stored on ConstRegs }
  11620. end
  11621. else
  11622. begin
  11623. Result := -1;
  11624. Exit;
  11625. end;
  11626. end
  11627. else
  11628. begin
  11629. Result := -1;
  11630. Exit;
  11631. end;
  11632. else
  11633. { Most likely an align };
  11634. end;
  11635. fOptimizer.GetNextInstruction(hp1, hp1);
  11636. end;
  11637. end;
  11638. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  11639. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  11640. (this is done as a separate stage because the double types are extensions of the branching type,
  11641. but we can't discount the conditional jump until the last step) }
  11642. procedure EvaluateBranchingType;
  11643. begin
  11644. Inc(CMOVScore);
  11645. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  11646. { Too many instructions to be worthwhile }
  11647. fState := tsInvalid;
  11648. end;
  11649. var
  11650. hp1: tai;
  11651. Count: Integer;
  11652. begin
  11653. { Table of valid CMOV block types
  11654. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  11655. ---------- --------- --------- --------- --------- ---------
  11656. tsSimple X Yes X X X
  11657. tsDetour = 1st X X X X
  11658. tsBranching <> Mid Yes X X X
  11659. tsDouble End-label Yes * Yes X Yes
  11660. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  11661. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  11662. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  11663. * Only one reference allowed
  11664. }
  11665. hp1 := nil; { To prevent compiler warnings }
  11666. Optimizer.CopyUsedRegs(RegisterTracking);
  11667. fOptimizer := Optimizer;
  11668. fLabel := AFirstLabel;
  11669. CMOVScore := 0;
  11670. ConstCount := 0;
  11671. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11672. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11673. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11674. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11675. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11676. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11677. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11678. fInsertionPoint := p_initialjump;
  11679. fCondition := nil;
  11680. fInitialJump := p_initialjump;
  11681. fFirstMovBlock := p_initialmov;
  11682. fFirstMovBlockStop := nil;
  11683. fSecondJump := nil;
  11684. fSecondMovBlock := nil;
  11685. fSecondMovBlockStop := nil;
  11686. fMidLabel := nil;
  11687. fSecondJump := nil;
  11688. fSecondMovBlock := nil;
  11689. fEndLabel := nil;
  11690. fAllocationRange := nil;
  11691. { Assume it all goes horribly wrong! }
  11692. fState := tsInvalid;
  11693. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  11694. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  11695. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11696. begin
  11697. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11698. for Count := 0 to 1 do
  11699. with taicpu(fCondition).oper[Count]^ do
  11700. case typ of
  11701. top_reg:
  11702. if getregtype(reg) = R_INTREGISTER then
  11703. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11704. top_ref:
  11705. begin
  11706. if
  11707. {$ifdef x86_64}
  11708. (ref^.base <> NR_RIP) and
  11709. {$endif x86_64}
  11710. (ref^.base <> NR_NO) then
  11711. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11712. if (ref^.index <> NR_NO) then
  11713. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11714. end
  11715. else
  11716. ;
  11717. end;
  11718. { When inserting instructions before hp_prev, try to insert them
  11719. before the allocation of the FLAGS register }
  11720. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  11721. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  11722. { If not found, set it equal to the condition so it's something sensible }
  11723. fInsertionPoint := fCondition;
  11724. { When dealing with a comparison against zero, take note of the
  11725. instruction before it to see if we can move instructions further
  11726. back in order to benefit PostPeepholeOptTestOr.
  11727. }
  11728. if (
  11729. (
  11730. (taicpu(fCondition).opcode = A_CMP) and
  11731. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  11732. ) or
  11733. (
  11734. (taicpu(fCondition).opcode = A_TEST) and
  11735. (
  11736. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  11737. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  11738. )
  11739. )
  11740. ) and
  11741. Optimizer.GetLastInstruction(fCondition, hp1) then
  11742. begin
  11743. { These instructions set the zero flag if the result is zero }
  11744. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11745. begin
  11746. fInsertionPoint := hp1;
  11747. { Also mark all the registers in this previous instruction
  11748. as 'in use', even if they've just been deallocated }
  11749. for Count := 0 to 1 do
  11750. with taicpu(hp1).oper[Count]^ do
  11751. case typ of
  11752. top_reg:
  11753. if getregtype(reg) = R_INTREGISTER then
  11754. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  11755. top_ref:
  11756. begin
  11757. if
  11758. {$ifdef x86_64}
  11759. (ref^.base <> NR_RIP) and
  11760. {$endif x86_64}
  11761. (ref^.base <> NR_NO) then
  11762. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  11763. if (ref^.index <> NR_NO) then
  11764. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  11765. end
  11766. else
  11767. ;
  11768. end;
  11769. end;
  11770. end;
  11771. end
  11772. else
  11773. fCondition := nil;
  11774. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  11775. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  11776. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  11777. { If not found, set it equal to p so it's something sensible }
  11778. fInsertionPoint := hp1;
  11779. hp1 := p_initialmov;
  11780. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  11781. Exit;
  11782. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  11783. if (hp1.typ <> ait_label) then { should be on a jump }
  11784. begin
  11785. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  11786. { Need a label afterwards }
  11787. Exit;
  11788. end
  11789. else
  11790. fMidLabel := hp1;
  11791. if tai_label(fMidLabel).labsym <> AFirstLabel then
  11792. { Not the correct label }
  11793. fMidLabel := nil;
  11794. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  11795. { If there's neither a 2nd jump nor correct label, then it's invalid
  11796. (see above table) }
  11797. Exit;
  11798. { Analyse the first block of MOVs more closely }
  11799. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  11800. if Assigned(fSecondJump) then
  11801. begin
  11802. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  11803. begin
  11804. fState := tsDetour
  11805. end
  11806. else
  11807. begin
  11808. { Need the correct mid-label for this one }
  11809. if not Assigned(fMidLabel) then
  11810. Exit;
  11811. fState := tsBranching;
  11812. end;
  11813. end
  11814. else
  11815. { No jump. but mid-label is present }
  11816. fState := tsSimple;
  11817. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  11818. begin
  11819. { Invalid or too many instructions to be worthwhile }
  11820. fState := tsInvalid;
  11821. Exit;
  11822. end;
  11823. { check further for
  11824. jCC xxx
  11825. <several movs 1>
  11826. jmp yyy
  11827. xxx:
  11828. <several movs 2>
  11829. yyy:
  11830. etc.
  11831. }
  11832. if (fState = tsBranching) and
  11833. { Estimate for required savings for extra jump }
  11834. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  11835. { Only one reference is allowed for double blocks }
  11836. (AFirstLabel.getrefs = 1) then
  11837. begin
  11838. Optimizer.GetNextInstruction(fMidLabel, hp1);
  11839. fSecondMovBlock := hp1;
  11840. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  11841. begin
  11842. EvaluateBranchingType;
  11843. Exit;
  11844. end;
  11845. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  11846. if (hp1.typ <> ait_label) then { should be on a jump }
  11847. begin
  11848. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  11849. begin
  11850. { Need a label afterwards }
  11851. EvaluateBranchingType;
  11852. Exit;
  11853. end;
  11854. end
  11855. else
  11856. fEndLabel := hp1;
  11857. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  11858. { Second jump doesn't go to the end }
  11859. fEndLabel := nil;
  11860. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  11861. begin
  11862. { If there's neither a 3rd jump nor correct end label, then it's
  11863. not a invalid double block, but is a valid single branching
  11864. block (see above table) }
  11865. EvaluateBranchingType;
  11866. Exit;
  11867. end;
  11868. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  11869. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  11870. { Invalid or too many instructions to be worthwhile }
  11871. Exit;
  11872. Inc(CMOVScore, Count);
  11873. if Assigned(fThirdJump) then
  11874. begin
  11875. if not Assigned(fSecondJump) then
  11876. fState := tsDoubleSecondBranching
  11877. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  11878. fState := tsDoubleBranchSame
  11879. else
  11880. fState := tsDoubleBranchDifferent;
  11881. end
  11882. else
  11883. fState := tsDouble;
  11884. end;
  11885. if fState = tsBranching then
  11886. EvaluateBranchingType;
  11887. end;
  11888. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  11889. new register to store the constant }
  11890. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  11891. var
  11892. RegSize: TSubRegister;
  11893. CurrentVal: TCGInt;
  11894. ANewReg: TRegister;
  11895. X: ShortInt;
  11896. begin
  11897. Result := False;
  11898. if not MatchOpType(taicpu(p), top_const, top_reg) then
  11899. Exit;
  11900. if ConstCount >= MAX_CMOV_REGISTERS then
  11901. { Arrays are full }
  11902. Exit;
  11903. { Remember that CMOV can't encode 8-bit registers }
  11904. case taicpu(p).opsize of
  11905. S_W:
  11906. RegSize := R_SUBW;
  11907. S_L:
  11908. RegSize := R_SUBD;
  11909. {$ifdef x86_64}
  11910. S_Q:
  11911. RegSize := R_SUBQ;
  11912. {$endif x86_64}
  11913. else
  11914. InternalError(2021100401);
  11915. end;
  11916. { See if the value has already been reserved for another CMOV instruction }
  11917. CurrentVal := taicpu(p).oper[0]^.val;
  11918. for X := 0 to ConstCount - 1 do
  11919. if ConstVals[X] = CurrentVal then
  11920. begin
  11921. ConstRegs[ConstCount] := ConstRegs[X];
  11922. ConstSizes[ConstCount] := RegSize;
  11923. ConstVals[ConstCount] := CurrentVal;
  11924. Inc(ConstCount);
  11925. Inc(Count);
  11926. Result := True;
  11927. Exit;
  11928. end;
  11929. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  11930. if ANewReg = NR_NO then
  11931. { No free registers }
  11932. Exit;
  11933. { Reserve the register so subsequent TryCMOVConst calls don't all end
  11934. up vying for the same register }
  11935. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  11936. ConstRegs[ConstCount] := ANewReg;
  11937. ConstSizes[ConstCount] := RegSize;
  11938. ConstVals[ConstCount] := CurrentVal;
  11939. Inc(ConstCount);
  11940. Inc(Count);
  11941. Result := True;
  11942. end;
  11943. destructor TCMOVTracking.Done;
  11944. begin
  11945. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  11946. end;
  11947. procedure TCMOVTracking.Process(out new_p: tai);
  11948. var
  11949. Count, Writes: LongInt;
  11950. RegMatch: Boolean;
  11951. hp1, hp_new: tai;
  11952. inverted_condition, condition: TAsmCond;
  11953. begin
  11954. if (fState in [tsInvalid, tsProcessed]) then
  11955. InternalError(2023110701);
  11956. { Repurpose RegisterTracking to mark registers that we've defined }
  11957. RegisterTracking[R_INTREGISTER].Clear;
  11958. Count := 0;
  11959. Writes := 0;
  11960. condition := taicpu(fInitialJump).condition;
  11961. inverted_condition := inverse_cond(condition);
  11962. { Exclude tsDoubleBranchDifferent from this check, as the second block
  11963. doesn't get CMOVs in this case }
  11964. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  11965. begin
  11966. { Include the jump in the flag tracking }
  11967. if Assigned(fThirdJump) then
  11968. begin
  11969. if (fState = tsDoubleBranchSame) then
  11970. begin
  11971. { Will be an unconditional jump, so track to the instruction before it }
  11972. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  11973. InternalError(2023110710);
  11974. end
  11975. else
  11976. hp1 := fThirdJump;
  11977. end
  11978. else
  11979. hp1 := fSecondMovBlockStop;
  11980. end
  11981. else
  11982. begin
  11983. { Include a conditional jump in the flag tracking }
  11984. if Assigned(fSecondJump) then
  11985. begin
  11986. if (fState = tsDetour) then
  11987. begin
  11988. { Will be an unconditional jump, so track to the instruction before it }
  11989. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  11990. InternalError(2023110711);
  11991. end
  11992. else
  11993. hp1 := fSecondJump;
  11994. end
  11995. else
  11996. hp1 := fFirstMovBlockStop;
  11997. end;
  11998. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  11999. { Process the second set of MOVs first, because if a destination
  12000. register is shared between the first and second MOV sets, it is more
  12001. efficient to turn the first one into a MOV instruction and place it
  12002. before the CMP if possible, but we won't know which registers are
  12003. shared until we've processed at least one list, so we might as well
  12004. make it the second one since that won't be modified again. }
  12005. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12006. begin
  12007. hp1 := fSecondMovBlock;
  12008. repeat
  12009. if not Assigned(hp1) then
  12010. InternalError(2018062902);
  12011. if (hp1.typ = ait_instruction) then
  12012. begin
  12013. { Extra safeguard }
  12014. if (taicpu(hp1).opcode <> A_MOV) then
  12015. InternalError(2018062903);
  12016. { Note: tsDoubleBranchDifferent is essentially identical to
  12017. tsBranching and the 2nd block is best left largely
  12018. untouched, but we need to evaluate which registers the MOVs
  12019. write to in order to track what would be complementary CMOV
  12020. pairs that can be further optimised. [Kit] }
  12021. if fState <> tsDoubleBranchDifferent then
  12022. begin
  12023. if taicpu(hp1).oper[0]^.typ = top_const then
  12024. begin
  12025. RegMatch := False;
  12026. for Count := 0 to ConstCount - 1 do
  12027. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12028. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12029. begin
  12030. RegMatch := True;
  12031. { If it's in RegisterTracking, then this register
  12032. is being used more than once and hence has
  12033. already had its value defined (it gets added to
  12034. UsedRegs through AllocRegBetween below) }
  12035. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12036. begin
  12037. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12038. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12039. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12040. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12041. ConstMovs[Count] := hp_new;
  12042. end
  12043. else
  12044. { We just need an instruction between hp_prev and hp1
  12045. where we know the register is marked as in use }
  12046. hp_new := fSecondMovBlock;
  12047. { Keep track of largest write for this register so it can be optimised later }
  12048. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12049. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12050. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12051. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12052. Break;
  12053. end;
  12054. if not RegMatch then
  12055. InternalError(2021100411);
  12056. end;
  12057. taicpu(hp1).opcode := A_CMOVcc;
  12058. taicpu(hp1).condition := condition;
  12059. end;
  12060. { Store these writes to search for duplicates later on }
  12061. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12062. Inc(Writes);
  12063. end;
  12064. fOptimizer.GetNextInstruction(hp1, hp1);
  12065. until (hp1 = fSecondMovBlockStop);
  12066. end;
  12067. { Now do the first set of MOVs }
  12068. hp1 := fFirstMovBlock;
  12069. repeat
  12070. if not Assigned(hp1) then
  12071. InternalError(2018062904);
  12072. if (hp1.typ = ait_instruction) then
  12073. begin
  12074. RegMatch := False;
  12075. { Extra safeguard }
  12076. if (taicpu(hp1).opcode <> A_MOV) then
  12077. InternalError(2018062905);
  12078. { Search through the RegWrites list to see if there are any
  12079. opposing CMOV pairs that write to the same register }
  12080. for Count := 0 to Writes - 1 do
  12081. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12082. begin
  12083. { We have a match. Keep this as a MOV }
  12084. { Move ahead in preparation }
  12085. fOptimizer.GetNextInstruction(hp1, hp1);
  12086. RegMatch := True;
  12087. Break;
  12088. end;
  12089. if RegMatch then
  12090. Continue;
  12091. if taicpu(hp1).oper[0]^.typ = top_const then
  12092. begin
  12093. for Count := 0 to ConstCount - 1 do
  12094. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12095. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12096. begin
  12097. RegMatch := True;
  12098. { If it's in RegisterTracking, then this register is
  12099. being used more than once and hence has already had
  12100. its value defined (it gets added to UsedRegs through
  12101. AllocRegBetween below) }
  12102. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12103. begin
  12104. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12105. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12106. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12107. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12108. ConstMovs[Count] := hp_new;
  12109. end
  12110. else
  12111. { We just need an instruction between hp_prev and hp1
  12112. where we know the register is marked as in use }
  12113. hp_new := fFirstMovBlock;
  12114. { Keep track of largest write for this register so it can be optimised later }
  12115. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12116. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12117. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12118. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12119. Break;
  12120. end;
  12121. if not RegMatch then
  12122. InternalError(2021100412);
  12123. end;
  12124. taicpu(hp1).opcode := A_CMOVcc;
  12125. taicpu(hp1).condition := inverted_condition;
  12126. if (fState = tsDoubleBranchDifferent) then
  12127. begin
  12128. { Store these writes to search for duplicates later on }
  12129. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12130. Inc(Writes);
  12131. end;
  12132. end;
  12133. fOptimizer.GetNextInstruction(hp1, hp1);
  12134. until (hp1 = fFirstMovBlockStop);
  12135. { Update initialisation MOVs to the smallest possible size }
  12136. for Count := 0 to ConstCount - 1 do
  12137. if Assigned(ConstMovs[Count]) then
  12138. begin
  12139. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12140. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12141. end;
  12142. case fState of
  12143. tsSimple:
  12144. begin
  12145. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12146. { No branch to delete }
  12147. end;
  12148. tsDetour:
  12149. begin
  12150. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12151. { Preserve jump }
  12152. end;
  12153. tsBranching, tsDoubleBranchDifferent:
  12154. begin
  12155. if (fState = tsBranching) then
  12156. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12157. else
  12158. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12159. taicpu(fSecondJump).opcode := A_JCC;
  12160. taicpu(fSecondJump).condition := inverted_condition;
  12161. end;
  12162. tsDouble, tsDoubleBranchSame:
  12163. begin
  12164. if (fState = tsDouble) then
  12165. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12166. else
  12167. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12168. { Delete second jump }
  12169. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12170. fOptimizer.RemoveInstruction(fSecondJump);
  12171. end;
  12172. tsDoubleSecondBranching:
  12173. begin
  12174. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12175. { Delete second jump, preserve third jump as conditional }
  12176. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12177. fOptimizer.RemoveInstruction(fSecondJump);
  12178. taicpu(fThirdJump).opcode := A_JCC;
  12179. taicpu(fThirdJump).condition := condition;
  12180. end;
  12181. else
  12182. InternalError(2023110720);
  12183. end;
  12184. { Now we can safely decrement the reference count }
  12185. tasmlabel(fLabel).decrefs;
  12186. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12187. { Remove the original jump }
  12188. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12189. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12190. fState := tsProcessed;
  12191. end;
  12192. {$endif 8086}
  12193. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12194. var
  12195. hp1,hp2: tai;
  12196. carryadd_opcode : TAsmOp;
  12197. symbol: TAsmSymbol;
  12198. increg, tmpreg: TRegister;
  12199. {$ifndef i8086}
  12200. CMOVTracking: PCMOVTracking;
  12201. hp3,hp4,hp5: tai;
  12202. {$endif i8086}
  12203. TempBool: Boolean;
  12204. begin
  12205. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12206. DoJumpOptimizations(p, TempBool) then
  12207. Exit(True);
  12208. result:=false;
  12209. if GetNextInstruction(p,hp1) then
  12210. begin
  12211. if (hp1.typ=ait_label) then
  12212. begin
  12213. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12214. Exit;
  12215. end
  12216. else if (hp1.typ<>ait_instruction) then
  12217. Exit;
  12218. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12219. if (
  12220. (
  12221. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12222. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12223. (Taicpu(hp1).oper[0]^.val=1)
  12224. ) or
  12225. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12226. ) and
  12227. GetNextInstruction(hp1,hp2) and
  12228. (hp2.typ = ait_label) and
  12229. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  12230. { jb @@1 cmc
  12231. inc/dec operand --> adc/sbb operand,0
  12232. @@1:
  12233. ... and ...
  12234. jnb @@1
  12235. inc/dec operand --> adc/sbb operand,0
  12236. @@1: }
  12237. begin
  12238. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12239. begin
  12240. case taicpu(hp1).opcode of
  12241. A_INC,
  12242. A_ADD:
  12243. carryadd_opcode:=A_ADC;
  12244. A_DEC,
  12245. A_SUB:
  12246. carryadd_opcode:=A_SBB;
  12247. else
  12248. InternalError(2021011001);
  12249. end;
  12250. Taicpu(p).clearop(0);
  12251. Taicpu(p).ops:=0;
  12252. Taicpu(p).is_jmp:=false;
  12253. Taicpu(p).opcode:=A_CMC;
  12254. Taicpu(p).condition:=C_NONE;
  12255. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12256. Taicpu(hp1).ops:=2;
  12257. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12258. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12259. else
  12260. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12261. Taicpu(hp1).loadconst(0,0);
  12262. Taicpu(hp1).opcode:=carryadd_opcode;
  12263. result:=true;
  12264. exit;
  12265. end
  12266. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12267. begin
  12268. case taicpu(hp1).opcode of
  12269. A_INC,
  12270. A_ADD:
  12271. carryadd_opcode:=A_ADC;
  12272. A_DEC,
  12273. A_SUB:
  12274. carryadd_opcode:=A_SBB;
  12275. else
  12276. InternalError(2021011002);
  12277. end;
  12278. Taicpu(hp1).ops:=2;
  12279. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12280. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12281. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12282. else
  12283. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12284. Taicpu(hp1).loadconst(0,0);
  12285. Taicpu(hp1).opcode:=carryadd_opcode;
  12286. RemoveCurrentP(p, hp1);
  12287. result:=true;
  12288. exit;
  12289. end
  12290. {
  12291. jcc @@1 setcc tmpreg
  12292. inc/dec/add/sub operand -> (movzx tmpreg)
  12293. @@1: add/sub tmpreg,operand
  12294. While this increases code size slightly, it makes the code much faster if the
  12295. jump is unpredictable
  12296. }
  12297. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12298. begin
  12299. { search for an available register which is volatile }
  12300. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12301. if increg <> NR_NO then
  12302. begin
  12303. { We don't need to check if tmpreg is in hp1 or not, because
  12304. it will be marked as in use at p (if not, this is
  12305. indictive of a compiler bug). }
  12306. TAsmLabel(symbol).decrefs;
  12307. Taicpu(p).clearop(0);
  12308. Taicpu(p).ops:=1;
  12309. Taicpu(p).is_jmp:=false;
  12310. Taicpu(p).opcode:=A_SETcc;
  12311. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12312. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12313. Taicpu(p).loadreg(0,increg);
  12314. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12315. begin
  12316. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12317. R_SUBW:
  12318. begin
  12319. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12320. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12321. end;
  12322. R_SUBD:
  12323. begin
  12324. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12325. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12326. end;
  12327. {$ifdef x86_64}
  12328. R_SUBQ:
  12329. begin
  12330. { MOVZX doesn't have a 64-bit variant, because
  12331. the 32-bit version implicitly zeroes the
  12332. upper 32-bits of the destination register }
  12333. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12334. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12335. setsubreg(tmpreg, R_SUBQ);
  12336. end;
  12337. {$endif x86_64}
  12338. else
  12339. Internalerror(2020030601);
  12340. end;
  12341. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12342. asml.InsertAfter(hp2,p);
  12343. end
  12344. else
  12345. tmpreg := increg;
  12346. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12347. begin
  12348. Taicpu(hp1).ops:=2;
  12349. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12350. end;
  12351. Taicpu(hp1).loadreg(0,tmpreg);
  12352. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12353. Result := True;
  12354. { p is no longer a Jcc instruction, so exit }
  12355. Exit;
  12356. end;
  12357. end;
  12358. end;
  12359. { Detect the following:
  12360. jmp<cond> @Lbl1
  12361. jmp @Lbl2
  12362. ...
  12363. @Lbl1:
  12364. ret
  12365. Change to:
  12366. jmp<inv_cond> @Lbl2
  12367. ret
  12368. }
  12369. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12370. begin
  12371. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12372. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12373. MatchInstruction(hp2,A_RET,[S_NO]) then
  12374. begin
  12375. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12376. { Change label address to that of the unconditional jump }
  12377. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12378. TAsmLabel(symbol).DecRefs;
  12379. taicpu(hp1).opcode := A_RET;
  12380. taicpu(hp1).is_jmp := false;
  12381. taicpu(hp1).ops := taicpu(hp2).ops;
  12382. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12383. case taicpu(hp2).ops of
  12384. 0:
  12385. taicpu(hp1).clearop(0);
  12386. 1:
  12387. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12388. else
  12389. internalerror(2016041302);
  12390. end;
  12391. end;
  12392. {$ifndef i8086}
  12393. end
  12394. {
  12395. convert
  12396. j<c> .L1
  12397. mov 1,reg
  12398. jmp .L2
  12399. .L1
  12400. mov 0,reg
  12401. .L2
  12402. into
  12403. mov 0,reg
  12404. set<not(c)> reg
  12405. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12406. would destroy the flag contents
  12407. }
  12408. else if MatchInstruction(hp1,A_MOV,[]) and
  12409. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12410. {$ifdef i386}
  12411. (
  12412. { Under i386, ESI, EDI, EBP and ESP
  12413. don't have an 8-bit representation }
  12414. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12415. ) and
  12416. {$endif i386}
  12417. (taicpu(hp1).oper[0]^.val=1) and
  12418. GetNextInstruction(hp1,hp2) and
  12419. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12420. GetNextInstruction(hp2,hp3) and
  12421. (hp3.typ=ait_label) and
  12422. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12423. (tai_label(hp3).labsym.getrefs=1) and
  12424. GetNextInstruction(hp3,hp4) and
  12425. MatchInstruction(hp4,A_MOV,[]) and
  12426. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12427. (taicpu(hp4).oper[0]^.val=0) and
  12428. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12429. GetNextInstruction(hp4,hp5) and
  12430. (hp5.typ=ait_label) and
  12431. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12432. (tai_label(hp5).labsym.getrefs=1) then
  12433. begin
  12434. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12435. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12436. { remove last label }
  12437. RemoveInstruction(hp5);
  12438. { remove second label }
  12439. RemoveInstruction(hp3);
  12440. { remove jmp }
  12441. RemoveInstruction(hp2);
  12442. if taicpu(hp1).opsize=S_B then
  12443. RemoveInstruction(hp1)
  12444. else
  12445. taicpu(hp1).loadconst(0,0);
  12446. taicpu(hp4).opcode:=A_SETcc;
  12447. taicpu(hp4).opsize:=S_B;
  12448. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12449. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12450. taicpu(hp4).opercnt:=1;
  12451. taicpu(hp4).ops:=1;
  12452. taicpu(hp4).freeop(1);
  12453. RemoveCurrentP(p);
  12454. Result:=true;
  12455. exit;
  12456. end
  12457. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12458. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12459. begin
  12460. { check for
  12461. jCC xxx
  12462. <several movs>
  12463. xxx:
  12464. Also spot:
  12465. Jcc xxx
  12466. <several movs>
  12467. jmp xxx
  12468. Change to:
  12469. <several cmovs with inverted condition>
  12470. jmp xxx (only for the 2nd case)
  12471. }
  12472. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12473. if CMOVTracking^.State <> tsInvalid then
  12474. begin
  12475. CMovTracking^.Process(p);
  12476. Result := True;
  12477. end;
  12478. CMOVTracking^.Done;
  12479. {$endif i8086}
  12480. end;
  12481. end;
  12482. end;
  12483. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12484. var
  12485. hp1,hp2,hp3: tai;
  12486. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12487. NewSize: TOpSize;
  12488. NewRegSize: TSubRegister;
  12489. Limit: TCgInt;
  12490. SwapOper: POper;
  12491. begin
  12492. result:=false;
  12493. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12494. GetNextInstruction(p,hp1) and
  12495. (hp1.typ = ait_instruction);
  12496. if reg_and_hp1_is_instr and
  12497. (
  12498. (taicpu(hp1).opcode <> A_LEA) or
  12499. { If the LEA instruction can be converted into an arithmetic instruction,
  12500. it may be possible to then fold it. }
  12501. (
  12502. { If the flags register is in use, don't change the instruction
  12503. to an ADD otherwise this will scramble the flags. [Kit] }
  12504. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12505. ConvertLEA(taicpu(hp1))
  12506. )
  12507. ) and
  12508. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12509. GetNextInstruction(hp1,hp2) and
  12510. MatchInstruction(hp2,A_MOV,[]) and
  12511. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12512. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12513. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12514. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12515. {$ifdef i386}
  12516. { not all registers have byte size sub registers on i386 }
  12517. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12518. {$endif i386}
  12519. (((taicpu(hp1).ops=2) and
  12520. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12521. ((taicpu(hp1).ops=1) and
  12522. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12523. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12524. begin
  12525. { change movsX/movzX reg/ref, reg2
  12526. add/sub/or/... reg3/$const, reg2
  12527. mov reg2 reg/ref
  12528. to add/sub/or/... reg3/$const, reg/ref }
  12529. { by example:
  12530. movswl %si,%eax movswl %si,%eax p
  12531. decl %eax addl %edx,%eax hp1
  12532. movw %ax,%si movw %ax,%si hp2
  12533. ->
  12534. movswl %si,%eax movswl %si,%eax p
  12535. decw %eax addw %edx,%eax hp1
  12536. movw %ax,%si movw %ax,%si hp2
  12537. }
  12538. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12539. {
  12540. ->
  12541. movswl %si,%eax movswl %si,%eax p
  12542. decw %si addw %dx,%si hp1
  12543. movw %ax,%si movw %ax,%si hp2
  12544. }
  12545. case taicpu(hp1).ops of
  12546. 1:
  12547. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12548. 2:
  12549. begin
  12550. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12551. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12552. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12553. end;
  12554. else
  12555. internalerror(2008042702);
  12556. end;
  12557. {
  12558. ->
  12559. decw %si addw %dx,%si p
  12560. }
  12561. DebugMsg(SPeepholeOptimization + 'var3',p);
  12562. RemoveCurrentP(p, hp1);
  12563. RemoveInstruction(hp2);
  12564. Result := True;
  12565. Exit;
  12566. end;
  12567. if reg_and_hp1_is_instr and
  12568. (taicpu(hp1).opcode = A_MOV) and
  12569. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12570. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  12571. {$ifdef x86_64}
  12572. { check for implicit extension to 64 bit }
  12573. or
  12574. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12575. (taicpu(hp1).opsize=S_Q) and
  12576. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  12577. )
  12578. {$endif x86_64}
  12579. )
  12580. then
  12581. begin
  12582. { change
  12583. movx %reg1,%reg2
  12584. mov %reg2,%reg3
  12585. dealloc %reg2
  12586. into
  12587. movx %reg,%reg3
  12588. }
  12589. TransferUsedRegs(TmpUsedRegs);
  12590. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12591. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  12592. begin
  12593. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  12594. {$ifdef x86_64}
  12595. if (taicpu(p).opsize in [S_BL,S_WL]) and
  12596. (taicpu(hp1).opsize=S_Q) then
  12597. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  12598. else
  12599. {$endif x86_64}
  12600. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  12601. RemoveInstruction(hp1);
  12602. Result := True;
  12603. Exit;
  12604. end;
  12605. end;
  12606. if reg_and_hp1_is_instr and
  12607. ((taicpu(hp1).opcode=A_MOV) or
  12608. (taicpu(hp1).opcode=A_ADD) or
  12609. (taicpu(hp1).opcode=A_SUB) or
  12610. (taicpu(hp1).opcode=A_CMP) or
  12611. (taicpu(hp1).opcode=A_OR) or
  12612. (taicpu(hp1).opcode=A_XOR) or
  12613. (taicpu(hp1).opcode=A_AND)
  12614. ) and
  12615. (taicpu(hp1).oper[1]^.typ = top_reg) then
  12616. begin
  12617. AndTest := (taicpu(hp1).opcode=A_AND) and
  12618. GetNextInstruction(hp1, hp2) and
  12619. (hp2.typ = ait_instruction) and
  12620. (
  12621. (
  12622. (taicpu(hp2).opcode=A_TEST) and
  12623. (
  12624. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  12625. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  12626. (
  12627. { If the AND and TEST instructions share a constant, this is also valid }
  12628. (taicpu(hp1).oper[0]^.typ = top_const) and
  12629. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  12630. )
  12631. ) and
  12632. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12633. ) or
  12634. (
  12635. (taicpu(hp2).opcode=A_CMP) and
  12636. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  12637. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  12638. )
  12639. );
  12640. { change
  12641. movx (oper),%reg2
  12642. and $x,%reg2
  12643. test %reg2,%reg2
  12644. dealloc %reg2
  12645. into
  12646. op %reg1,%reg3
  12647. if the second op accesses only the bits stored in reg1
  12648. }
  12649. if ((taicpu(p).oper[0]^.typ=top_reg) or
  12650. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  12651. (taicpu(hp1).oper[0]^.typ = top_const) and
  12652. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12653. AndTest then
  12654. begin
  12655. { Check if the AND constant is in range }
  12656. case taicpu(p).opsize of
  12657. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12658. begin
  12659. NewSize := S_B;
  12660. Limit := $FF;
  12661. end;
  12662. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12663. begin
  12664. NewSize := S_W;
  12665. Limit := $FFFF;
  12666. end;
  12667. {$ifdef x86_64}
  12668. S_LQ:
  12669. begin
  12670. NewSize := S_L;
  12671. Limit := $FFFFFFFF;
  12672. end;
  12673. {$endif x86_64}
  12674. else
  12675. InternalError(2021120303);
  12676. end;
  12677. if (
  12678. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  12679. { Check for negative operands }
  12680. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  12681. ) and
  12682. GetNextInstruction(hp2,hp3) and
  12683. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  12684. (taicpu(hp3).condition in [C_E,C_NE]) then
  12685. begin
  12686. TransferUsedRegs(TmpUsedRegs);
  12687. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12688. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12689. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  12690. begin
  12691. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  12692. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12693. taicpu(hp1).opcode := A_TEST;
  12694. taicpu(hp1).opsize := NewSize;
  12695. RemoveInstruction(hp2);
  12696. RemoveCurrentP(p, hp1);
  12697. Result:=true;
  12698. exit;
  12699. end;
  12700. end;
  12701. end;
  12702. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12703. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  12704. (taicpu(hp1).opsize=S_B)) or
  12705. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  12706. (taicpu(hp1).opsize=S_W))
  12707. {$ifdef x86_64}
  12708. or ((taicpu(p).opsize=S_LQ) and
  12709. (taicpu(hp1).opsize=S_L))
  12710. {$endif x86_64}
  12711. ) and
  12712. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  12713. begin
  12714. { change
  12715. movx %reg1,%reg2
  12716. op %reg2,%reg3
  12717. dealloc %reg2
  12718. into
  12719. op %reg1,%reg3
  12720. if the second op accesses only the bits stored in reg1
  12721. }
  12722. TransferUsedRegs(TmpUsedRegs);
  12723. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12724. if AndTest then
  12725. begin
  12726. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12727. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12728. end
  12729. else
  12730. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12731. if not RegUsed then
  12732. begin
  12733. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  12734. if taicpu(p).oper[0]^.typ=top_reg then
  12735. begin
  12736. case taicpu(hp1).opsize of
  12737. S_B:
  12738. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  12739. S_W:
  12740. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  12741. S_L:
  12742. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  12743. else
  12744. Internalerror(2020102301);
  12745. end;
  12746. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  12747. end
  12748. else
  12749. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  12750. RemoveCurrentP(p);
  12751. if AndTest then
  12752. RemoveInstruction(hp2);
  12753. result:=true;
  12754. exit;
  12755. end;
  12756. end
  12757. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12758. (
  12759. { Bitwise operations only }
  12760. (taicpu(hp1).opcode=A_AND) or
  12761. (taicpu(hp1).opcode=A_TEST) or
  12762. (
  12763. (taicpu(hp1).oper[0]^.typ = top_const) and
  12764. (
  12765. (taicpu(hp1).opcode=A_OR) or
  12766. (taicpu(hp1).opcode=A_XOR)
  12767. )
  12768. )
  12769. ) and
  12770. (
  12771. (taicpu(hp1).oper[0]^.typ = top_const) or
  12772. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  12773. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  12774. ) then
  12775. begin
  12776. { change
  12777. movx %reg2,%reg2
  12778. op const,%reg2
  12779. into
  12780. op const,%reg2 (smaller version)
  12781. movx %reg2,%reg2
  12782. also change
  12783. movx %reg1,%reg2
  12784. and/test (oper),%reg2
  12785. dealloc %reg2
  12786. into
  12787. and/test (oper),%reg1
  12788. }
  12789. case taicpu(p).opsize of
  12790. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12791. begin
  12792. NewSize := S_B;
  12793. NewRegSize := R_SUBL;
  12794. Limit := $FF;
  12795. end;
  12796. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12797. begin
  12798. NewSize := S_W;
  12799. NewRegSize := R_SUBW;
  12800. Limit := $FFFF;
  12801. end;
  12802. {$ifdef x86_64}
  12803. S_LQ:
  12804. begin
  12805. NewSize := S_L;
  12806. NewRegSize := R_SUBD;
  12807. Limit := $FFFFFFFF;
  12808. end;
  12809. {$endif x86_64}
  12810. else
  12811. Internalerror(2021120302);
  12812. end;
  12813. TransferUsedRegs(TmpUsedRegs);
  12814. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12815. if AndTest then
  12816. begin
  12817. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  12818. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  12819. end
  12820. else
  12821. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  12822. if
  12823. (
  12824. (taicpu(p).opcode = A_MOVZX) and
  12825. (
  12826. (taicpu(hp1).opcode=A_AND) or
  12827. (taicpu(hp1).opcode=A_TEST)
  12828. ) and
  12829. not (
  12830. { If both are references, then the final instruction will have
  12831. both operands as references, which is not allowed }
  12832. (taicpu(p).oper[0]^.typ = top_ref) and
  12833. (taicpu(hp1).oper[0]^.typ = top_ref)
  12834. ) and
  12835. not RegUsed
  12836. ) or
  12837. (
  12838. (
  12839. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  12840. not RegUsed
  12841. ) and
  12842. (taicpu(p).oper[0]^.typ = top_reg) and
  12843. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12844. (taicpu(hp1).oper[0]^.typ = top_const) and
  12845. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  12846. ) then
  12847. begin
  12848. {$if defined(i386) or defined(i8086)}
  12849. { If the target size is 8-bit, make sure we can actually encode it }
  12850. 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
  12851. Exit;
  12852. {$endif i386 or i8086}
  12853. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  12854. taicpu(hp1).opsize := NewSize;
  12855. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  12856. if AndTest then
  12857. begin
  12858. RemoveInstruction(hp2);
  12859. if not RegUsed then
  12860. begin
  12861. taicpu(hp1).opcode := A_TEST;
  12862. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  12863. begin
  12864. { Make sure the reference is the second operand }
  12865. SwapOper := taicpu(hp1).oper[0];
  12866. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  12867. taicpu(hp1).oper[1] := SwapOper;
  12868. end;
  12869. end;
  12870. end;
  12871. case taicpu(hp1).oper[0]^.typ of
  12872. top_reg:
  12873. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12874. top_const:
  12875. { For the AND/TEST case }
  12876. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12877. else
  12878. ;
  12879. end;
  12880. if RegUsed then
  12881. begin
  12882. AsmL.Remove(p);
  12883. AsmL.InsertAfter(p, hp1);
  12884. p := hp1;
  12885. end
  12886. else
  12887. RemoveCurrentP(p, hp1);
  12888. result:=true;
  12889. exit;
  12890. end;
  12891. end;
  12892. end;
  12893. if reg_and_hp1_is_instr and
  12894. (taicpu(p).oper[0]^.typ = top_reg) and
  12895. (
  12896. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12897. ) and
  12898. (taicpu(hp1).oper[0]^.typ = top_const) and
  12899. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12900. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12901. { Minimum shift value allowed is the bit difference between the sizes }
  12902. (taicpu(hp1).oper[0]^.val >=
  12903. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12904. 8 * (
  12905. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12906. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12907. )
  12908. ) then
  12909. begin
  12910. { For:
  12911. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12912. shl/sal ##, %reg1
  12913. Remove the movsx/movzx instruction if the shift overwrites the
  12914. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12915. }
  12916. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12917. RemoveCurrentP(p, hp1);
  12918. Result := True;
  12919. Exit;
  12920. end
  12921. else if reg_and_hp1_is_instr and
  12922. (taicpu(p).oper[0]^.typ = top_reg) and
  12923. (
  12924. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12925. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12926. ) and
  12927. (taicpu(hp1).oper[0]^.typ = top_const) and
  12928. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12929. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12930. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12931. (taicpu(hp1).oper[0]^.val <
  12932. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12933. 8 * (
  12934. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12935. )
  12936. ) then
  12937. begin
  12938. { For:
  12939. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12940. sar ##, %reg1 shr ##, %reg1
  12941. Move the shift to before the movx instruction if the shift value
  12942. is not too large.
  12943. }
  12944. asml.Remove(hp1);
  12945. asml.InsertBefore(hp1, p);
  12946. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12947. case taicpu(p).opsize of
  12948. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12949. taicpu(hp1).opsize := S_B;
  12950. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12951. taicpu(hp1).opsize := S_W;
  12952. {$ifdef x86_64}
  12953. S_LQ:
  12954. taicpu(hp1).opsize := S_L;
  12955. {$endif}
  12956. else
  12957. InternalError(2020112401);
  12958. end;
  12959. if (taicpu(hp1).opcode = A_SHR) then
  12960. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12961. else
  12962. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12963. Result := True;
  12964. end;
  12965. if reg_and_hp1_is_instr and
  12966. (taicpu(p).oper[0]^.typ = top_reg) and
  12967. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12968. (
  12969. (taicpu(hp1).opcode = taicpu(p).opcode)
  12970. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12971. {$ifdef x86_64}
  12972. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12973. {$endif x86_64}
  12974. ) then
  12975. begin
  12976. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12977. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12978. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12979. begin
  12980. {
  12981. For example:
  12982. movzbw %al,%ax
  12983. movzwl %ax,%eax
  12984. Compress into:
  12985. movzbl %al,%eax
  12986. }
  12987. RegUsed := False;
  12988. case taicpu(p).opsize of
  12989. S_BW:
  12990. case taicpu(hp1).opsize of
  12991. S_WL:
  12992. begin
  12993. taicpu(p).opsize := S_BL;
  12994. RegUsed := True;
  12995. end;
  12996. {$ifdef x86_64}
  12997. S_WQ:
  12998. begin
  12999. if taicpu(p).opcode = A_MOVZX then
  13000. begin
  13001. taicpu(p).opsize := S_BL;
  13002. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13003. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13004. end
  13005. else
  13006. taicpu(p).opsize := S_BQ;
  13007. RegUsed := True;
  13008. end;
  13009. {$endif x86_64}
  13010. else
  13011. ;
  13012. end;
  13013. {$ifdef x86_64}
  13014. S_BL:
  13015. case taicpu(hp1).opsize of
  13016. S_LQ:
  13017. begin
  13018. if taicpu(p).opcode = A_MOVZX then
  13019. begin
  13020. taicpu(p).opsize := S_BL;
  13021. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13022. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13023. end
  13024. else
  13025. taicpu(p).opsize := S_BQ;
  13026. RegUsed := True;
  13027. end;
  13028. else
  13029. ;
  13030. end;
  13031. S_WL:
  13032. case taicpu(hp1).opsize of
  13033. S_LQ:
  13034. begin
  13035. if taicpu(p).opcode = A_MOVZX then
  13036. begin
  13037. taicpu(p).opsize := S_WL;
  13038. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13039. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13040. end
  13041. else
  13042. taicpu(p).opsize := S_WQ;
  13043. RegUsed := True;
  13044. end;
  13045. else
  13046. ;
  13047. end;
  13048. {$endif x86_64}
  13049. else
  13050. ;
  13051. end;
  13052. if RegUsed then
  13053. begin
  13054. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13055. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13056. RemoveInstruction(hp1);
  13057. Result := True;
  13058. Exit;
  13059. end;
  13060. end;
  13061. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13062. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13063. GetNextInstruction(hp1, hp2) and
  13064. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13065. (
  13066. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13067. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13068. {$ifdef x86_64}
  13069. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13070. {$endif x86_64}
  13071. ) and
  13072. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13073. (
  13074. (
  13075. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13076. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13077. ) or
  13078. (
  13079. { Only allow the operands in reverse order for TEST instructions }
  13080. (taicpu(hp2).opcode = A_TEST) and
  13081. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13082. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13083. )
  13084. ) then
  13085. begin
  13086. {
  13087. For example:
  13088. movzbl %al,%eax
  13089. movzbl (ref),%edx
  13090. andl %edx,%eax
  13091. (%edx deallocated)
  13092. Change to:
  13093. andb (ref),%al
  13094. movzbl %al,%eax
  13095. Rules are:
  13096. - First two instructions have the same opcode and opsize
  13097. - First instruction's operands are the same super-register
  13098. - Second instruction operates on a different register
  13099. - Third instruction is AND, OR, XOR or TEST
  13100. - Third instruction's operands are the destination registers of the first two instructions
  13101. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13102. - Second instruction's destination register is deallocated afterwards
  13103. }
  13104. TransferUsedRegs(TmpUsedRegs);
  13105. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13106. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13107. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13108. begin
  13109. case taicpu(p).opsize of
  13110. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13111. NewSize := S_B;
  13112. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13113. NewSize := S_W;
  13114. {$ifdef x86_64}
  13115. S_LQ:
  13116. NewSize := S_L;
  13117. {$endif x86_64}
  13118. else
  13119. InternalError(2021120301);
  13120. end;
  13121. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13122. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13123. taicpu(hp2).opsize := NewSize;
  13124. RemoveInstruction(hp1);
  13125. { With TEST, it's best to keep the MOVX instruction at the top }
  13126. if (taicpu(hp2).opcode <> A_TEST) then
  13127. begin
  13128. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13129. asml.Remove(p);
  13130. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13131. asml.InsertAfter(p, hp2);
  13132. p := hp2;
  13133. end
  13134. else
  13135. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13136. Result := True;
  13137. Exit;
  13138. end;
  13139. end;
  13140. end;
  13141. if taicpu(p).opcode=A_MOVZX then
  13142. begin
  13143. { removes superfluous And's after movzx's }
  13144. if reg_and_hp1_is_instr and
  13145. (taicpu(hp1).opcode = A_AND) and
  13146. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13147. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13148. {$ifdef x86_64}
  13149. { check for implicit extension to 64 bit }
  13150. or
  13151. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13152. (taicpu(hp1).opsize=S_Q) and
  13153. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13154. )
  13155. {$endif x86_64}
  13156. )
  13157. then
  13158. begin
  13159. case taicpu(p).opsize Of
  13160. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13161. if (taicpu(hp1).oper[0]^.val = $ff) then
  13162. begin
  13163. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13164. RemoveInstruction(hp1);
  13165. Result:=true;
  13166. exit;
  13167. end;
  13168. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13169. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13170. begin
  13171. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13172. RemoveInstruction(hp1);
  13173. Result:=true;
  13174. exit;
  13175. end;
  13176. {$ifdef x86_64}
  13177. S_LQ:
  13178. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13179. begin
  13180. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13181. RemoveInstruction(hp1);
  13182. Result:=true;
  13183. exit;
  13184. end;
  13185. {$endif x86_64}
  13186. else
  13187. ;
  13188. end;
  13189. { we cannot get rid of the and, but can we get rid of the movz ?}
  13190. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13191. begin
  13192. case taicpu(p).opsize Of
  13193. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13194. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13195. begin
  13196. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13197. RemoveCurrentP(p,hp1);
  13198. Result:=true;
  13199. exit;
  13200. end;
  13201. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13202. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13203. begin
  13204. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13205. RemoveCurrentP(p,hp1);
  13206. Result:=true;
  13207. exit;
  13208. end;
  13209. {$ifdef x86_64}
  13210. S_LQ:
  13211. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13212. begin
  13213. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13214. RemoveCurrentP(p,hp1);
  13215. Result:=true;
  13216. exit;
  13217. end;
  13218. {$endif x86_64}
  13219. else
  13220. ;
  13221. end;
  13222. end;
  13223. end;
  13224. { changes some movzx constructs to faster synonyms (all examples
  13225. are given with eax/ax, but are also valid for other registers)}
  13226. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13227. begin
  13228. case taicpu(p).opsize of
  13229. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13230. (the machine code is equivalent to movzbl %al,%eax), but the
  13231. code generator still generates that assembler instruction and
  13232. it is silently converted. This should probably be checked.
  13233. [Kit] }
  13234. S_BW:
  13235. begin
  13236. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13237. (
  13238. not IsMOVZXAcceptable
  13239. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13240. or (
  13241. (cs_opt_size in current_settings.optimizerswitches) and
  13242. (taicpu(p).oper[1]^.reg = NR_AX)
  13243. )
  13244. ) then
  13245. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13246. begin
  13247. DebugMsg(SPeepholeOptimization + 'var7',p);
  13248. taicpu(p).opcode := A_AND;
  13249. taicpu(p).changeopsize(S_W);
  13250. taicpu(p).loadConst(0,$ff);
  13251. Result := True;
  13252. end
  13253. else if not IsMOVZXAcceptable and
  13254. GetNextInstruction(p, hp1) and
  13255. (tai(hp1).typ = ait_instruction) and
  13256. (taicpu(hp1).opcode = A_AND) and
  13257. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13258. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13259. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13260. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13261. begin
  13262. DebugMsg(SPeepholeOptimization + 'var8',p);
  13263. taicpu(p).opcode := A_MOV;
  13264. taicpu(p).changeopsize(S_W);
  13265. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13266. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13267. Result := True;
  13268. end;
  13269. end;
  13270. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13271. S_BL:
  13272. if not IsMOVZXAcceptable then
  13273. begin
  13274. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13275. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13276. begin
  13277. DebugMsg(SPeepholeOptimization + 'var9',p);
  13278. taicpu(p).opcode := A_AND;
  13279. taicpu(p).changeopsize(S_L);
  13280. taicpu(p).loadConst(0,$ff);
  13281. Result := True;
  13282. end
  13283. else if GetNextInstruction(p, hp1) and
  13284. (tai(hp1).typ = ait_instruction) and
  13285. (taicpu(hp1).opcode = A_AND) and
  13286. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13287. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13288. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13289. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13290. begin
  13291. DebugMsg(SPeepholeOptimization + 'var10',p);
  13292. taicpu(p).opcode := A_MOV;
  13293. taicpu(p).changeopsize(S_L);
  13294. { do not use R_SUBWHOLE
  13295. as movl %rdx,%eax
  13296. is invalid in assembler PM }
  13297. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13298. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13299. Result := True;
  13300. end;
  13301. end;
  13302. {$endif i8086}
  13303. S_WL:
  13304. if not IsMOVZXAcceptable then
  13305. begin
  13306. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13307. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13308. begin
  13309. DebugMsg(SPeepholeOptimization + 'var11',p);
  13310. taicpu(p).opcode := A_AND;
  13311. taicpu(p).changeopsize(S_L);
  13312. taicpu(p).loadConst(0,$ffff);
  13313. Result := True;
  13314. end
  13315. else if GetNextInstruction(p, hp1) and
  13316. (tai(hp1).typ = ait_instruction) and
  13317. (taicpu(hp1).opcode = A_AND) and
  13318. (taicpu(hp1).oper[0]^.typ = top_const) and
  13319. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13320. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13321. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13322. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13323. begin
  13324. DebugMsg(SPeepholeOptimization + 'var12',p);
  13325. taicpu(p).opcode := A_MOV;
  13326. taicpu(p).changeopsize(S_L);
  13327. { do not use R_SUBWHOLE
  13328. as movl %rdx,%eax
  13329. is invalid in assembler PM }
  13330. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13331. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13332. Result := True;
  13333. end;
  13334. end;
  13335. else
  13336. InternalError(2017050705);
  13337. end;
  13338. end
  13339. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13340. begin
  13341. if GetNextInstruction(p, hp1) and
  13342. (tai(hp1).typ = ait_instruction) and
  13343. (taicpu(hp1).opcode = A_AND) and
  13344. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13345. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13346. begin
  13347. //taicpu(p).opcode := A_MOV;
  13348. case taicpu(p).opsize Of
  13349. S_BL:
  13350. begin
  13351. DebugMsg(SPeepholeOptimization + 'var13',p);
  13352. taicpu(hp1).changeopsize(S_L);
  13353. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13354. end;
  13355. S_WL:
  13356. begin
  13357. DebugMsg(SPeepholeOptimization + 'var14',p);
  13358. taicpu(hp1).changeopsize(S_L);
  13359. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13360. end;
  13361. S_BW:
  13362. begin
  13363. DebugMsg(SPeepholeOptimization + 'var15',p);
  13364. taicpu(hp1).changeopsize(S_W);
  13365. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13366. end;
  13367. else
  13368. Internalerror(2017050704)
  13369. end;
  13370. Result := True;
  13371. end;
  13372. end;
  13373. end;
  13374. end;
  13375. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13376. var
  13377. hp1, hp2 : tai;
  13378. MaskLength : Cardinal;
  13379. MaskedBits : TCgInt;
  13380. ActiveReg : TRegister;
  13381. begin
  13382. Result:=false;
  13383. { There are no optimisations for reference targets }
  13384. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13385. Exit;
  13386. while GetNextInstruction(p, hp1) and
  13387. (hp1.typ = ait_instruction) do
  13388. begin
  13389. if (taicpu(p).oper[0]^.typ = top_const) then
  13390. begin
  13391. case taicpu(hp1).opcode of
  13392. A_AND:
  13393. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13394. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13395. { the second register must contain the first one, so compare their subreg types }
  13396. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13397. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13398. { change
  13399. and const1, reg
  13400. and const2, reg
  13401. to
  13402. and (const1 and const2), reg
  13403. }
  13404. begin
  13405. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13406. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13407. RemoveCurrentP(p, hp1);
  13408. Result:=true;
  13409. exit;
  13410. end;
  13411. A_CMP:
  13412. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13413. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13414. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13415. { Just check that the condition on the next instruction is compatible }
  13416. GetNextInstruction(hp1, hp2) and
  13417. (hp2.typ = ait_instruction) and
  13418. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13419. then
  13420. { change
  13421. and 2^n, reg
  13422. cmp 2^n, reg
  13423. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13424. to
  13425. and 2^n, reg
  13426. test reg, reg
  13427. j(~c) / set(~c) / cmov(~c)
  13428. }
  13429. begin
  13430. { Keep TEST instruction in, rather than remove it, because
  13431. it may trigger other optimisations such as MovAndTest2Test }
  13432. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13433. taicpu(hp1).opcode := A_TEST;
  13434. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13435. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13436. Result := True;
  13437. Exit;
  13438. end
  13439. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13440. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13441. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13442. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13443. { change
  13444. and $ff/$ff/$ffff, reg
  13445. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13446. dealloc reg
  13447. to
  13448. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13449. }
  13450. begin
  13451. TransferUsedRegs(TmpUsedRegs);
  13452. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13453. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13454. begin
  13455. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13456. case taicpu(p).oper[0]^.val of
  13457. $ff:
  13458. begin
  13459. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13460. taicpu(hp1).opsize:=S_B;
  13461. end;
  13462. $ffff:
  13463. begin
  13464. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13465. taicpu(hp1).opsize:=S_W;
  13466. end;
  13467. $ffffffff:
  13468. begin
  13469. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13470. taicpu(hp1).opsize:=S_L;
  13471. end;
  13472. else
  13473. Internalerror(2023030401);
  13474. end;
  13475. RemoveCurrentP(p);
  13476. Result := True;
  13477. Exit;
  13478. end;
  13479. end;
  13480. A_MOVZX:
  13481. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13482. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13483. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13484. (
  13485. (
  13486. (taicpu(p).opsize=S_W) and
  13487. (taicpu(hp1).opsize=S_BW)
  13488. ) or
  13489. (
  13490. (taicpu(p).opsize=S_L) and
  13491. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13492. )
  13493. {$ifdef x86_64}
  13494. or
  13495. (
  13496. (taicpu(p).opsize=S_Q) and
  13497. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13498. )
  13499. {$endif x86_64}
  13500. ) then
  13501. begin
  13502. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13503. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13504. ) or
  13505. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13506. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13507. then
  13508. begin
  13509. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13510. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13511. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13512. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13513. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13514. }
  13515. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13516. RemoveInstruction(hp1);
  13517. { See if there are other optimisations possible }
  13518. Continue;
  13519. end;
  13520. end;
  13521. A_SHL:
  13522. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13523. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13524. begin
  13525. {$ifopt R+}
  13526. {$define RANGE_WAS_ON}
  13527. {$R-}
  13528. {$endif}
  13529. { get length of potential and mask }
  13530. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13531. { really a mask? }
  13532. {$ifdef RANGE_WAS_ON}
  13533. {$R+}
  13534. {$endif}
  13535. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13536. { unmasked part shifted out? }
  13537. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13538. begin
  13539. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13540. RemoveCurrentP(p, hp1);
  13541. Result:=true;
  13542. exit;
  13543. end;
  13544. end;
  13545. A_SHR:
  13546. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13547. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13548. (taicpu(hp1).oper[0]^.val <= 63) then
  13549. begin
  13550. { Does SHR combined with the AND cover all the bits?
  13551. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13552. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13553. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13554. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13555. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13556. begin
  13557. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13558. RemoveCurrentP(p, hp1);
  13559. Result := True;
  13560. Exit;
  13561. end;
  13562. end;
  13563. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13564. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13565. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13566. begin
  13567. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13568. (
  13569. (
  13570. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13571. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  13572. ) or (
  13573. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13574. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  13575. {$ifdef x86_64}
  13576. ) or (
  13577. (taicpu(hp1).opsize = S_LQ) and
  13578. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  13579. {$endif x86_64}
  13580. )
  13581. ) then
  13582. begin
  13583. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  13584. begin
  13585. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  13586. RemoveInstruction(hp1);
  13587. { See if there are other optimisations possible }
  13588. Continue;
  13589. end;
  13590. { The super-registers are the same though.
  13591. Note that this change by itself doesn't improve
  13592. code speed, but it opens up other optimisations. }
  13593. {$ifdef x86_64}
  13594. { Convert 64-bit register to 32-bit }
  13595. case taicpu(hp1).opsize of
  13596. S_BQ:
  13597. begin
  13598. taicpu(hp1).opsize := S_BL;
  13599. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13600. end;
  13601. S_WQ:
  13602. begin
  13603. taicpu(hp1).opsize := S_WL;
  13604. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  13605. end
  13606. else
  13607. ;
  13608. end;
  13609. {$endif x86_64}
  13610. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  13611. taicpu(hp1).opcode := A_MOVZX;
  13612. { See if there are other optimisations possible }
  13613. Continue;
  13614. end;
  13615. end;
  13616. else
  13617. ;
  13618. end;
  13619. end
  13620. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  13621. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13622. begin
  13623. {$ifdef x86_64}
  13624. if (taicpu(p).opsize = S_Q) then
  13625. begin
  13626. { Never necessary }
  13627. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  13628. RemoveCurrentP(p, hp1);
  13629. Result := True;
  13630. Exit;
  13631. end;
  13632. {$endif x86_64}
  13633. { Forward check to determine necessity of and %reg,%reg }
  13634. TransferUsedRegs(TmpUsedRegs);
  13635. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13636. { Saves on a bunch of dereferences }
  13637. ActiveReg := taicpu(p).oper[1]^.reg;
  13638. case taicpu(hp1).opcode of
  13639. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  13640. if (
  13641. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13642. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13643. ) and
  13644. (
  13645. (taicpu(hp1).opcode <> A_MOV) or
  13646. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  13647. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  13648. ) and
  13649. not (
  13650. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  13651. (taicpu(hp1).opcode = A_MOV) and
  13652. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  13653. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  13654. ) and
  13655. (
  13656. (
  13657. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13658. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  13659. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  13660. ) or
  13661. (
  13662. {$ifdef x86_64}
  13663. (
  13664. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  13665. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  13666. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  13667. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  13668. ) and
  13669. {$endif x86_64}
  13670. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  13671. )
  13672. ) then
  13673. begin
  13674. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  13675. RemoveCurrentP(p, hp1);
  13676. Result := True;
  13677. Exit;
  13678. end;
  13679. A_ADD,
  13680. A_AND,
  13681. A_BSF,
  13682. A_BSR,
  13683. A_BTC,
  13684. A_BTR,
  13685. A_BTS,
  13686. A_OR,
  13687. A_SUB,
  13688. A_XOR:
  13689. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  13690. if (
  13691. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13692. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13693. ) and
  13694. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  13695. begin
  13696. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  13697. RemoveCurrentP(p, hp1);
  13698. Result := True;
  13699. Exit;
  13700. end;
  13701. A_CMP,
  13702. A_TEST:
  13703. if (
  13704. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  13705. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  13706. ) and
  13707. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  13708. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  13709. begin
  13710. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  13711. RemoveCurrentP(p, hp1);
  13712. Result := True;
  13713. Exit;
  13714. end;
  13715. A_BSWAP,
  13716. A_NEG,
  13717. A_NOT:
  13718. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  13719. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  13720. begin
  13721. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  13722. RemoveCurrentP(p, hp1);
  13723. Result := True;
  13724. Exit;
  13725. end;
  13726. else
  13727. ;
  13728. end;
  13729. end;
  13730. if (taicpu(hp1).is_jmp) and
  13731. (taicpu(hp1).opcode<>A_JMP) and
  13732. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  13733. begin
  13734. { change
  13735. and x, reg
  13736. jxx
  13737. to
  13738. test x, reg
  13739. jxx
  13740. if reg is deallocated before the
  13741. jump, but only if it's a conditional jump (PFV)
  13742. }
  13743. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  13744. taicpu(p).opcode := A_TEST;
  13745. Exit;
  13746. end;
  13747. Break;
  13748. end;
  13749. { Lone AND tests }
  13750. if (taicpu(p).oper[0]^.typ = top_const) then
  13751. begin
  13752. {
  13753. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  13754. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  13755. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  13756. }
  13757. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  13758. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  13759. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  13760. begin
  13761. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  13762. if taicpu(p).opsize = S_L then
  13763. begin
  13764. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  13765. Result := True;
  13766. end;
  13767. end;
  13768. end;
  13769. { Backward check to determine necessity of and %reg,%reg }
  13770. if (taicpu(p).oper[0]^.typ = top_reg) and
  13771. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13772. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13773. GetLastInstruction(p, hp2) and
  13774. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  13775. { Check size of adjacent instruction to determine if the AND is
  13776. effectively a null operation }
  13777. (
  13778. (taicpu(p).opsize = taicpu(hp2).opsize) or
  13779. { Note: Don't include S_Q }
  13780. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  13781. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  13782. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  13783. ) then
  13784. begin
  13785. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  13786. { If GetNextInstruction returned False, hp1 will be nil }
  13787. RemoveCurrentP(p, hp1);
  13788. Result := True;
  13789. Exit;
  13790. end;
  13791. end;
  13792. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  13793. var
  13794. hp1, hp2: tai;
  13795. NewRef: TReference;
  13796. Distance: Cardinal;
  13797. TempTracking: TAllUsedRegs;
  13798. { This entire nested function is used in an if-statement below, but we
  13799. want to avoid all the used reg transfers and GetNextInstruction calls
  13800. until we really have to check }
  13801. function MemRegisterNotUsedLater: Boolean; inline;
  13802. var
  13803. hp2: tai;
  13804. begin
  13805. TransferUsedRegs(TmpUsedRegs);
  13806. hp2 := p;
  13807. repeat
  13808. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13809. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13810. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  13811. end;
  13812. begin
  13813. Result := False;
  13814. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13815. (taicpu(p).oper[1]^.typ = top_reg) then
  13816. begin
  13817. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13818. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13819. (hp1.typ <> ait_instruction) or
  13820. not
  13821. (
  13822. (cs_opt_level3 in current_settings.optimizerswitches) or
  13823. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13824. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13825. ) then
  13826. Exit;
  13827. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13828. addq $x, %rax
  13829. movq %rax, %rdx
  13830. sarq $63, %rdx
  13831. (%rax still in use)
  13832. ...letting OptPass2ADD run its course (and without -Os) will produce:
  13833. leaq $x(%rax),%rdx
  13834. addq $x, %rax
  13835. sarq $63, %rdx
  13836. ...which is okay since it breaks the dependency chain between
  13837. addq and movq, but if OptPass2MOV is called first:
  13838. addq $x, %rax
  13839. cqto
  13840. ...which is better in all ways, taking only 2 cycles to execute
  13841. and much smaller in code size.
  13842. }
  13843. { The extra register tracking is quite strenuous }
  13844. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13845. MatchInstruction(hp1, A_MOV, []) then
  13846. begin
  13847. { Update the register tracking to the MOV instruction }
  13848. CopyUsedRegs(TempTracking);
  13849. hp2 := p;
  13850. repeat
  13851. UpdateUsedRegs(tai(hp2.Next));
  13852. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13853. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13854. OptPass2ADD get called again }
  13855. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13856. begin
  13857. { Reset the tracking to the current instruction }
  13858. RestoreUsedRegs(TempTracking);
  13859. ReleaseUsedRegs(TempTracking);
  13860. Result := True;
  13861. Exit;
  13862. end;
  13863. { Reset the tracking to the current instruction }
  13864. RestoreUsedRegs(TempTracking);
  13865. ReleaseUsedRegs(TempTracking);
  13866. { If OptPass2MOV returned True, we don't need to set Result to
  13867. True if hp1 didn't change because the ADD instruction didn't
  13868. get modified and we'll be evaluating hp1 again when the
  13869. peephole optimizer reaches it }
  13870. end;
  13871. { Change:
  13872. add %reg2,%reg1
  13873. (%reg2 not modified in between)
  13874. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13875. To:
  13876. mov/s/z #(%reg1,%reg2),%reg1
  13877. }
  13878. if (taicpu(p).oper[0]^.typ = top_reg) and
  13879. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13880. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13881. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13882. (
  13883. (
  13884. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13885. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13886. { r/esp cannot be an index }
  13887. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13888. ) or (
  13889. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13890. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13891. )
  13892. ) and (
  13893. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13894. (
  13895. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13896. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13897. MemRegisterNotUsedLater
  13898. )
  13899. ) then
  13900. begin
  13901. if (
  13902. { Instructions are guaranteed to be adjacent on -O2 and under }
  13903. (cs_opt_level3 in current_settings.optimizerswitches) and
  13904. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13905. ) then
  13906. begin
  13907. { If the other register is used in between, move the MOV
  13908. instruction to right after the ADD instruction so a
  13909. saving can still be made }
  13910. Asml.Remove(hp1);
  13911. Asml.InsertAfter(hp1, p);
  13912. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13913. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13914. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13915. RemoveCurrentp(p, hp1);
  13916. end
  13917. else
  13918. begin
  13919. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13920. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13921. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13922. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13923. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13924. { hp1 may not be the immediate next instruction under -O3 }
  13925. RemoveCurrentp(p)
  13926. else
  13927. RemoveCurrentp(p, hp1);
  13928. end;
  13929. Result := True;
  13930. Exit;
  13931. end;
  13932. { Change:
  13933. addl/q $x,%reg1
  13934. movl/q %reg1,%reg2
  13935. To:
  13936. leal/q $x(%reg1),%reg2
  13937. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13938. Breaks the dependency chain.
  13939. }
  13940. if (taicpu(p).oper[0]^.typ = top_const) and
  13941. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13942. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13943. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13944. (
  13945. { Instructions are guaranteed to be adjacent on -O2 and under }
  13946. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13947. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13948. ) then
  13949. begin
  13950. TransferUsedRegs(TmpUsedRegs);
  13951. hp2 := p;
  13952. repeat
  13953. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13954. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13955. if (
  13956. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13957. not (cs_opt_size in current_settings.optimizerswitches) or
  13958. (
  13959. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13960. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13961. )
  13962. ) then
  13963. begin
  13964. { Change the MOV instruction to a LEA instruction, and update the
  13965. first operand }
  13966. reference_reset(NewRef, 1, []);
  13967. NewRef.base := taicpu(p).oper[1]^.reg;
  13968. NewRef.scalefactor := 1;
  13969. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13970. taicpu(hp1).opcode := A_LEA;
  13971. taicpu(hp1).loadref(0, NewRef);
  13972. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13973. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13974. begin
  13975. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13976. { Move what is now the LEA instruction to before the ADD instruction }
  13977. Asml.Remove(hp1);
  13978. Asml.InsertBefore(hp1, p);
  13979. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13980. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13981. p := hp1;
  13982. end
  13983. else
  13984. begin
  13985. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13986. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13987. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13988. { hp1 may not be the immediate next instruction under -O3 }
  13989. RemoveCurrentp(p)
  13990. else
  13991. RemoveCurrentp(p, hp1);
  13992. end;
  13993. Result := True;
  13994. end;
  13995. end;
  13996. end;
  13997. end;
  13998. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13999. var
  14000. SubReg: TSubRegister;
  14001. hp1, hp2: tai;
  14002. CallJmp: Boolean;
  14003. begin
  14004. Result := False;
  14005. CallJmp := False;
  14006. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14007. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14008. with taicpu(p).oper[0]^.ref^ do
  14009. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14010. if (offset = 0) then
  14011. begin
  14012. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14013. begin
  14014. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14015. taicpu(p).opcode := A_ADD;
  14016. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14017. Result := True;
  14018. end
  14019. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14020. begin
  14021. if (base <> NR_NO) then
  14022. begin
  14023. if (scalefactor <= 1) then
  14024. begin
  14025. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14026. taicpu(p).opcode := A_ADD;
  14027. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14028. Result := True;
  14029. end;
  14030. end
  14031. else
  14032. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14033. if (scalefactor in [2, 4, 8]) then
  14034. begin
  14035. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14036. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14037. taicpu(p).opcode := A_SHL;
  14038. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14039. Result := True;
  14040. end;
  14041. end;
  14042. end
  14043. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14044. lot of latency, so break off the offset if %reg3 is used soon
  14045. afterwards }
  14046. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14047. { If 3-component addresses don't have additional latency, don't
  14048. perform this optimisation }
  14049. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14050. GetNextInstruction(p, hp1) and
  14051. (
  14052. (
  14053. { Permit jumps and calls since they have a larger degree of overhead }
  14054. (
  14055. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14056. (
  14057. { ... unless the register specifies the location }
  14058. (taicpu(hp1).ops > 0) and
  14059. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14060. )
  14061. ) and
  14062. (
  14063. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14064. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14065. )
  14066. )
  14067. or
  14068. (
  14069. { Check up to two instructions ahead }
  14070. GetNextInstruction(hp1, hp2) and
  14071. (
  14072. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14073. (
  14074. { Same as above }
  14075. (taicpu(hp2).ops > 0) and
  14076. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14077. )
  14078. ) and
  14079. (
  14080. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14081. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14082. )
  14083. )
  14084. ) then
  14085. begin
  14086. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14087. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14088. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14089. offset := 0;
  14090. if Assigned(symbol) or Assigned(relsymbol) then
  14091. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14092. else
  14093. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14094. { Inserting before the next instruction rather than after the
  14095. current instruction gives more accurate register tracking }
  14096. asml.InsertBefore(hp2, hp1);
  14097. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14098. Result := True;
  14099. end;
  14100. end;
  14101. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14102. var
  14103. hp1, hp2: tai;
  14104. NewRef: TReference;
  14105. Distance: Cardinal;
  14106. TempTracking: TAllUsedRegs;
  14107. begin
  14108. Result := False;
  14109. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14110. MatchOpType(taicpu(p),top_const,top_reg) then
  14111. begin
  14112. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14113. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14114. (hp1.typ <> ait_instruction) or
  14115. not
  14116. (
  14117. (cs_opt_level3 in current_settings.optimizerswitches) or
  14118. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14119. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14120. ) then
  14121. Exit;
  14122. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14123. subq $x, %rax
  14124. movq %rax, %rdx
  14125. sarq $63, %rdx
  14126. (%rax still in use)
  14127. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14128. leaq $-x(%rax),%rdx
  14129. movq $x, %rax
  14130. sarq $63, %rdx
  14131. ...which is okay since it breaks the dependency chain between
  14132. subq and movq, but if OptPass2MOV is called first:
  14133. subq $x, %rax
  14134. cqto
  14135. ...which is better in all ways, taking only 2 cycles to execute
  14136. and much smaller in code size.
  14137. }
  14138. { The extra register tracking is quite strenuous }
  14139. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14140. MatchInstruction(hp1, A_MOV, []) then
  14141. begin
  14142. { Update the register tracking to the MOV instruction }
  14143. CopyUsedRegs(TempTracking);
  14144. hp2 := p;
  14145. repeat
  14146. UpdateUsedRegs(tai(hp2.Next));
  14147. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14148. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14149. OptPass2SUB get called again }
  14150. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  14151. begin
  14152. { Reset the tracking to the current instruction }
  14153. RestoreUsedRegs(TempTracking);
  14154. ReleaseUsedRegs(TempTracking);
  14155. Result := True;
  14156. Exit;
  14157. end;
  14158. { Reset the tracking to the current instruction }
  14159. RestoreUsedRegs(TempTracking);
  14160. ReleaseUsedRegs(TempTracking);
  14161. { If OptPass2MOV returned True, we don't need to set Result to
  14162. True if hp1 didn't change because the SUB instruction didn't
  14163. get modified and we'll be evaluating hp1 again when the
  14164. peephole optimizer reaches it }
  14165. end;
  14166. { Change:
  14167. subl/q $x,%reg1
  14168. movl/q %reg1,%reg2
  14169. To:
  14170. leal/q $-x(%reg1),%reg2
  14171. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14172. Breaks the dependency chain and potentially permits the removal of
  14173. a CMP instruction if one follows.
  14174. }
  14175. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14176. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14177. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14178. (
  14179. { Instructions are guaranteed to be adjacent on -O2 and under }
  14180. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14181. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14182. ) then
  14183. begin
  14184. TransferUsedRegs(TmpUsedRegs);
  14185. hp2 := p;
  14186. repeat
  14187. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14188. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14189. if (
  14190. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14191. not (cs_opt_size in current_settings.optimizerswitches) or
  14192. (
  14193. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14194. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14195. )
  14196. ) then
  14197. begin
  14198. { Change the MOV instruction to a LEA instruction, and update the
  14199. first operand }
  14200. reference_reset(NewRef, 1, []);
  14201. NewRef.base := taicpu(p).oper[1]^.reg;
  14202. NewRef.scalefactor := 1;
  14203. NewRef.offset := -taicpu(p).oper[0]^.val;
  14204. taicpu(hp1).opcode := A_LEA;
  14205. taicpu(hp1).loadref(0, NewRef);
  14206. TransferUsedRegs(TmpUsedRegs);
  14207. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14208. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  14209. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14210. begin
  14211. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14212. { Move what is now the LEA instruction to before the SUB instruction }
  14213. Asml.Remove(hp1);
  14214. Asml.InsertBefore(hp1, p);
  14215. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14216. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14217. p := hp1;
  14218. end
  14219. else
  14220. begin
  14221. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14222. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14223. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14224. { hp1 may not be the immediate next instruction under -O3 }
  14225. RemoveCurrentp(p)
  14226. else
  14227. RemoveCurrentp(p, hp1);
  14228. end;
  14229. Result := True;
  14230. end;
  14231. end;
  14232. end;
  14233. end;
  14234. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14235. begin
  14236. { we can skip all instructions not messing with the stack pointer }
  14237. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14238. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14239. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14240. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14241. ({(taicpu(hp1).ops=0) or }
  14242. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14243. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14244. ) and }
  14245. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14246. )
  14247. ) do
  14248. GetNextInstruction(hp1,hp1);
  14249. Result:=assigned(hp1);
  14250. end;
  14251. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14252. var
  14253. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14254. begin
  14255. Result:=false;
  14256. hp5:=nil;
  14257. hp6:=nil;
  14258. hp7:=nil;
  14259. hp8:=nil;
  14260. { replace
  14261. leal(q) x(<stackpointer>),<stackpointer>
  14262. <optional .seh_stackalloc ...>
  14263. <optional .seh_endprologue ...>
  14264. call procname
  14265. <optional NOP>
  14266. leal(q) -x(<stackpointer>),<stackpointer>
  14267. <optional VZEROUPPER>
  14268. ret
  14269. by
  14270. jmp procname
  14271. but do it only on level 4 because it destroys stack back traces
  14272. }
  14273. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14274. MatchOpType(taicpu(p),top_ref,top_reg) and
  14275. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14276. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14277. { the -8, -24, -40 are not required, but bail out early if possible,
  14278. higher values are unlikely }
  14279. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14280. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14281. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14282. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14283. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14284. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14285. GetNextInstruction(p, hp1) and
  14286. { Take a copy of hp1 }
  14287. SetAndTest(hp1, hp4) and
  14288. { trick to skip label }
  14289. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14290. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14291. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14292. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14293. SkipSimpleInstructions(hp1) and
  14294. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14295. GetNextInstruction(hp1, hp2) and
  14296. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14297. { skip nop instruction on win64 }
  14298. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14299. SetAndTest(hp2,hp6) and
  14300. GetNextInstruction(hp2,hp2) and
  14301. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14302. ) and
  14303. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14304. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14305. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14306. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14307. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14308. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14309. { Segment register will be NR_NO }
  14310. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14311. GetNextInstruction(hp2, hp3) and
  14312. { trick to skip label }
  14313. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14314. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14315. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14316. SetAndTest(hp3,hp5) and
  14317. GetNextInstruction(hp3,hp3) and
  14318. MatchInstruction(hp3,A_RET,[S_NO])
  14319. )
  14320. ) and
  14321. (taicpu(hp3).ops=0) then
  14322. begin
  14323. taicpu(hp1).opcode := A_JMP;
  14324. taicpu(hp1).is_jmp := true;
  14325. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14326. { search for the stackalloc directive and remove it }
  14327. hp7:=tai(p.next);
  14328. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14329. begin
  14330. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14331. begin
  14332. { sanity check }
  14333. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14334. Internalerror(2024012201);
  14335. hp8:=tai(hp7.next);
  14336. RemoveInstruction(tai(hp7));
  14337. hp7:=hp8;
  14338. break;
  14339. end
  14340. else
  14341. hp7:=tai(hp7.next);
  14342. end;
  14343. RemoveCurrentP(p, hp4);
  14344. RemoveInstruction(hp2);
  14345. RemoveInstruction(hp3);
  14346. { if there is a vzeroupper instruction then move it before the jmp }
  14347. if Assigned(hp5) then
  14348. begin
  14349. AsmL.Remove(hp5);
  14350. ASmL.InsertBefore(hp5,hp1)
  14351. end;
  14352. { remove nop on win64 }
  14353. if Assigned(hp6) then
  14354. RemoveInstruction(hp6);
  14355. Result:=true;
  14356. end;
  14357. end;
  14358. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14359. {$ifdef x86_64}
  14360. var
  14361. hp1, hp2, hp3, hp4, hp5: tai;
  14362. {$endif x86_64}
  14363. begin
  14364. Result:=false;
  14365. {$ifdef x86_64}
  14366. hp5:=nil;
  14367. { replace
  14368. push %rax
  14369. call procname
  14370. pop %rcx
  14371. ret
  14372. by
  14373. jmp procname
  14374. but do it only on level 4 because it destroys stack back traces
  14375. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14376. for all supported calling conventions
  14377. }
  14378. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14379. MatchOpType(taicpu(p),top_reg) and
  14380. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14381. GetNextInstruction(p, hp1) and
  14382. { Take a copy of hp1 }
  14383. SetAndTest(hp1, hp4) and
  14384. { trick to skip label }
  14385. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14386. SkipSimpleInstructions(hp1) and
  14387. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14388. GetNextInstruction(hp1, hp2) and
  14389. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14390. MatchOpType(taicpu(hp2),top_reg) and
  14391. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14392. GetNextInstruction(hp2, hp3) and
  14393. { trick to skip label }
  14394. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14395. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14396. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14397. SetAndTest(hp3,hp5) and
  14398. GetNextInstruction(hp3,hp3) and
  14399. MatchInstruction(hp3,A_RET,[S_NO])
  14400. )
  14401. ) and
  14402. (taicpu(hp3).ops=0) then
  14403. begin
  14404. taicpu(hp1).opcode := A_JMP;
  14405. taicpu(hp1).is_jmp := true;
  14406. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14407. RemoveCurrentP(p, hp4);
  14408. RemoveInstruction(hp2);
  14409. RemoveInstruction(hp3);
  14410. if Assigned(hp5) then
  14411. begin
  14412. AsmL.Remove(hp5);
  14413. ASmL.InsertBefore(hp5,hp1)
  14414. end;
  14415. Result:=true;
  14416. end;
  14417. {$endif x86_64}
  14418. end;
  14419. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14420. var
  14421. Value, RegName: string;
  14422. hp1: tai;
  14423. begin
  14424. Result:=false;
  14425. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14426. begin
  14427. case taicpu(p).oper[0]^.val of
  14428. 0:
  14429. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14430. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14431. (
  14432. { See if we can still convert the instruction }
  14433. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14434. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14435. ) then
  14436. begin
  14437. { change "mov $0,%reg" into "xor %reg,%reg" }
  14438. taicpu(p).opcode := A_XOR;
  14439. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14440. Result := True;
  14441. {$ifdef x86_64}
  14442. end
  14443. else if (taicpu(p).opsize = S_Q) then
  14444. begin
  14445. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14446. { The actual optimization }
  14447. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14448. taicpu(p).changeopsize(S_L);
  14449. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14450. Result := True;
  14451. end;
  14452. $1..$FFFFFFFF:
  14453. begin
  14454. { Code size reduction by J. Gareth "Kit" Moreton }
  14455. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14456. case taicpu(p).opsize of
  14457. S_Q:
  14458. begin
  14459. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14460. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14461. { The actual optimization }
  14462. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14463. taicpu(p).changeopsize(S_L);
  14464. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14465. Result := True;
  14466. end;
  14467. else
  14468. { Do nothing };
  14469. end;
  14470. {$endif x86_64}
  14471. end;
  14472. -1:
  14473. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14474. if (cs_opt_size in current_settings.optimizerswitches) and
  14475. (taicpu(p).opsize <> S_B) and
  14476. (
  14477. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14478. (
  14479. { See if we can still convert the instruction }
  14480. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14481. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14482. )
  14483. ) then
  14484. begin
  14485. { change "mov $-1,%reg" into "or $-1,%reg" }
  14486. { NOTES:
  14487. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14488. - This operation creates a false dependency on the register, so only do it when optimising for size
  14489. - 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
  14490. }
  14491. taicpu(p).opcode := A_OR;
  14492. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14493. Result := True;
  14494. end;
  14495. else
  14496. { Do nothing };
  14497. end;
  14498. end;
  14499. end;
  14500. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14501. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14502. begin
  14503. Result := False;
  14504. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14505. Exit;
  14506. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14507. so don't bother optimising }
  14508. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14509. Exit;
  14510. if (taicpu(p).oper[0]^.typ <> top_const) or
  14511. { If the value can fit into an 8-bit signed integer, a smaller
  14512. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14513. falls within this range }
  14514. (
  14515. (taicpu(p).oper[0]^.val > -128) and
  14516. (taicpu(p).oper[0]^.val <= 127)
  14517. ) then
  14518. Exit;
  14519. { If we're optimising for size, this is acceptable }
  14520. if (cs_opt_size in current_settings.optimizerswitches) then
  14521. Exit(True);
  14522. if (taicpu(p).oper[1]^.typ = top_reg) and
  14523. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14524. Exit(True);
  14525. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14526. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14527. Exit(True);
  14528. end;
  14529. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14530. var
  14531. hp1: tai;
  14532. Value: TCGInt;
  14533. begin
  14534. Result := False;
  14535. if MatchOpType(taicpu(p), top_const, top_reg) then
  14536. begin
  14537. { Detect:
  14538. andw x, %ax (0 <= x < $8000)
  14539. ...
  14540. movzwl %ax,%eax
  14541. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14542. }
  14543. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  14544. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  14545. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  14546. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  14547. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  14548. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  14549. begin
  14550. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  14551. taicpu(hp1).opcode := A_CWDE;
  14552. taicpu(hp1).clearop(0);
  14553. taicpu(hp1).clearop(1);
  14554. taicpu(hp1).ops := 0;
  14555. { A change was made, but not with p, so don't set Result, but
  14556. notify the compiler that a change was made }
  14557. Include(OptsToCheck, aoc_ForceNewIteration);
  14558. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  14559. end;
  14560. end;
  14561. { If "not x" is a power of 2 (popcnt = 1), change:
  14562. and $x, %reg/ref
  14563. To:
  14564. btr lb(x), %reg/ref
  14565. }
  14566. if IsBTXAcceptable(p) and
  14567. (
  14568. { Make sure a TEST doesn't follow that plays with the register }
  14569. not GetNextInstruction(p, hp1) or
  14570. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  14571. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  14572. ) then
  14573. begin
  14574. {$push}{$R-}{$Q-}
  14575. { Value is a sign-extended 32-bit integer - just correct it
  14576. if it's represented as an unsigned value. Also, IsBTXAcceptable
  14577. checks to see if this operand is an immediate. }
  14578. Value := not taicpu(p).oper[0]^.val;
  14579. {$pop}
  14580. {$ifdef x86_64}
  14581. if taicpu(p).opsize = S_L then
  14582. {$endif x86_64}
  14583. Value := Value and $FFFFFFFF;
  14584. if (PopCnt(QWord(Value)) = 1) then
  14585. begin
  14586. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  14587. taicpu(p).opcode := A_BTR;
  14588. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  14589. Result := True;
  14590. Exit;
  14591. end;
  14592. end;
  14593. end;
  14594. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  14595. begin
  14596. Result := False;
  14597. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  14598. Exit;
  14599. { Convert:
  14600. movswl %ax,%eax -> cwtl
  14601. movslq %eax,%rax -> cdqe
  14602. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  14603. refer to the same opcode and depends only on the assembler's
  14604. current operand-size attribute. [Kit]
  14605. }
  14606. with taicpu(p) do
  14607. case opsize of
  14608. S_WL:
  14609. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  14610. begin
  14611. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  14612. opcode := A_CWDE;
  14613. clearop(0);
  14614. clearop(1);
  14615. ops := 0;
  14616. Result := True;
  14617. end;
  14618. {$ifdef x86_64}
  14619. S_LQ:
  14620. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  14621. begin
  14622. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  14623. opcode := A_CDQE;
  14624. clearop(0);
  14625. clearop(1);
  14626. ops := 0;
  14627. Result := True;
  14628. end;
  14629. {$endif x86_64}
  14630. else
  14631. ;
  14632. end;
  14633. end;
  14634. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  14635. var
  14636. hp1, hp2: tai;
  14637. IdentityMask, Shift: TCGInt;
  14638. LimitSize: Topsize;
  14639. DoNotMerge: Boolean;
  14640. begin
  14641. Result := False;
  14642. { All these optimisations work on "shr const,%reg" }
  14643. if not MatchOpType(taicpu(p), top_const, top_reg) then
  14644. Exit;
  14645. DoNotMerge := False;
  14646. Shift := taicpu(p).oper[0]^.val;
  14647. LimitSize := taicpu(p).opsize;
  14648. hp1 := p;
  14649. repeat
  14650. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  14651. Break;
  14652. { Detect:
  14653. shr x, %reg
  14654. and y, %reg
  14655. If and y, %reg doesn't actually change the value of %reg (e.g. with
  14656. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  14657. }
  14658. case taicpu(hp1).opcode of
  14659. A_AND:
  14660. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  14661. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14662. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  14663. begin
  14664. { Make sure the FLAGS register isn't in use }
  14665. TransferUsedRegs(TmpUsedRegs);
  14666. hp2 := p;
  14667. repeat
  14668. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  14669. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  14670. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  14671. begin
  14672. { Generate the identity mask }
  14673. case taicpu(p).opsize of
  14674. S_B:
  14675. IdentityMask := $FF shr Shift;
  14676. S_W:
  14677. IdentityMask := $FFFF shr Shift;
  14678. S_L:
  14679. IdentityMask := $FFFFFFFF shr Shift;
  14680. {$ifdef x86_64}
  14681. S_Q:
  14682. { We need to force the operands to be unsigned 64-bit
  14683. integers otherwise the wrong value is generated }
  14684. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  14685. {$endif x86_64}
  14686. else
  14687. InternalError(2022081501);
  14688. end;
  14689. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  14690. begin
  14691. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  14692. { All the possible 1 bits are covered, so we can remove the AND }
  14693. hp2 := tai(hp1.Previous);
  14694. RemoveInstruction(hp1);
  14695. { p wasn't actually changed, so don't set Result to True,
  14696. but a change was nonetheless made elsewhere }
  14697. Include(OptsToCheck, aoc_ForceNewIteration);
  14698. { Do another pass in case other AND or MOVZX instructions
  14699. follow }
  14700. hp1 := hp2;
  14701. Continue;
  14702. end;
  14703. end;
  14704. end;
  14705. A_TEST, A_CMP, A_Jcc:
  14706. { Skip over conditional jumps and relevant comparisons }
  14707. Continue;
  14708. A_MOVZX:
  14709. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14710. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  14711. begin
  14712. { Since the original register is being read as is, subsequent
  14713. SHRs must not be merged at this point }
  14714. DoNotMerge := True;
  14715. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  14716. begin
  14717. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14718. begin
  14719. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  14720. { All the possible 1 bits are covered, so we can remove the AND }
  14721. hp2 := tai(hp1.Previous);
  14722. RemoveInstruction(hp1);
  14723. hp1 := hp2;
  14724. end
  14725. else { Different register target }
  14726. begin
  14727. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  14728. taicpu(hp1).opcode := A_MOV;
  14729. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  14730. case taicpu(hp1).opsize of
  14731. S_BW:
  14732. taicpu(hp1).opsize := S_W;
  14733. S_BL, S_WL:
  14734. taicpu(hp1).opsize := S_L;
  14735. else
  14736. InternalError(2022081503);
  14737. end;
  14738. end;
  14739. end
  14740. else if (Shift > 0) and
  14741. (taicpu(p).opsize = S_W) and
  14742. (taicpu(hp1).opsize = S_WL) and
  14743. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  14744. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  14745. begin
  14746. { Detect:
  14747. shr x, %ax (x > 0)
  14748. ...
  14749. movzwl %ax,%eax
  14750. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14751. }
  14752. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  14753. taicpu(hp1).opcode := A_CWDE;
  14754. taicpu(hp1).clearop(0);
  14755. taicpu(hp1).clearop(1);
  14756. taicpu(hp1).ops := 0;
  14757. end;
  14758. { Move onto the next instruction }
  14759. Continue;
  14760. end;
  14761. A_SHL, A_SAL, A_SHR:
  14762. if (taicpu(hp1).opsize <= LimitSize) and
  14763. MatchOpType(taicpu(hp1), top_const, top_reg) and
  14764. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  14765. begin
  14766. { Make sure the sizes don't exceed the register size limit
  14767. (measured by the shift value falling below the limit) }
  14768. if taicpu(hp1).opsize < LimitSize then
  14769. LimitSize := taicpu(hp1).opsize;
  14770. if taicpu(hp1).opcode = A_SHR then
  14771. Inc(Shift, taicpu(hp1).oper[0]^.val)
  14772. else
  14773. begin
  14774. Dec(Shift, taicpu(hp1).oper[0]^.val);
  14775. DoNotMerge := True;
  14776. end;
  14777. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  14778. Break;
  14779. { Since we've established that the combined shift is within
  14780. limits, we can actually combine the adjacent SHR
  14781. instructions even if they're different sizes }
  14782. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  14783. begin
  14784. hp2 := tai(hp1.Previous);
  14785. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  14786. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  14787. RemoveInstruction(hp1);
  14788. hp1 := hp2;
  14789. end;
  14790. { Move onto the next instruction }
  14791. Continue;
  14792. end;
  14793. else
  14794. ;
  14795. end;
  14796. Break;
  14797. until False;
  14798. { Detect the following (looking backwards):
  14799. shr %cl,%reg
  14800. shr x, %reg
  14801. Swap the two SHR instructions to minimise a pipeline stall.
  14802. }
  14803. if GetLastInstruction(p, hp1) and
  14804. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  14805. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  14806. { First operand will be %cl }
  14807. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  14808. { Just to be sure }
  14809. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  14810. begin
  14811. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  14812. { Moving the entries this way ensures the register tracking remains correct }
  14813. Asml.Remove(p);
  14814. Asml.InsertBefore(p, hp1);
  14815. p := hp1;
  14816. { Don't set Result to True because the current instruction is now
  14817. "shr %cl,%reg" and there's nothing more we can do with it }
  14818. end;
  14819. end;
  14820. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  14821. var
  14822. hp1, hp2: tai;
  14823. Opposite, SecondOpposite: TAsmOp;
  14824. NewCond: TAsmCond;
  14825. begin
  14826. Result := False;
  14827. { Change:
  14828. add/sub 128,(dest)
  14829. To:
  14830. sub/add -128,(dest)
  14831. This generaally takes fewer bytes to encode because -128 can be stored
  14832. in a signed byte, whereas +128 cannot.
  14833. }
  14834. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  14835. begin
  14836. if taicpu(p).opcode = A_ADD then
  14837. Opposite := A_SUB
  14838. else
  14839. Opposite := A_ADD;
  14840. { Be careful if the flags are in use, because the CF flag inverts
  14841. when changing from ADD to SUB and vice versa }
  14842. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14843. GetNextInstruction(p, hp1) then
  14844. begin
  14845. TransferUsedRegs(TmpUsedRegs);
  14846. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  14847. hp2 := hp1;
  14848. { Scan ahead to check if everything's safe }
  14849. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  14850. begin
  14851. if (hp1.typ <> ait_instruction) then
  14852. { Probably unsafe since the flags are still in use }
  14853. Exit;
  14854. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  14855. { Stop searching at an unconditional jump }
  14856. Break;
  14857. if not
  14858. (
  14859. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  14860. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  14861. ) and
  14862. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  14863. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  14864. Exit;
  14865. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14866. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  14867. { Move to the next instruction }
  14868. GetNextInstruction(hp1, hp1);
  14869. end;
  14870. while Assigned(hp2) and (hp2 <> hp1) do
  14871. begin
  14872. NewCond := C_None;
  14873. case taicpu(hp2).condition of
  14874. C_A, C_NBE:
  14875. NewCond := C_BE;
  14876. C_B, C_C, C_NAE:
  14877. NewCond := C_AE;
  14878. C_AE, C_NB, C_NC:
  14879. NewCond := C_B;
  14880. C_BE, C_NA:
  14881. NewCond := C_A;
  14882. else
  14883. { No change needed };
  14884. end;
  14885. if NewCond <> C_None then
  14886. begin
  14887. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  14888. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  14889. taicpu(hp2).condition := NewCond;
  14890. end
  14891. else
  14892. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  14893. begin
  14894. { Because of the flipping of the carry bit, to ensure
  14895. the operation remains equivalent, ADC becomes SBB
  14896. and vice versa, and the constant is not-inverted.
  14897. If multiple ADCs or SBBs appear in a row, each one
  14898. changed causes the carry bit to invert, so they all
  14899. need to be flipped }
  14900. if taicpu(hp2).opcode = A_ADC then
  14901. SecondOpposite := A_SBB
  14902. else
  14903. SecondOpposite := A_ADC;
  14904. if taicpu(hp2).oper[0]^.typ <> top_const then
  14905. { Should have broken out of this optimisation already }
  14906. InternalError(2021112901);
  14907. 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]^) + ' -> ' +
  14908. 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);
  14909. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  14910. taicpu(hp2).opcode := SecondOpposite;
  14911. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  14912. end;
  14913. { Move to the next instruction }
  14914. GetNextInstruction(hp2, hp2);
  14915. end;
  14916. if (hp2 <> hp1) then
  14917. InternalError(2021111501);
  14918. end;
  14919. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  14920. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  14921. taicpu(p).opcode := Opposite;
  14922. taicpu(p).oper[0]^.val := -128;
  14923. { No further optimisations can be made on this instruction, so move
  14924. onto the next one to save time }
  14925. p := tai(p.Next);
  14926. UpdateUsedRegs(p);
  14927. Result := True;
  14928. Exit;
  14929. end;
  14930. { Detect:
  14931. add/sub %reg2,(dest)
  14932. add/sub x, (dest)
  14933. (dest can be a register or a reference)
  14934. Swap the instructions to minimise a pipeline stall. This reverses the
  14935. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  14936. optimisations could be made.
  14937. }
  14938. if (taicpu(p).oper[0]^.typ = top_reg) and
  14939. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  14940. (
  14941. (
  14942. (taicpu(p).oper[1]^.typ = top_reg) and
  14943. { We can try searching further ahead if we're writing to a register }
  14944. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  14945. ) or
  14946. (
  14947. (taicpu(p).oper[1]^.typ = top_ref) and
  14948. GetNextInstruction(p, hp1)
  14949. )
  14950. ) and
  14951. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  14952. (taicpu(hp1).oper[0]^.typ = top_const) and
  14953. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  14954. begin
  14955. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  14956. TransferUsedRegs(TmpUsedRegs);
  14957. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  14958. hp2 := p;
  14959. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  14960. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  14961. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  14962. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14963. begin
  14964. asml.remove(hp1);
  14965. asml.InsertBefore(hp1, p);
  14966. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  14967. Result := True;
  14968. end;
  14969. end;
  14970. end;
  14971. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  14972. var
  14973. hp1: tai;
  14974. begin
  14975. Result:=false;
  14976. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  14977. while GetNextInstruction(p, hp1) and
  14978. TrySwapMovCmp(p, hp1) do
  14979. begin
  14980. if MatchInstruction(hp1, A_MOV, []) then
  14981. begin
  14982. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14983. begin
  14984. { A little hacky, but since CMP doesn't read the flags, only
  14985. modify them, it's safe if they get scrambled by MOV -> XOR }
  14986. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14987. Result := PostPeepholeOptMov(hp1);
  14988. {$ifdef x86_64}
  14989. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14990. { Used to shrink instruction size }
  14991. PostPeepholeOptXor(hp1);
  14992. {$endif x86_64}
  14993. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14994. end
  14995. else
  14996. begin
  14997. Result := PostPeepholeOptMov(hp1);
  14998. {$ifdef x86_64}
  14999. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15000. { Used to shrink instruction size }
  15001. PostPeepholeOptXor(hp1);
  15002. {$endif x86_64}
  15003. end;
  15004. end;
  15005. { Enabling this flag is actually a null operation, but it marks
  15006. the code as 'modified' during this pass }
  15007. Include(OptsToCheck, aoc_ForceNewIteration);
  15008. end;
  15009. { change "cmp $0, %reg" to "test %reg, %reg" }
  15010. if MatchOpType(taicpu(p),top_const,top_reg) and
  15011. (taicpu(p).oper[0]^.val = 0) then
  15012. begin
  15013. taicpu(p).opcode := A_TEST;
  15014. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15015. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15016. Result:=true;
  15017. end;
  15018. end;
  15019. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15020. var
  15021. IsTestConstX, IsValid : Boolean;
  15022. hp1,hp2 : tai;
  15023. begin
  15024. Result:=false;
  15025. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15026. if (taicpu(p).opcode = A_TEST) then
  15027. while GetNextInstruction(p, hp1) and
  15028. TrySwapMovCmp(p, hp1) do
  15029. begin
  15030. if MatchInstruction(hp1, A_MOV, []) then
  15031. begin
  15032. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15033. begin
  15034. { A little hacky, but since TEST doesn't read the flags, only
  15035. modify them, it's safe if they get scrambled by MOV -> XOR }
  15036. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15037. Result := PostPeepholeOptMov(hp1);
  15038. {$ifdef x86_64}
  15039. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15040. { Used to shrink instruction size }
  15041. PostPeepholeOptXor(hp1);
  15042. {$endif x86_64}
  15043. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15044. end
  15045. else
  15046. begin
  15047. Result := PostPeepholeOptMov(hp1);
  15048. {$ifdef x86_64}
  15049. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15050. { Used to shrink instruction size }
  15051. PostPeepholeOptXor(hp1);
  15052. {$endif x86_64}
  15053. end;
  15054. end;
  15055. { Enabling this flag is actually a null operation, but it marks
  15056. the code as 'modified' during this pass }
  15057. Include(OptsToCheck, aoc_ForceNewIteration);
  15058. end;
  15059. { If x is a power of 2 (popcnt = 1), change:
  15060. or $x, %reg/ref
  15061. To:
  15062. bts lb(x), %reg/ref
  15063. }
  15064. if (taicpu(p).opcode = A_OR) and
  15065. IsBTXAcceptable(p) and
  15066. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15067. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15068. (
  15069. { Don't optimise if a test instruction follows }
  15070. not GetNextInstruction(p, hp1) or
  15071. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15072. ) then
  15073. begin
  15074. 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);
  15075. taicpu(p).opcode := A_BTS;
  15076. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15077. Result := True;
  15078. Exit;
  15079. end;
  15080. { If x is a power of 2 (popcnt = 1), change:
  15081. test $x, %reg/ref
  15082. je / sete / cmove (or jne / setne)
  15083. To:
  15084. bt lb(x), %reg/ref
  15085. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15086. }
  15087. if (taicpu(p).opcode = A_TEST) and
  15088. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15089. (taicpu(p).oper[0]^.typ = top_const) and
  15090. (
  15091. (cs_opt_size in current_settings.optimizerswitches) or
  15092. (
  15093. (taicpu(p).oper[1]^.typ = top_reg) and
  15094. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15095. ) or
  15096. (
  15097. (taicpu(p).oper[1]^.typ <> top_reg) and
  15098. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15099. )
  15100. ) and
  15101. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15102. { For sizes less than S_L, the byte size is equal or larger with BT,
  15103. so don't bother optimising }
  15104. (taicpu(p).opsize >= S_L) then
  15105. begin
  15106. IsValid := True;
  15107. { Check the next set of instructions, watching the FLAGS register
  15108. and the conditions used }
  15109. TransferUsedRegs(TmpUsedRegs);
  15110. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15111. hp1 := p;
  15112. hp2 := nil;
  15113. while GetNextInstruction(hp1, hp1) do
  15114. begin
  15115. if not Assigned(hp2) then
  15116. { The first instruction after TEST }
  15117. hp2 := hp1;
  15118. if (hp1.typ <> ait_instruction) then
  15119. begin
  15120. { If the flags are no longer in use, everything is fine }
  15121. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15122. IsValid := False;
  15123. Break;
  15124. end;
  15125. case taicpu(hp1).condition of
  15126. C_None:
  15127. begin
  15128. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15129. { Something is not quite normal, so play safe and don't change }
  15130. IsValid := False;
  15131. Break;
  15132. end;
  15133. C_E, C_Z, C_NE, C_NZ:
  15134. { This is fine };
  15135. else
  15136. begin
  15137. { Unsupported condition }
  15138. IsValid := False;
  15139. Break;
  15140. end;
  15141. end;
  15142. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15143. end;
  15144. if IsValid then
  15145. begin
  15146. while hp2 <> hp1 do
  15147. begin
  15148. case taicpu(hp2).condition of
  15149. C_Z, C_E:
  15150. taicpu(hp2).condition := C_NC;
  15151. C_NZ, C_NE:
  15152. taicpu(hp2).condition := C_C;
  15153. else
  15154. { Should not get this by this point }
  15155. InternalError(2022110701);
  15156. end;
  15157. GetNextInstruction(hp2, hp2);
  15158. end;
  15159. 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);
  15160. taicpu(p).opcode := A_BT;
  15161. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15162. Result := True;
  15163. Exit;
  15164. end;
  15165. end;
  15166. { removes the line marked with (x) from the sequence
  15167. and/or/xor/add/sub/... $x, %y
  15168. test/or %y, %y | test $-1, %y (x)
  15169. j(n)z _Label
  15170. as the first instruction already adjusts the ZF
  15171. %y operand may also be a reference }
  15172. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15173. MatchOperand(taicpu(p).oper[0]^,-1);
  15174. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15175. GetLastInstruction(p, hp1) and
  15176. (tai(hp1).typ = ait_instruction) and
  15177. GetNextInstruction(p,hp2) and
  15178. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15179. case taicpu(hp1).opcode Of
  15180. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15181. { These two instructions set the zero flag if the result is zero }
  15182. A_POPCNT, A_LZCNT:
  15183. begin
  15184. if (
  15185. { With POPCNT, an input of zero will set the zero flag
  15186. because the population count of zero is zero }
  15187. (taicpu(hp1).opcode = A_POPCNT) and
  15188. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15189. (
  15190. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15191. { Faster than going through the second half of the 'or'
  15192. condition below }
  15193. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15194. )
  15195. ) or (
  15196. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15197. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15198. { and in case of carry for A(E)/B(E)/C/NC }
  15199. (
  15200. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15201. (
  15202. (taicpu(hp1).opcode <> A_ADD) and
  15203. (taicpu(hp1).opcode <> A_SUB) and
  15204. (taicpu(hp1).opcode <> A_LZCNT)
  15205. )
  15206. )
  15207. ) then
  15208. begin
  15209. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15210. RemoveCurrentP(p, hp2);
  15211. Result:=true;
  15212. Exit;
  15213. end;
  15214. end;
  15215. A_SHL, A_SAL, A_SHR, A_SAR:
  15216. begin
  15217. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15218. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15219. { therefore, it's only safe to do this optimization for }
  15220. { shifts by a (nonzero) constant }
  15221. (taicpu(hp1).oper[0]^.typ = top_const) and
  15222. (taicpu(hp1).oper[0]^.val <> 0) and
  15223. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15224. { and in case of carry for A(E)/B(E)/C/NC }
  15225. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15226. begin
  15227. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15228. RemoveCurrentP(p, hp2);
  15229. Result:=true;
  15230. Exit;
  15231. end;
  15232. end;
  15233. A_DEC, A_INC, A_NEG:
  15234. begin
  15235. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15236. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15237. { and in case of carry for A(E)/B(E)/C/NC }
  15238. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15239. begin
  15240. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15241. RemoveCurrentP(p, hp2);
  15242. Result:=true;
  15243. Exit;
  15244. end;
  15245. end;
  15246. A_ANDN, A_BZHI:
  15247. begin
  15248. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15249. { Only the zero and sign flags are consistent with what the result is }
  15250. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15251. begin
  15252. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15253. RemoveCurrentP(p, hp2);
  15254. Result:=true;
  15255. Exit;
  15256. end;
  15257. end;
  15258. A_BEXTR:
  15259. begin
  15260. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15261. { Only the zero flag is set }
  15262. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15263. begin
  15264. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15265. RemoveCurrentP(p, hp2);
  15266. Result:=true;
  15267. Exit;
  15268. end;
  15269. end;
  15270. else
  15271. ;
  15272. end; { case }
  15273. { change "test $-1,%reg" into "test %reg,%reg" }
  15274. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15275. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15276. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15277. if MatchInstruction(p, A_OR, []) and
  15278. { Can only match if they're both registers }
  15279. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15280. begin
  15281. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15282. taicpu(p).opcode := A_TEST;
  15283. { No need to set Result to True, as we've done all the optimisations we can }
  15284. end;
  15285. end;
  15286. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15287. var
  15288. hp1,hp3 : tai;
  15289. {$ifndef x86_64}
  15290. hp2 : taicpu;
  15291. {$endif x86_64}
  15292. begin
  15293. Result:=false;
  15294. hp3:=nil;
  15295. {$ifndef x86_64}
  15296. { don't do this on modern CPUs, this really hurts them due to
  15297. broken call/ret pairing }
  15298. if (current_settings.optimizecputype < cpu_Pentium2) and
  15299. not(cs_create_pic in current_settings.moduleswitches) and
  15300. GetNextInstruction(p, hp1) and
  15301. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15302. MatchOpType(taicpu(hp1),top_ref) and
  15303. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15304. begin
  15305. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15306. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15307. InsertLLItem(p.previous, p, hp2);
  15308. taicpu(p).opcode := A_JMP;
  15309. taicpu(p).is_jmp := true;
  15310. RemoveInstruction(hp1);
  15311. Result:=true;
  15312. end
  15313. else
  15314. {$endif x86_64}
  15315. { replace
  15316. call procname
  15317. ret
  15318. by
  15319. jmp procname
  15320. but do it only on level 4 because it destroys stack back traces
  15321. else if the subroutine is marked as no return, remove the ret
  15322. }
  15323. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15324. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15325. GetNextInstruction(p, hp1) and
  15326. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15327. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15328. SetAndTest(hp1,hp3) and
  15329. GetNextInstruction(hp1,hp1) and
  15330. MatchInstruction(hp1,A_RET,[S_NO])
  15331. )
  15332. ) and
  15333. (taicpu(hp1).ops=0) then
  15334. begin
  15335. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15336. { we might destroy stack alignment here if we do not do a call }
  15337. (target_info.stackalign<=sizeof(SizeUInt)) then
  15338. begin
  15339. taicpu(p).opcode := A_JMP;
  15340. taicpu(p).is_jmp := true;
  15341. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15342. end
  15343. else
  15344. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15345. RemoveInstruction(hp1);
  15346. if Assigned(hp3) then
  15347. begin
  15348. AsmL.Remove(hp3);
  15349. AsmL.InsertBefore(hp3,p)
  15350. end;
  15351. Result:=true;
  15352. end;
  15353. end;
  15354. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15355. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15356. begin
  15357. case OpSize of
  15358. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15359. Result := (Val <= $FF) and (Val >= -128);
  15360. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15361. Result := (Val <= $FFFF) and (Val >= -32768);
  15362. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15363. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15364. else
  15365. Result := True;
  15366. end;
  15367. end;
  15368. var
  15369. hp1, hp2 : tai;
  15370. SizeChange: Boolean;
  15371. PreMessage: string;
  15372. begin
  15373. Result := False;
  15374. if (taicpu(p).oper[0]^.typ = top_reg) and
  15375. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15376. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15377. begin
  15378. { Change (using movzbl %al,%eax as an example):
  15379. movzbl %al, %eax movzbl %al, %eax
  15380. cmpl x, %eax testl %eax,%eax
  15381. To:
  15382. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15383. movzbl %al, %eax movzbl %al, %eax
  15384. Smaller instruction and minimises pipeline stall as the CPU
  15385. doesn't have to wait for the register to get zero-extended. [Kit]
  15386. Also allow if the smaller of the two registers is being checked,
  15387. as this still removes the false dependency.
  15388. }
  15389. if
  15390. (
  15391. (
  15392. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15393. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15394. ) or (
  15395. { If MatchOperand returns True, they must both be registers }
  15396. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15397. )
  15398. ) and
  15399. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15400. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15401. begin
  15402. 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);
  15403. asml.Remove(hp1);
  15404. asml.InsertBefore(hp1, p);
  15405. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15406. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15407. begin
  15408. taicpu(hp1).opcode := A_TEST;
  15409. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15410. end;
  15411. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15412. case taicpu(p).opsize of
  15413. S_BW, S_BL:
  15414. begin
  15415. SizeChange := taicpu(hp1).opsize <> S_B;
  15416. taicpu(hp1).changeopsize(S_B);
  15417. end;
  15418. S_WL:
  15419. begin
  15420. SizeChange := taicpu(hp1).opsize <> S_W;
  15421. taicpu(hp1).changeopsize(S_W);
  15422. end
  15423. else
  15424. InternalError(2020112701);
  15425. end;
  15426. UpdateUsedRegs(tai(p.Next));
  15427. { Check if the register is used aferwards - if not, we can
  15428. remove the movzx instruction completely }
  15429. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15430. begin
  15431. { Hp1 is a better position than p for debugging purposes }
  15432. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15433. RemoveCurrentp(p, hp1);
  15434. Result := True;
  15435. end;
  15436. if SizeChange then
  15437. DebugMsg(SPeepholeOptimization + PreMessage +
  15438. 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)
  15439. else
  15440. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15441. Exit;
  15442. end;
  15443. { Change (using movzwl %ax,%eax as an example):
  15444. movzwl %ax, %eax
  15445. movb %al, (dest) (Register is smaller than read register in movz)
  15446. To:
  15447. movb %al, (dest) (Move one back to avoid a false dependency)
  15448. movzwl %ax, %eax
  15449. }
  15450. if (taicpu(hp1).opcode = A_MOV) and
  15451. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15452. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15453. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15454. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15455. begin
  15456. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15457. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15458. asml.Remove(hp1);
  15459. asml.InsertBefore(hp1, p);
  15460. if taicpu(hp1).oper[1]^.typ = top_reg then
  15461. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15462. { Check if the register is used aferwards - if not, we can
  15463. remove the movzx instruction completely }
  15464. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15465. begin
  15466. { Hp1 is a better position than p for debugging purposes }
  15467. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15468. RemoveCurrentp(p, hp1);
  15469. Result := True;
  15470. end;
  15471. Exit;
  15472. end;
  15473. end;
  15474. end;
  15475. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15476. var
  15477. hp1: tai;
  15478. {$ifdef x86_64}
  15479. PreMessage, RegName: string;
  15480. {$endif x86_64}
  15481. begin
  15482. Result := False;
  15483. { If x is a power of 2 (popcnt = 1), change:
  15484. xor $x, %reg/ref
  15485. To:
  15486. btc lb(x), %reg/ref
  15487. }
  15488. if IsBTXAcceptable(p) and
  15489. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15490. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15491. (
  15492. { Don't optimise if a test instruction follows }
  15493. not GetNextInstruction(p, hp1) or
  15494. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15495. ) then
  15496. begin
  15497. 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);
  15498. taicpu(p).opcode := A_BTC;
  15499. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15500. Result := True;
  15501. Exit;
  15502. end;
  15503. {$ifdef x86_64}
  15504. { Code size reduction by J. Gareth "Kit" Moreton }
  15505. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15506. as this removes the REX prefix }
  15507. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15508. Exit;
  15509. if taicpu(p).oper[0]^.typ <> top_reg then
  15510. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15511. InternalError(2018011500);
  15512. case taicpu(p).opsize of
  15513. S_Q:
  15514. begin
  15515. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15516. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15517. { The actual optimization }
  15518. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15519. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15520. taicpu(p).changeopsize(S_L);
  15521. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15522. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15523. end;
  15524. else
  15525. ;
  15526. end;
  15527. {$endif x86_64}
  15528. end;
  15529. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15530. var
  15531. XReg: TRegister;
  15532. begin
  15533. Result := False;
  15534. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15535. Smaller encoding and slightly faster on some platforms (also works for
  15536. ZMM-sized registers) }
  15537. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15538. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15539. begin
  15540. XReg := taicpu(p).oper[0]^.reg;
  15541. if (taicpu(p).oper[1]^.reg = XReg) then
  15542. begin
  15543. taicpu(p).changeopsize(S_XMM);
  15544. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15545. if (cs_opt_size in current_settings.optimizerswitches) then
  15546. begin
  15547. { Change input registers to %xmm0 to reduce size. Note that
  15548. there's a risk of a false dependency doing this, so only
  15549. optimise for size here }
  15550. XReg := NR_XMM0;
  15551. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15552. end
  15553. else
  15554. begin
  15555. setsubreg(XReg, R_SUBMMX);
  15556. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15557. end;
  15558. taicpu(p).oper[0]^.reg := XReg;
  15559. taicpu(p).oper[1]^.reg := XReg;
  15560. Result := True;
  15561. end;
  15562. end;
  15563. end;
  15564. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15565. var
  15566. OperIdx: Integer;
  15567. begin
  15568. for OperIdx := 0 to p.ops - 1 do
  15569. if p.oper[OperIdx]^.typ = top_ref then
  15570. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15571. end;
  15572. end.