aoptx86.pas 698 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. { Handle instructions that behave differently depending on the size and operand count }
  861. case taicpu(p1).opcode of
  862. A_MUL, A_DIV, A_IDIV:
  863. if taicpu(p1).opsize = S_B then
  864. Result := (getsupreg(Reg) = RS_EAX)
  865. else
  866. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  867. A_IMUL:
  868. if taicpu(p1).ops = 1 then
  869. begin
  870. if taicpu(p1).opsize = S_B then
  871. Result := (getsupreg(Reg) = RS_EAX)
  872. else
  873. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  874. end;
  875. { If ops are greater than 1, call inherited method }
  876. else
  877. case getsupreg(reg) of
  878. { RS_EAX = RS_RAX on x86-64 }
  879. RS_EAX:
  880. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  881. RS_ECX:
  882. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  883. RS_EDX:
  884. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  885. RS_EBX:
  886. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  887. RS_ESP:
  888. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. RS_EBP:
  890. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  891. RS_ESI:
  892. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  893. RS_EDI:
  894. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. else
  896. ;
  897. end;
  898. end;
  899. if result then
  900. exit;
  901. end
  902. else if getregtype(reg)=R_MMREGISTER then
  903. begin
  904. case getsupreg(reg) of
  905. RS_XMM0:
  906. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. else
  908. ;
  909. end;
  910. if result then
  911. exit;
  912. end
  913. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  914. begin
  915. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  916. exit(true);
  917. case getsubreg(reg) of
  918. R_SUBFLAGCARRY:
  919. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  920. R_SUBFLAGPARITY:
  921. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  922. R_SUBFLAGAUXILIARY:
  923. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  924. R_SUBFLAGZERO:
  925. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. R_SUBFLAGSIGN:
  927. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  928. R_SUBFLAGOVERFLOW:
  929. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  930. R_SUBFLAGINTERRUPT:
  931. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  932. R_SUBFLAGDIRECTION:
  933. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  934. R_SUBW,R_SUBD,R_SUBQ:
  935. { Everything except the direction bits }
  936. Result:=
  937. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  938. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  939. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  940. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  941. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  942. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  943. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  944. else
  945. ;
  946. end;
  947. if result then
  948. exit;
  949. end
  950. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  951. exit(true);
  952. Result:=inherited RegInInstruction(Reg, p1);
  953. end;
  954. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  955. const
  956. WriteOps: array[0..3] of set of TInsChange =
  957. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  958. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  959. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  960. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  961. var
  962. OperIdx: Integer;
  963. begin
  964. Result := False;
  965. if p1.typ <> ait_instruction then
  966. exit;
  967. with insprop[taicpu(p1).opcode] do
  968. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  969. begin
  970. case getsubreg(reg) of
  971. R_SUBW,R_SUBD,R_SUBQ:
  972. Result :=
  973. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  974. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  975. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  976. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  977. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  978. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  979. R_SUBFLAGCARRY:
  980. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  981. R_SUBFLAGPARITY:
  982. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  983. R_SUBFLAGAUXILIARY:
  984. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  985. R_SUBFLAGZERO:
  986. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  987. R_SUBFLAGSIGN:
  988. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  989. R_SUBFLAGOVERFLOW:
  990. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  991. R_SUBFLAGINTERRUPT:
  992. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  993. R_SUBFLAGDIRECTION:
  994. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  995. else
  996. internalerror(2017042602);
  997. end;
  998. exit;
  999. end;
  1000. case taicpu(p1).opcode of
  1001. A_CALL:
  1002. { We could potentially set Result to False if the register in
  1003. question is non-volatile for the subroutine's calling convention,
  1004. but this would require detecting the calling convention in use and
  1005. also assuming that the routine doesn't contain malformed assembly
  1006. language, for example... so it could only be done under -O4 as it
  1007. would be considered a side-effect. [Kit] }
  1008. Result := True;
  1009. A_MOVSD:
  1010. { special handling for SSE MOVSD }
  1011. if (taicpu(p1).ops>0) then
  1012. begin
  1013. if taicpu(p1).ops<>2 then
  1014. internalerror(2017042703);
  1015. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1016. end;
  1017. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1018. so fix it here (FK)
  1019. }
  1020. A_VMOVSS,
  1021. A_VMOVSD:
  1022. begin
  1023. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1024. exit;
  1025. end;
  1026. A_MUL, A_DIV, A_IDIV:
  1027. begin
  1028. if taicpu(p1).opsize = S_B then
  1029. Result := (getsupreg(Reg) = RS_EAX)
  1030. else
  1031. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1032. end;
  1033. A_IMUL:
  1034. begin
  1035. if taicpu(p1).ops = 1 then
  1036. begin
  1037. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1038. end
  1039. else
  1040. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1041. Exit;
  1042. end;
  1043. else
  1044. ;
  1045. end;
  1046. if Result then
  1047. exit;
  1048. with insprop[taicpu(p1).opcode] do
  1049. begin
  1050. if getregtype(reg)=R_INTREGISTER then
  1051. begin
  1052. case getsupreg(reg) of
  1053. RS_EAX:
  1054. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_ECX:
  1060. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. RS_EDX:
  1066. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1067. begin
  1068. Result := True;
  1069. exit
  1070. end;
  1071. RS_EBX:
  1072. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1073. begin
  1074. Result := True;
  1075. exit
  1076. end;
  1077. RS_ESP:
  1078. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1079. begin
  1080. Result := True;
  1081. exit
  1082. end;
  1083. RS_EBP:
  1084. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1085. begin
  1086. Result := True;
  1087. exit
  1088. end;
  1089. RS_ESI:
  1090. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1091. begin
  1092. Result := True;
  1093. exit
  1094. end;
  1095. RS_EDI:
  1096. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1097. begin
  1098. Result := True;
  1099. exit
  1100. end;
  1101. end;
  1102. end;
  1103. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1104. if (WriteOps[OperIdx]*Ch<>[]) and
  1105. { The register doesn't get modified inside a reference }
  1106. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1107. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1108. begin
  1109. Result := true;
  1110. exit
  1111. end;
  1112. end;
  1113. end;
  1114. {$ifdef DEBUG_AOPTCPU}
  1115. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1116. begin
  1117. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1118. end;
  1119. function debug_tostr(i: tcgint): string; inline;
  1120. begin
  1121. Result := tostr(i);
  1122. end;
  1123. function debug_hexstr(i: tcgint): string;
  1124. begin
  1125. Result := '0x';
  1126. case i of
  1127. 0..$FF:
  1128. Result := Result + hexstr(i, 2);
  1129. $100..$FFFF:
  1130. Result := Result + hexstr(i, 4);
  1131. $10000..$FFFFFF:
  1132. Result := Result + hexstr(i, 6);
  1133. $1000000..$FFFFFFFF:
  1134. Result := Result + hexstr(i, 8);
  1135. else
  1136. Result := Result + hexstr(i, 16);
  1137. end;
  1138. end;
  1139. function debug_regname(r: TRegister): string; inline;
  1140. begin
  1141. Result := '%' + std_regname(r);
  1142. end;
  1143. { Debug output function - creates a string representation of an operator }
  1144. function debug_operstr(oper: TOper): string;
  1145. begin
  1146. case oper.typ of
  1147. top_const:
  1148. Result := '$' + debug_tostr(oper.val);
  1149. top_reg:
  1150. Result := debug_regname(oper.reg);
  1151. top_ref:
  1152. begin
  1153. if oper.ref^.offset <> 0 then
  1154. Result := debug_tostr(oper.ref^.offset) + '('
  1155. else
  1156. Result := '(';
  1157. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1158. begin
  1159. Result := Result + debug_regname(oper.ref^.base);
  1160. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1161. Result := Result + ',' + debug_regname(oper.ref^.index);
  1162. end
  1163. else
  1164. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1165. Result := Result + debug_regname(oper.ref^.index);
  1166. if (oper.ref^.scalefactor > 1) then
  1167. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1168. else
  1169. Result := Result + ')';
  1170. end;
  1171. else
  1172. Result := '[UNKNOWN]';
  1173. end;
  1174. end;
  1175. function debug_op2str(opcode: tasmop): string; inline;
  1176. begin
  1177. Result := std_op2str[opcode];
  1178. end;
  1179. function debug_opsize2str(opsize: topsize): string; inline;
  1180. begin
  1181. Result := gas_opsize2str[opsize];
  1182. end;
  1183. {$else DEBUG_AOPTCPU}
  1184. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1185. begin
  1186. end;
  1187. function debug_tostr(i: tcgint): string; inline;
  1188. begin
  1189. Result := '';
  1190. end;
  1191. function debug_hexstr(i: tcgint): string; inline;
  1192. begin
  1193. Result := '';
  1194. end;
  1195. function debug_regname(r: TRegister): string; inline;
  1196. begin
  1197. Result := '';
  1198. end;
  1199. function debug_operstr(oper: TOper): string; inline;
  1200. begin
  1201. Result := '';
  1202. end;
  1203. function debug_op2str(opcode: tasmop): string; inline;
  1204. begin
  1205. Result := '';
  1206. end;
  1207. function debug_opsize2str(opsize: topsize): string; inline;
  1208. begin
  1209. Result := '';
  1210. end;
  1211. {$endif DEBUG_AOPTCPU}
  1212. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1213. begin
  1214. {$ifdef x86_64}
  1215. { Always fine on x86-64 }
  1216. Result := True;
  1217. {$else x86_64}
  1218. Result :=
  1219. {$ifdef i8086}
  1220. (current_settings.cputype >= cpu_386) and
  1221. {$endif i8086}
  1222. (
  1223. { Always accept if optimising for size }
  1224. (cs_opt_size in current_settings.optimizerswitches) or
  1225. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1226. (current_settings.optimizecputype >= cpu_Pentium2)
  1227. );
  1228. {$endif x86_64}
  1229. end;
  1230. { Attempts to allocate a volatile integer register for use between p and hp,
  1231. using AUsedRegs for the current register usage information. Returns NR_NO
  1232. if no free register could be found }
  1233. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1234. var
  1235. RegSet: TCPURegisterSet;
  1236. CurrentSuperReg: Integer;
  1237. CurrentReg: TRegister;
  1238. Currentp: tai;
  1239. Breakout: Boolean;
  1240. begin
  1241. Result := NR_NO;
  1242. RegSet :=
  1243. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1244. current_procinfo.saved_regs_int;
  1245. (*
  1246. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1247. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1248. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1249. *)
  1250. for CurrentSuperReg in RegSet do
  1251. begin
  1252. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1253. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1254. {$if defined(i386) or defined(i8086)}
  1255. { If the target size is 8-bit, make sure we can actually encode it }
  1256. and (
  1257. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1258. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1259. )
  1260. {$endif i386 or i8086}
  1261. then
  1262. begin
  1263. Currentp := p;
  1264. Breakout := False;
  1265. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1266. begin
  1267. case Currentp.typ of
  1268. ait_instruction:
  1269. begin
  1270. if RegInInstruction(CurrentReg, Currentp) then
  1271. begin
  1272. Breakout := True;
  1273. Break;
  1274. end;
  1275. { Cannot allocate across an unconditional jump }
  1276. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1277. Exit;
  1278. end;
  1279. ait_marker:
  1280. { Don't try anything more if a marker is hit }
  1281. Exit;
  1282. ait_regalloc:
  1283. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1284. begin
  1285. Breakout := True;
  1286. Break;
  1287. end;
  1288. else
  1289. ;
  1290. end;
  1291. end;
  1292. if Breakout then
  1293. { Try the next register }
  1294. Continue;
  1295. { We have a free register available }
  1296. Result := CurrentReg;
  1297. if not DontAlloc then
  1298. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1299. Exit;
  1300. end;
  1301. end;
  1302. end;
  1303. { Attempts to allocate a volatile MM register for use between p and hp,
  1304. using AUsedRegs for the current register usage information. Returns NR_NO
  1305. if no free register could be found }
  1306. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1307. var
  1308. RegSet: TCPURegisterSet;
  1309. CurrentSuperReg: Integer;
  1310. CurrentReg: TRegister;
  1311. Currentp: tai;
  1312. Breakout: Boolean;
  1313. begin
  1314. Result := NR_NO;
  1315. RegSet :=
  1316. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1317. current_procinfo.saved_regs_mm;
  1318. for CurrentSuperReg in RegSet do
  1319. begin
  1320. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1321. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1322. begin
  1323. Currentp := p;
  1324. Breakout := False;
  1325. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1326. begin
  1327. case Currentp.typ of
  1328. ait_instruction:
  1329. begin
  1330. if RegInInstruction(CurrentReg, Currentp) then
  1331. begin
  1332. Breakout := True;
  1333. Break;
  1334. end;
  1335. { Cannot allocate across an unconditional jump }
  1336. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1337. Exit;
  1338. end;
  1339. ait_marker:
  1340. { Don't try anything more if a marker is hit }
  1341. Exit;
  1342. ait_regalloc:
  1343. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1344. begin
  1345. Breakout := True;
  1346. Break;
  1347. end;
  1348. else
  1349. ;
  1350. end;
  1351. end;
  1352. if Breakout then
  1353. { Try the next register }
  1354. Continue;
  1355. { We have a free register available }
  1356. Result := CurrentReg;
  1357. if not DontAlloc then
  1358. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1359. Exit;
  1360. end;
  1361. end;
  1362. end;
  1363. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1364. begin
  1365. if not SuperRegistersEqual(reg1,reg2) then
  1366. exit(false);
  1367. if getregtype(reg1)<>R_INTREGISTER then
  1368. exit(true); {because SuperRegisterEqual is true}
  1369. case getsubreg(reg1) of
  1370. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1371. higher, it preserves the high bits, so the new value depends on
  1372. reg2's previous value. In other words, it is equivalent to doing:
  1373. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1374. R_SUBL:
  1375. exit(getsubreg(reg2)=R_SUBL);
  1376. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1377. higher, it actually does a:
  1378. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1379. R_SUBH:
  1380. exit(getsubreg(reg2)=R_SUBH);
  1381. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1382. bits of reg2:
  1383. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1384. R_SUBW:
  1385. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1386. { a write to R_SUBD always overwrites every other subregister,
  1387. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1388. R_SUBD,
  1389. R_SUBQ:
  1390. exit(true);
  1391. else
  1392. internalerror(2017042801);
  1393. end;
  1394. end;
  1395. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1396. begin
  1397. if not SuperRegistersEqual(reg1,reg2) then
  1398. exit(false);
  1399. if getregtype(reg1)<>R_INTREGISTER then
  1400. exit(true); {because SuperRegisterEqual is true}
  1401. case getsubreg(reg1) of
  1402. R_SUBL:
  1403. exit(getsubreg(reg2)<>R_SUBH);
  1404. R_SUBH:
  1405. exit(getsubreg(reg2)<>R_SUBL);
  1406. R_SUBW,
  1407. R_SUBD,
  1408. R_SUBQ:
  1409. exit(true);
  1410. else
  1411. internalerror(2017042802);
  1412. end;
  1413. end;
  1414. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1415. var
  1416. hp1 : tai;
  1417. l : TCGInt;
  1418. begin
  1419. result:=false;
  1420. if not(GetNextInstruction(p, hp1)) then
  1421. exit;
  1422. { changes the code sequence
  1423. shr/sar const1, x
  1424. shl const2, x
  1425. to
  1426. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1427. if (taicpu(p).oper[0]^.typ = top_const) and
  1428. MatchInstruction(hp1,A_SHL,[]) and
  1429. (taicpu(hp1).oper[0]^.typ = top_const) and
  1430. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1431. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1432. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1433. begin
  1434. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1435. not(cs_opt_size in current_settings.optimizerswitches) then
  1436. begin
  1437. { shr/sar const1, %reg
  1438. shl const2, %reg
  1439. with const1 > const2 }
  1440. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1441. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1442. taicpu(hp1).opcode := A_AND;
  1443. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1444. case taicpu(p).opsize Of
  1445. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1446. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1447. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1448. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1449. else
  1450. Internalerror(2017050703)
  1451. end;
  1452. end
  1453. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1454. not(cs_opt_size in current_settings.optimizerswitches) then
  1455. begin
  1456. { shr/sar const1, %reg
  1457. shl const2, %reg
  1458. with const1 < const2 }
  1459. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1460. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1461. taicpu(p).opcode := A_AND;
  1462. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1463. case taicpu(p).opsize Of
  1464. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1465. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1466. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1467. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1468. else
  1469. Internalerror(2017050702)
  1470. end;
  1471. end
  1472. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1473. begin
  1474. { shr/sar const1, %reg
  1475. shl const2, %reg
  1476. with const1 = const2 }
  1477. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1478. taicpu(p).opcode := A_AND;
  1479. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1480. case taicpu(p).opsize Of
  1481. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1482. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1483. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1484. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1485. else
  1486. Internalerror(2017050701)
  1487. end;
  1488. RemoveInstruction(hp1);
  1489. end;
  1490. end;
  1491. end;
  1492. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1493. var
  1494. opsize : topsize;
  1495. hp1, hp2 : tai;
  1496. tmpref : treference;
  1497. ShiftValue : Cardinal;
  1498. BaseValue : TCGInt;
  1499. begin
  1500. result:=false;
  1501. opsize:=taicpu(p).opsize;
  1502. { changes certain "imul const, %reg"'s to lea sequences }
  1503. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1504. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1505. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1506. if (taicpu(p).oper[0]^.val = 1) then
  1507. if (taicpu(p).ops = 2) then
  1508. { remove "imul $1, reg" }
  1509. begin
  1510. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1511. Result := RemoveCurrentP(p);
  1512. end
  1513. else
  1514. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1515. begin
  1516. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1517. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1518. asml.InsertAfter(hp1, p);
  1519. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1520. RemoveCurrentP(p, hp1);
  1521. Result := True;
  1522. end
  1523. else if ((taicpu(p).ops <= 2) or
  1524. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1525. not(cs_opt_size in current_settings.optimizerswitches) and
  1526. (not(GetNextInstruction(p, hp1)) or
  1527. not((tai(hp1).typ = ait_instruction) and
  1528. ((taicpu(hp1).opcode=A_Jcc) and
  1529. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1530. begin
  1531. {
  1532. imul X, reg1, reg2 to
  1533. lea (reg1,reg1,Y), reg2
  1534. shl ZZ,reg2
  1535. imul XX, reg1 to
  1536. lea (reg1,reg1,YY), reg1
  1537. shl ZZ,reg2
  1538. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1539. it does not exist as a separate optimization target in FPC though.
  1540. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1541. at most two zeros
  1542. }
  1543. reference_reset(tmpref,1,[]);
  1544. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1545. begin
  1546. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1547. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1548. TmpRef.base := taicpu(p).oper[1]^.reg;
  1549. TmpRef.index := taicpu(p).oper[1]^.reg;
  1550. if not(BaseValue in [3,5,9]) then
  1551. Internalerror(2018110101);
  1552. TmpRef.ScaleFactor := BaseValue-1;
  1553. if (taicpu(p).ops = 2) then
  1554. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1555. else
  1556. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1557. AsmL.InsertAfter(hp1,p);
  1558. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1559. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1560. RemoveCurrentP(p, hp1);
  1561. if ShiftValue>0 then
  1562. begin
  1563. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1564. AsmL.InsertAfter(hp2,hp1);
  1565. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1566. end;
  1567. Result := True;
  1568. end;
  1569. end;
  1570. end;
  1571. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1572. begin
  1573. Result := False;
  1574. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1575. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1576. begin
  1577. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1578. taicpu(p).opcode := A_MOV;
  1579. Result := True;
  1580. end;
  1581. end;
  1582. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1583. var
  1584. p: taicpu absolute hp; { Implicit typecast }
  1585. i: Integer;
  1586. begin
  1587. Result := False;
  1588. if not assigned(hp) or
  1589. (hp.typ <> ait_instruction) then
  1590. Exit;
  1591. Prefetch(insprop[p.opcode]);
  1592. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1593. with insprop[p.opcode] do
  1594. begin
  1595. case getsubreg(reg) of
  1596. R_SUBW,R_SUBD,R_SUBQ:
  1597. Result:=
  1598. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1599. uncommon flags are checked first }
  1600. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1601. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1602. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1603. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1604. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1605. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1606. R_SUBFLAGCARRY:
  1607. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1608. R_SUBFLAGPARITY:
  1609. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1610. R_SUBFLAGAUXILIARY:
  1611. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1612. R_SUBFLAGZERO:
  1613. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1614. R_SUBFLAGSIGN:
  1615. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1616. R_SUBFLAGOVERFLOW:
  1617. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1618. R_SUBFLAGINTERRUPT:
  1619. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1620. R_SUBFLAGDIRECTION:
  1621. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1622. else
  1623. internalerror(2017050501);
  1624. end;
  1625. exit;
  1626. end;
  1627. { Handle special cases first }
  1628. case p.opcode of
  1629. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1630. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1631. begin
  1632. Result :=
  1633. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1634. (p.oper[1]^.typ = top_reg) and
  1635. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1636. (
  1637. (p.oper[0]^.typ = top_const) or
  1638. (
  1639. (p.oper[0]^.typ = top_reg) and
  1640. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1641. ) or (
  1642. (p.oper[0]^.typ = top_ref) and
  1643. not RegInRef(reg,p.oper[0]^.ref^)
  1644. )
  1645. );
  1646. end;
  1647. A_MUL, A_IMUL:
  1648. Result :=
  1649. (
  1650. (p.ops=3) and { IMUL only }
  1651. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1652. (
  1653. (
  1654. (p.oper[1]^.typ=top_reg) and
  1655. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1656. ) or (
  1657. (p.oper[1]^.typ=top_ref) and
  1658. not RegInRef(reg,p.oper[1]^.ref^)
  1659. )
  1660. )
  1661. ) or (
  1662. (
  1663. (p.ops=1) and
  1664. (
  1665. (
  1666. (
  1667. (p.oper[0]^.typ=top_reg) and
  1668. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1669. )
  1670. ) or (
  1671. (p.oper[0]^.typ=top_ref) and
  1672. not RegInRef(reg,p.oper[0]^.ref^)
  1673. )
  1674. ) and (
  1675. (
  1676. (p.opsize=S_B) and
  1677. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1678. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1679. ) or (
  1680. (p.opsize=S_W) and
  1681. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1682. ) or (
  1683. (p.opsize=S_L) and
  1684. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1685. {$ifdef x86_64}
  1686. ) or (
  1687. (p.opsize=S_Q) and
  1688. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1689. {$endif x86_64}
  1690. )
  1691. )
  1692. )
  1693. );
  1694. A_CBW:
  1695. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1696. {$ifndef x86_64}
  1697. A_LDS:
  1698. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1699. A_LES:
  1700. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1701. {$endif not x86_64}
  1702. A_LFS:
  1703. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1704. A_LGS:
  1705. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1706. A_LSS:
  1707. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1708. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1709. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1710. A_LODSB:
  1711. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1712. A_LODSW:
  1713. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1714. {$ifdef x86_64}
  1715. A_LODSQ:
  1716. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1717. {$endif x86_64}
  1718. A_LODSD:
  1719. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1720. A_FSTSW, A_FNSTSW:
  1721. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1722. else
  1723. begin
  1724. with insprop[p.opcode] do
  1725. begin
  1726. if (
  1727. { xor %reg,%reg etc. is classed as a new value }
  1728. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1729. MatchOpType(p, top_reg, top_reg) and
  1730. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1731. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1732. ) then
  1733. begin
  1734. Result := True;
  1735. Exit;
  1736. end;
  1737. { Make sure the entire register is overwritten }
  1738. if (getregtype(reg) = R_INTREGISTER) then
  1739. begin
  1740. if (p.ops > 0) then
  1741. begin
  1742. if RegInOp(reg, p.oper[0]^) then
  1743. begin
  1744. if (p.oper[0]^.typ = top_ref) then
  1745. begin
  1746. if RegInRef(reg, p.oper[0]^.ref^) then
  1747. begin
  1748. Result := False;
  1749. Exit;
  1750. end;
  1751. end
  1752. else if (p.oper[0]^.typ = top_reg) then
  1753. begin
  1754. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end
  1759. else if ([Ch_WOp1]*Ch<>[]) then
  1760. begin
  1761. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1762. Result := True
  1763. else
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end;
  1769. end;
  1770. end;
  1771. if (p.ops > 1) then
  1772. begin
  1773. if RegInOp(reg, p.oper[1]^) then
  1774. begin
  1775. if (p.oper[1]^.typ = top_ref) then
  1776. begin
  1777. if RegInRef(reg, p.oper[1]^.ref^) then
  1778. begin
  1779. Result := False;
  1780. Exit;
  1781. end;
  1782. end
  1783. else if (p.oper[1]^.typ = top_reg) then
  1784. begin
  1785. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end
  1790. else if ([Ch_WOp2]*Ch<>[]) then
  1791. begin
  1792. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1793. Result := True
  1794. else
  1795. begin
  1796. Result := False;
  1797. Exit;
  1798. end;
  1799. end;
  1800. end;
  1801. end;
  1802. if (p.ops > 2) then
  1803. begin
  1804. if RegInOp(reg, p.oper[2]^) then
  1805. begin
  1806. if (p.oper[2]^.typ = top_ref) then
  1807. begin
  1808. if RegInRef(reg, p.oper[2]^.ref^) then
  1809. begin
  1810. Result := False;
  1811. Exit;
  1812. end;
  1813. end
  1814. else if (p.oper[2]^.typ = top_reg) then
  1815. begin
  1816. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1817. begin
  1818. Result := False;
  1819. Exit;
  1820. end
  1821. else if ([Ch_WOp3]*Ch<>[]) then
  1822. begin
  1823. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1824. Result := True
  1825. else
  1826. begin
  1827. Result := False;
  1828. Exit;
  1829. end;
  1830. end;
  1831. end;
  1832. end;
  1833. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1834. begin
  1835. if (p.oper[3]^.typ = top_ref) then
  1836. begin
  1837. if RegInRef(reg, p.oper[3]^.ref^) then
  1838. begin
  1839. Result := False;
  1840. Exit;
  1841. end;
  1842. end
  1843. else if (p.oper[3]^.typ = top_reg) then
  1844. begin
  1845. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1846. begin
  1847. Result := False;
  1848. Exit;
  1849. end
  1850. else if ([Ch_WOp4]*Ch<>[]) then
  1851. begin
  1852. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1853. Result := True
  1854. else
  1855. begin
  1856. Result := False;
  1857. Exit;
  1858. end;
  1859. end;
  1860. end;
  1861. end;
  1862. end;
  1863. end;
  1864. end;
  1865. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1866. case getsupreg(reg) of
  1867. RS_EAX:
  1868. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1869. begin
  1870. Result := True;
  1871. Exit;
  1872. end;
  1873. RS_ECX:
  1874. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1875. begin
  1876. Result := True;
  1877. Exit;
  1878. end;
  1879. RS_EDX:
  1880. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1881. begin
  1882. Result := True;
  1883. Exit;
  1884. end;
  1885. RS_EBX:
  1886. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1887. begin
  1888. Result := True;
  1889. Exit;
  1890. end;
  1891. RS_ESP:
  1892. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1893. begin
  1894. Result := True;
  1895. Exit;
  1896. end;
  1897. RS_EBP:
  1898. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1899. begin
  1900. Result := True;
  1901. Exit;
  1902. end;
  1903. RS_ESI:
  1904. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1905. begin
  1906. Result := True;
  1907. Exit;
  1908. end;
  1909. RS_EDI:
  1910. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1911. begin
  1912. Result := True;
  1913. Exit;
  1914. end;
  1915. else
  1916. ;
  1917. end;
  1918. end;
  1919. end;
  1920. end;
  1921. end;
  1922. end;
  1923. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1924. var
  1925. hp2,hp3 : tai;
  1926. begin
  1927. { some x86-64 issue a NOP before the real exit code }
  1928. if MatchInstruction(p,A_NOP,[]) then
  1929. GetNextInstruction(p,p);
  1930. result:=assigned(p) and (p.typ=ait_instruction) and
  1931. ((taicpu(p).opcode = A_RET) or
  1932. ((taicpu(p).opcode=A_LEAVE) and
  1933. GetNextInstruction(p,hp2) and
  1934. MatchInstruction(hp2,A_RET,[S_NO])
  1935. ) or
  1936. (((taicpu(p).opcode=A_LEA) and
  1937. MatchOpType(taicpu(p),top_ref,top_reg) and
  1938. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1939. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1940. ) and
  1941. GetNextInstruction(p,hp2) and
  1942. MatchInstruction(hp2,A_RET,[S_NO])
  1943. ) or
  1944. ((((taicpu(p).opcode=A_MOV) and
  1945. MatchOpType(taicpu(p),top_reg,top_reg) and
  1946. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1947. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1948. ((taicpu(p).opcode=A_LEA) and
  1949. MatchOpType(taicpu(p),top_ref,top_reg) and
  1950. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1951. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1952. )
  1953. ) and
  1954. GetNextInstruction(p,hp2) and
  1955. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1956. MatchOpType(taicpu(hp2),top_reg) and
  1957. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1958. GetNextInstruction(hp2,hp3) and
  1959. MatchInstruction(hp3,A_RET,[S_NO])
  1960. )
  1961. );
  1962. end;
  1963. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1964. begin
  1965. isFoldableArithOp := False;
  1966. case hp1.opcode of
  1967. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1968. isFoldableArithOp :=
  1969. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1970. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1971. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1972. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1973. (taicpu(hp1).oper[1]^.reg = reg);
  1974. A_INC,A_DEC,A_NEG,A_NOT:
  1975. isFoldableArithOp :=
  1976. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1977. (taicpu(hp1).oper[0]^.reg = reg);
  1978. else
  1979. ;
  1980. end;
  1981. end;
  1982. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1983. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1984. var
  1985. hp2: tai;
  1986. begin
  1987. hp2 := p;
  1988. repeat
  1989. hp2 := tai(hp2.previous);
  1990. if assigned(hp2) and
  1991. (hp2.typ = ait_regalloc) and
  1992. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1993. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1994. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1995. begin
  1996. RemoveInstruction(hp2);
  1997. break;
  1998. end;
  1999. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2000. end;
  2001. begin
  2002. case current_procinfo.procdef.returndef.typ of
  2003. arraydef,recorddef,pointerdef,
  2004. stringdef,enumdef,procdef,objectdef,errordef,
  2005. filedef,setdef,procvardef,
  2006. classrefdef,forwarddef:
  2007. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2008. orddef:
  2009. if current_procinfo.procdef.returndef.size <> 0 then
  2010. begin
  2011. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2012. { for int64/qword }
  2013. if current_procinfo.procdef.returndef.size = 8 then
  2014. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2015. end;
  2016. else
  2017. ;
  2018. end;
  2019. end;
  2020. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2021. var
  2022. hp1,hp2 : tai;
  2023. begin
  2024. result:=false;
  2025. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2026. begin
  2027. { vmova* reg1,reg1
  2028. =>
  2029. <nop> }
  2030. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2031. begin
  2032. RemoveCurrentP(p);
  2033. result:=true;
  2034. exit;
  2035. end;
  2036. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2037. (hp1.typ = ait_instruction) and
  2038. (
  2039. { Under -O2 and below, the instructions are always adjacent }
  2040. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2041. (taicpu(hp1).ops <= 1) or
  2042. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2043. { If reg1 = reg3, reg1 must not be modified in between }
  2044. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2045. ) then
  2046. begin
  2047. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2048. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2049. begin
  2050. { vmova* reg1,reg2
  2051. ...
  2052. vmova* reg2,reg3
  2053. dealloc reg2
  2054. =>
  2055. vmova* reg1,reg3 }
  2056. TransferUsedRegs(TmpUsedRegs);
  2057. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2058. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2059. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2060. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2061. begin
  2062. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2063. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2064. TransferUsedRegs(TmpUsedRegs);
  2065. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2066. RemoveInstruction(hp1);
  2067. result:=true;
  2068. exit;
  2069. end;
  2070. { special case:
  2071. vmova* reg1,<op>
  2072. ...
  2073. vmova* <op>,reg1
  2074. =>
  2075. vmova* reg1,<op> }
  2076. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2077. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2078. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2079. ) then
  2080. begin
  2081. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2082. RemoveInstruction(hp1);
  2083. result:=true;
  2084. exit;
  2085. end
  2086. end
  2087. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2088. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2089. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2090. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2091. ) and
  2092. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2093. begin
  2094. { vmova* reg1,reg2
  2095. ...
  2096. vmovs* reg2,<op>
  2097. dealloc reg2
  2098. =>
  2099. vmovs* reg1,<op> }
  2100. TransferUsedRegs(TmpUsedRegs);
  2101. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2102. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2103. begin
  2104. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2105. taicpu(p).opcode:=taicpu(hp1).opcode;
  2106. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2107. TransferUsedRegs(TmpUsedRegs);
  2108. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2109. RemoveInstruction(hp1);
  2110. result:=true;
  2111. exit;
  2112. end
  2113. end;
  2114. if MatchInstruction(hp1,[A_VFMADDPD,
  2115. A_VFMADD132PD,
  2116. A_VFMADD132PS,
  2117. A_VFMADD132SD,
  2118. A_VFMADD132SS,
  2119. A_VFMADD213PD,
  2120. A_VFMADD213PS,
  2121. A_VFMADD213SD,
  2122. A_VFMADD213SS,
  2123. A_VFMADD231PD,
  2124. A_VFMADD231PS,
  2125. A_VFMADD231SD,
  2126. A_VFMADD231SS,
  2127. A_VFMADDSUB132PD,
  2128. A_VFMADDSUB132PS,
  2129. A_VFMADDSUB213PD,
  2130. A_VFMADDSUB213PS,
  2131. A_VFMADDSUB231PD,
  2132. A_VFMADDSUB231PS,
  2133. A_VFMSUB132PD,
  2134. A_VFMSUB132PS,
  2135. A_VFMSUB132SD,
  2136. A_VFMSUB132SS,
  2137. A_VFMSUB213PD,
  2138. A_VFMSUB213PS,
  2139. A_VFMSUB213SD,
  2140. A_VFMSUB213SS,
  2141. A_VFMSUB231PD,
  2142. A_VFMSUB231PS,
  2143. A_VFMSUB231SD,
  2144. A_VFMSUB231SS,
  2145. A_VFMSUBADD132PD,
  2146. A_VFMSUBADD132PS,
  2147. A_VFMSUBADD213PD,
  2148. A_VFMSUBADD213PS,
  2149. A_VFMSUBADD231PD,
  2150. A_VFMSUBADD231PS,
  2151. A_VFNMADD132PD,
  2152. A_VFNMADD132PS,
  2153. A_VFNMADD132SD,
  2154. A_VFNMADD132SS,
  2155. A_VFNMADD213PD,
  2156. A_VFNMADD213PS,
  2157. A_VFNMADD213SD,
  2158. A_VFNMADD213SS,
  2159. A_VFNMADD231PD,
  2160. A_VFNMADD231PS,
  2161. A_VFNMADD231SD,
  2162. A_VFNMADD231SS,
  2163. A_VFNMSUB132PD,
  2164. A_VFNMSUB132PS,
  2165. A_VFNMSUB132SD,
  2166. A_VFNMSUB132SS,
  2167. A_VFNMSUB213PD,
  2168. A_VFNMSUB213PS,
  2169. A_VFNMSUB213SD,
  2170. A_VFNMSUB213SS,
  2171. A_VFNMSUB231PD,
  2172. A_VFNMSUB231PS,
  2173. A_VFNMSUB231SD,
  2174. A_VFNMSUB231SS],[S_NO]) and
  2175. { we mix single and double opperations here because we assume that the compiler
  2176. generates vmovapd only after double operations and vmovaps only after single operations }
  2177. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2178. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2179. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2180. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2181. begin
  2182. TransferUsedRegs(TmpUsedRegs);
  2183. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2184. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2185. begin
  2186. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2187. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2188. RemoveCurrentP(p)
  2189. else
  2190. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2191. RemoveInstruction(hp2);
  2192. end;
  2193. end
  2194. else if (hp1.typ = ait_instruction) and
  2195. (((taicpu(p).opcode=A_MOVAPS) and
  2196. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2197. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2198. ((taicpu(p).opcode=A_MOVAPD) and
  2199. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2200. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2201. ) and
  2202. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2203. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2204. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2205. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2206. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2207. { change
  2208. movapX reg,reg2
  2209. addsX/subsX/... reg3, reg2
  2210. movapX reg2,reg
  2211. to
  2212. addsX/subsX/... reg3,reg
  2213. }
  2214. begin
  2215. TransferUsedRegs(TmpUsedRegs);
  2216. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2217. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2218. begin
  2219. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2220. debug_op2str(taicpu(p).opcode)+' '+
  2221. debug_op2str(taicpu(hp1).opcode)+' '+
  2222. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2223. { we cannot eliminate the first move if
  2224. the operations uses the same register for source and dest }
  2225. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2226. { Remember that hp1 is not necessarily the immediate
  2227. next instruction }
  2228. RemoveCurrentP(p);
  2229. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2230. RemoveInstruction(hp2);
  2231. result:=true;
  2232. end;
  2233. end
  2234. else if (hp1.typ = ait_instruction) and
  2235. (((taicpu(p).opcode=A_VMOVAPD) and
  2236. (taicpu(hp1).opcode=A_VCOMISD)) or
  2237. ((taicpu(p).opcode=A_VMOVAPS) and
  2238. ((taicpu(hp1).opcode=A_VCOMISS))
  2239. )
  2240. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2241. { change
  2242. movapX reg,reg1
  2243. vcomisX reg1,reg1
  2244. to
  2245. vcomisX reg,reg
  2246. }
  2247. begin
  2248. TransferUsedRegs(TmpUsedRegs);
  2249. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2250. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2251. begin
  2252. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2253. debug_op2str(taicpu(p).opcode)+' '+
  2254. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2255. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2256. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2257. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2258. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2259. RemoveCurrentP(p);
  2260. result:=true;
  2261. exit;
  2262. end;
  2263. end
  2264. end;
  2265. end;
  2266. end;
  2267. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2268. var
  2269. hp1 : tai;
  2270. begin
  2271. result:=false;
  2272. { replace
  2273. V<Op>X %mreg1,%mreg2,%mreg3
  2274. VMovX %mreg3,%mreg4
  2275. dealloc %mreg3
  2276. by
  2277. V<Op>X %mreg1,%mreg2,%mreg4
  2278. ?
  2279. }
  2280. if GetNextInstruction(p,hp1) and
  2281. { we mix single and double operations here because we assume that the compiler
  2282. generates vmovapd only after double operations and vmovaps only after single operations }
  2283. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2284. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2285. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2286. begin
  2287. TransferUsedRegs(TmpUsedRegs);
  2288. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2289. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2290. begin
  2291. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2292. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2293. RemoveInstruction(hp1);
  2294. result:=true;
  2295. end;
  2296. end;
  2297. end;
  2298. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2299. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2300. begin
  2301. Result := False;
  2302. { For safety reasons, only check for exact register matches }
  2303. { Check base register }
  2304. if (ref.base = AOldReg) then
  2305. begin
  2306. ref.base := ANewReg;
  2307. Result := True;
  2308. end;
  2309. { Check index register }
  2310. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2311. begin
  2312. ref.index := ANewReg;
  2313. Result := True;
  2314. end;
  2315. end;
  2316. { Replaces all references to AOldReg in an operand to ANewReg }
  2317. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2318. var
  2319. OldSupReg, NewSupReg: TSuperRegister;
  2320. OldSubReg, NewSubReg: TSubRegister;
  2321. OldRegType: TRegisterType;
  2322. ThisOper: POper;
  2323. begin
  2324. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2325. Result := False;
  2326. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2327. InternalError(2020011801);
  2328. OldSupReg := getsupreg(AOldReg);
  2329. OldSubReg := getsubreg(AOldReg);
  2330. OldRegType := getregtype(AOldReg);
  2331. NewSupReg := getsupreg(ANewReg);
  2332. NewSubReg := getsubreg(ANewReg);
  2333. if OldRegType <> getregtype(ANewReg) then
  2334. InternalError(2020011802);
  2335. if OldSubReg <> NewSubReg then
  2336. InternalError(2020011803);
  2337. case ThisOper^.typ of
  2338. top_reg:
  2339. if (
  2340. (ThisOper^.reg = AOldReg) or
  2341. (
  2342. (OldRegType = R_INTREGISTER) and
  2343. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2344. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2345. (
  2346. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2347. {$ifndef x86_64}
  2348. and (
  2349. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2350. don't have an 8-bit representation }
  2351. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2352. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2353. )
  2354. {$endif x86_64}
  2355. )
  2356. )
  2357. ) then
  2358. begin
  2359. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2360. Result := True;
  2361. end;
  2362. top_ref:
  2363. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2364. Result := True;
  2365. else
  2366. ;
  2367. end;
  2368. end;
  2369. { Replaces all references to AOldReg in an instruction to ANewReg }
  2370. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2371. const
  2372. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2373. var
  2374. OperIdx: Integer;
  2375. begin
  2376. Result := False;
  2377. for OperIdx := 0 to p.ops - 1 do
  2378. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2379. begin
  2380. { The shift and rotate instructions can only use CL }
  2381. if not (
  2382. (OperIdx = 0) and
  2383. { This second condition just helps to avoid unnecessarily
  2384. calling MatchInstruction for 10 different opcodes }
  2385. (p.oper[0]^.reg = NR_CL) and
  2386. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2387. ) then
  2388. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2389. end
  2390. else if p.oper[OperIdx]^.typ = top_ref then
  2391. { It's okay to replace registers in references that get written to }
  2392. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2393. end;
  2394. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2395. begin
  2396. Result :=
  2397. (ref^.index = NR_NO) and
  2398. (
  2399. {$ifdef x86_64}
  2400. (
  2401. (ref^.base = NR_RIP) and
  2402. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2403. ) or
  2404. {$endif x86_64}
  2405. (ref^.refaddr = addr_full) or
  2406. (ref^.base = NR_STACK_POINTER_REG) or
  2407. (ref^.base = current_procinfo.framepointer)
  2408. );
  2409. end;
  2410. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2411. var
  2412. l: asizeint;
  2413. begin
  2414. Result := False;
  2415. { Should have been checked previously }
  2416. if p.opcode <> A_LEA then
  2417. InternalError(2020072501);
  2418. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2419. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2420. not(cs_opt_size in current_settings.optimizerswitches) then
  2421. exit;
  2422. with p.oper[0]^.ref^ do
  2423. begin
  2424. if (base <> p.oper[1]^.reg) or
  2425. (index <> NR_NO) or
  2426. assigned(symbol) then
  2427. exit;
  2428. l:=offset;
  2429. if (l=1) and UseIncDec then
  2430. begin
  2431. p.opcode:=A_INC;
  2432. p.loadreg(0,p.oper[1]^.reg);
  2433. p.ops:=1;
  2434. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2435. end
  2436. else if (l=-1) and UseIncDec then
  2437. begin
  2438. p.opcode:=A_DEC;
  2439. p.loadreg(0,p.oper[1]^.reg);
  2440. p.ops:=1;
  2441. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2442. end
  2443. else
  2444. begin
  2445. if (l<0) and (l<>-2147483648) then
  2446. begin
  2447. p.opcode:=A_SUB;
  2448. p.loadConst(0,-l);
  2449. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2450. end
  2451. else
  2452. begin
  2453. p.opcode:=A_ADD;
  2454. p.loadConst(0,l);
  2455. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2456. end;
  2457. end;
  2458. end;
  2459. Result := True;
  2460. end;
  2461. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2462. var
  2463. CurrentReg, ReplaceReg: TRegister;
  2464. begin
  2465. Result := False;
  2466. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2467. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2468. case hp.opcode of
  2469. A_FSTSW, A_FNSTSW,
  2470. A_IN, A_INS, A_OUT, A_OUTS,
  2471. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2472. { These routines have explicit operands, but they are restricted in
  2473. what they can be (e.g. IN and OUT can only read from AL, AX or
  2474. EAX. }
  2475. Exit;
  2476. A_IMUL:
  2477. begin
  2478. { The 1-operand version writes to implicit registers
  2479. The 2-operand version reads from the first operator, and reads
  2480. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2481. the 3-operand version reads from a register that it doesn't write to
  2482. }
  2483. case hp.ops of
  2484. 1:
  2485. if (
  2486. (
  2487. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2488. ) or
  2489. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2490. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2491. begin
  2492. Result := True;
  2493. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2494. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2495. end;
  2496. 2:
  2497. { Only modify the first parameter }
  2498. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2499. begin
  2500. Result := True;
  2501. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2502. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2503. end;
  2504. 3:
  2505. { Only modify the second parameter }
  2506. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2507. begin
  2508. Result := True;
  2509. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2510. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2511. end;
  2512. else
  2513. InternalError(2020012901);
  2514. end;
  2515. end;
  2516. else
  2517. if (hp.ops > 0) and
  2518. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2519. begin
  2520. Result := True;
  2521. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2522. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2523. end;
  2524. end;
  2525. end;
  2526. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2527. var
  2528. hp2: tai;
  2529. p_SourceReg, p_TargetReg: TRegister;
  2530. begin
  2531. Result := False;
  2532. { Backward optimisation. If we have:
  2533. func. %reg1,%reg2
  2534. mov %reg2,%reg3
  2535. (dealloc %reg2)
  2536. Change to:
  2537. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2538. Perform similar optimisations with 1, 3 and 4-operand instructions
  2539. that only have one output.
  2540. }
  2541. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2542. begin
  2543. p_SourceReg := taicpu(p).oper[0]^.reg;
  2544. p_TargetReg := taicpu(p).oper[1]^.reg;
  2545. TransferUsedRegs(TmpUsedRegs);
  2546. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2547. GetLastInstruction(p, hp2) and
  2548. (hp2.typ = ait_instruction) and
  2549. { Have to make sure it's an instruction that only reads from
  2550. the first operands and only writes (not reads or modifies) to
  2551. the last one; in essence, a pure function such as BSR, POPCNT
  2552. or ANDN }
  2553. (
  2554. (
  2555. (taicpu(hp2).ops = 1) and
  2556. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2557. ) or
  2558. (
  2559. (taicpu(hp2).ops = 2) and
  2560. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2561. ) or
  2562. (
  2563. (taicpu(hp2).ops = 3) and
  2564. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2565. ) or
  2566. (
  2567. (taicpu(hp2).ops = 4) and
  2568. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2569. )
  2570. ) and
  2571. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2572. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2573. begin
  2574. case taicpu(hp2).opcode of
  2575. A_FSTSW, A_FNSTSW,
  2576. A_IN, A_INS, A_OUT, A_OUTS,
  2577. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2578. { These routines have explicit operands, but they are restricted in
  2579. what they can be (e.g. IN and OUT can only read from AL, AX or
  2580. EAX. }
  2581. ;
  2582. else
  2583. begin
  2584. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2585. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2586. if not RegInInstruction(p_TargetReg, hp2) then
  2587. begin
  2588. { Since we're allocating from an earlier point, we
  2589. need to remove the register from the tracking }
  2590. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2591. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2592. end;
  2593. RemoveCurrentp(p, hp1);
  2594. { If the Func was another MOV instruction, we might get
  2595. "mov %reg,%reg" that doesn't get removed in Pass 2
  2596. otherwise, so deal with it here (also do something
  2597. similar with lea (%reg),%reg}
  2598. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2599. begin
  2600. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2601. if p = hp2 then
  2602. RemoveCurrentp(p)
  2603. else
  2604. RemoveInstruction(hp2);
  2605. end;
  2606. Result := True;
  2607. Exit;
  2608. end;
  2609. end;
  2610. end;
  2611. end;
  2612. end;
  2613. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2614. var
  2615. hp1, hp2, hp3: tai;
  2616. DoOptimisation, TempBool: Boolean;
  2617. {$ifdef x86_64}
  2618. NewConst: TCGInt;
  2619. {$endif x86_64}
  2620. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2621. begin
  2622. if taicpu(hp1).opcode = signed_movop then
  2623. begin
  2624. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2625. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2626. end
  2627. else
  2628. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2629. end;
  2630. function TryConstMerge(var p1, p2: tai): Boolean;
  2631. var
  2632. ThisRef: TReference;
  2633. begin
  2634. Result := False;
  2635. ThisRef := taicpu(p2).oper[1]^.ref^;
  2636. { Only permit writes to the stack, since we can guarantee alignment with that }
  2637. if (ThisRef.index = NR_NO) and
  2638. (
  2639. (ThisRef.base = NR_STACK_POINTER_REG) or
  2640. (ThisRef.base = current_procinfo.framepointer)
  2641. ) then
  2642. begin
  2643. case taicpu(p).opsize of
  2644. S_B:
  2645. begin
  2646. { Word writes must be on a 2-byte boundary }
  2647. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2648. begin
  2649. { Reduce offset of second reference to see if it is sequential with the first }
  2650. Dec(ThisRef.offset, 1);
  2651. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2652. begin
  2653. { Make sure the constants aren't represented as a
  2654. negative number, as these won't merge properly }
  2655. taicpu(p1).opsize := S_W;
  2656. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2657. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2658. RemoveInstruction(p2);
  2659. Result := True;
  2660. end;
  2661. end;
  2662. end;
  2663. S_W:
  2664. begin
  2665. { Longword writes must be on a 4-byte boundary }
  2666. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2667. begin
  2668. { Reduce offset of second reference to see if it is sequential with the first }
  2669. Dec(ThisRef.offset, 2);
  2670. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2671. begin
  2672. { Make sure the constants aren't represented as a
  2673. negative number, as these won't merge properly }
  2674. taicpu(p1).opsize := S_L;
  2675. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2676. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2677. RemoveInstruction(p2);
  2678. Result := True;
  2679. end;
  2680. end;
  2681. end;
  2682. {$ifdef x86_64}
  2683. S_L:
  2684. begin
  2685. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2686. see if the constants can be encoded this way. }
  2687. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2688. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2689. { Quadword writes must be on an 8-byte boundary }
  2690. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2691. begin
  2692. { Reduce offset of second reference to see if it is sequential with the first }
  2693. Dec(ThisRef.offset, 4);
  2694. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2695. begin
  2696. { Make sure the constants aren't represented as a
  2697. negative number, as these won't merge properly }
  2698. taicpu(p1).opsize := S_Q;
  2699. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2700. taicpu(p1).oper[0]^.val := NewConst;
  2701. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2702. RemoveInstruction(p2);
  2703. Result := True;
  2704. end;
  2705. end;
  2706. end;
  2707. {$endif x86_64}
  2708. else
  2709. ;
  2710. end;
  2711. end;
  2712. end;
  2713. var
  2714. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2715. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2716. NewSize: topsize; NewOffset: asizeint;
  2717. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2718. SourceRef, TargetRef: TReference;
  2719. MovAligned, MovUnaligned: TAsmOp;
  2720. ThisRef: TReference;
  2721. JumpTracking: TLinkedList;
  2722. begin
  2723. Result:=false;
  2724. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2725. { remove mov reg1,reg1? }
  2726. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2727. then
  2728. begin
  2729. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2730. { take care of the register (de)allocs following p }
  2731. RemoveCurrentP(p, hp1);
  2732. Result:=true;
  2733. exit;
  2734. end;
  2735. { All the next optimisations require a next instruction }
  2736. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2737. Exit;
  2738. { Prevent compiler warnings }
  2739. p_TargetReg := NR_NO;
  2740. if taicpu(p).oper[1]^.typ = top_reg then
  2741. begin
  2742. { Saves on a large number of dereferences }
  2743. p_TargetReg := taicpu(p).oper[1]^.reg;
  2744. { Look for:
  2745. mov %reg1,%reg2
  2746. ??? %reg2,r/m
  2747. Change to:
  2748. mov %reg1,%reg2
  2749. ??? %reg1,r/m
  2750. }
  2751. if taicpu(p).oper[0]^.typ = top_reg then
  2752. begin
  2753. if RegReadByInstruction(p_TargetReg, hp1) and
  2754. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2755. begin
  2756. { A change has occurred, just not in p }
  2757. Result := True;
  2758. TransferUsedRegs(TmpUsedRegs);
  2759. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2760. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2761. { Just in case something didn't get modified (e.g. an
  2762. implicit register) }
  2763. not RegReadByInstruction(p_TargetReg, hp1) then
  2764. begin
  2765. { We can remove the original MOV }
  2766. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2767. RemoveCurrentp(p, hp1);
  2768. { UsedRegs got updated by RemoveCurrentp }
  2769. Result := True;
  2770. Exit;
  2771. end;
  2772. { If we know a MOV instruction has become a null operation, we might as well
  2773. get rid of it now to save time. }
  2774. if (taicpu(hp1).opcode = A_MOV) and
  2775. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2776. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2777. { Just being a register is enough to confirm it's a null operation }
  2778. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2779. begin
  2780. Result := True;
  2781. { Speed-up to reduce a pipeline stall... if we had something like...
  2782. movl %eax,%edx
  2783. movw %dx,%ax
  2784. ... the second instruction would change to movw %ax,%ax, but
  2785. given that it is now %ax that's active rather than %eax,
  2786. penalties might occur due to a partial register write, so instead,
  2787. change it to a MOVZX instruction when optimising for speed.
  2788. }
  2789. if not (cs_opt_size in current_settings.optimizerswitches) and
  2790. IsMOVZXAcceptable and
  2791. (taicpu(hp1).opsize < taicpu(p).opsize)
  2792. {$ifdef x86_64}
  2793. { operations already implicitly set the upper 64 bits to zero }
  2794. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2795. {$endif x86_64}
  2796. then
  2797. begin
  2798. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2799. case taicpu(p).opsize of
  2800. S_W:
  2801. if taicpu(hp1).opsize = S_B then
  2802. taicpu(hp1).opsize := S_BL
  2803. else
  2804. InternalError(2020012911);
  2805. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2806. case taicpu(hp1).opsize of
  2807. S_B:
  2808. taicpu(hp1).opsize := S_BL;
  2809. S_W:
  2810. taicpu(hp1).opsize := S_WL;
  2811. else
  2812. InternalError(2020012912);
  2813. end;
  2814. else
  2815. InternalError(2020012910);
  2816. end;
  2817. taicpu(hp1).opcode := A_MOVZX;
  2818. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2819. end
  2820. else
  2821. begin
  2822. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2823. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2824. RemoveInstruction(hp1);
  2825. { The instruction after what was hp1 is now the immediate next instruction,
  2826. so we can continue to make optimisations if it's present }
  2827. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2828. Exit;
  2829. hp1 := hp2;
  2830. end;
  2831. end;
  2832. end;
  2833. end;
  2834. end;
  2835. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2836. overwrites the original destination register. e.g.
  2837. movl ###,%reg2d
  2838. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2839. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2840. }
  2841. if (taicpu(p).oper[1]^.typ = top_reg) and
  2842. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2843. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2844. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2845. begin
  2846. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2847. begin
  2848. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2849. case taicpu(p).oper[0]^.typ of
  2850. top_const:
  2851. { We have something like:
  2852. movb $x, %regb
  2853. movzbl %regb,%regd
  2854. Change to:
  2855. movl $x, %regd
  2856. }
  2857. begin
  2858. case taicpu(hp1).opsize of
  2859. S_BW:
  2860. begin
  2861. convert_mov_value(A_MOVSX, $FF);
  2862. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2863. taicpu(p).opsize := S_W;
  2864. end;
  2865. S_BL:
  2866. begin
  2867. convert_mov_value(A_MOVSX, $FF);
  2868. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2869. taicpu(p).opsize := S_L;
  2870. end;
  2871. S_WL:
  2872. begin
  2873. convert_mov_value(A_MOVSX, $FFFF);
  2874. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2875. taicpu(p).opsize := S_L;
  2876. end;
  2877. {$ifdef x86_64}
  2878. S_BQ:
  2879. begin
  2880. convert_mov_value(A_MOVSX, $FF);
  2881. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2882. taicpu(p).opsize := S_Q;
  2883. end;
  2884. S_WQ:
  2885. begin
  2886. convert_mov_value(A_MOVSX, $FFFF);
  2887. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2888. taicpu(p).opsize := S_Q;
  2889. end;
  2890. S_LQ:
  2891. begin
  2892. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2893. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2894. taicpu(p).opsize := S_Q;
  2895. end;
  2896. {$endif x86_64}
  2897. else
  2898. { If hp1 was a MOV instruction, it should have been
  2899. optimised already }
  2900. InternalError(2020021001);
  2901. end;
  2902. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2903. RemoveInstruction(hp1);
  2904. Result := True;
  2905. Exit;
  2906. end;
  2907. top_ref:
  2908. begin
  2909. { We have something like:
  2910. movb mem, %regb
  2911. movzbl %regb,%regd
  2912. Change to:
  2913. movzbl mem, %regd
  2914. }
  2915. ThisRef := taicpu(p).oper[0]^.ref^;
  2916. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2917. begin
  2918. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2919. taicpu(hp1).loadref(0, ThisRef);
  2920. { Make sure any registers in the references are properly tracked }
  2921. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2922. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2923. if (ThisRef.index <> NR_NO) then
  2924. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2925. RemoveCurrentP(p, hp1);
  2926. Result := True;
  2927. Exit;
  2928. end;
  2929. end;
  2930. else
  2931. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2932. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2933. Exit;
  2934. end;
  2935. end
  2936. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2937. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2938. optimised }
  2939. else
  2940. begin
  2941. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2942. RemoveCurrentP(p, hp1);
  2943. Result := True;
  2944. Exit;
  2945. end;
  2946. end;
  2947. if (taicpu(hp1).opcode = A_AND) and
  2948. (taicpu(p).oper[1]^.typ = top_reg) and
  2949. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2950. begin
  2951. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2952. begin
  2953. case taicpu(p).opsize of
  2954. S_L:
  2955. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2956. begin
  2957. { Optimize out:
  2958. mov x, %reg
  2959. and ffffffffh, %reg
  2960. }
  2961. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2962. RemoveInstruction(hp1);
  2963. Result:=true;
  2964. exit;
  2965. end;
  2966. S_Q: { TODO: Confirm if this is even possible }
  2967. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2968. begin
  2969. { Optimize out:
  2970. mov x, %reg
  2971. and ffffffffffffffffh, %reg
  2972. }
  2973. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2974. RemoveInstruction(hp1);
  2975. Result:=true;
  2976. exit;
  2977. end;
  2978. else
  2979. ;
  2980. end;
  2981. if (
  2982. (taicpu(p).oper[0]^.typ=top_reg) or
  2983. (
  2984. (taicpu(p).oper[0]^.typ=top_ref) and
  2985. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2986. )
  2987. ) and
  2988. GetNextInstruction(hp1,hp2) and
  2989. MatchInstruction(hp2,A_TEST,[]) and
  2990. (
  2991. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2992. (
  2993. { If the register being tested is smaller than the one
  2994. that received a bitwise AND, permit it if the constant
  2995. fits into the smaller size }
  2996. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2997. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2998. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2999. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3000. (
  3001. (
  3002. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3003. (taicpu(hp1).oper[0]^.val <= $FF)
  3004. ) or
  3005. (
  3006. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3007. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3008. {$ifdef x86_64}
  3009. ) or
  3010. (
  3011. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3012. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3013. {$endif x86_64}
  3014. )
  3015. )
  3016. )
  3017. ) and
  3018. (
  3019. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3020. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3021. ) and
  3022. GetNextInstruction(hp2,hp3) and
  3023. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3024. (taicpu(hp3).condition in [C_E,C_NE]) then
  3025. begin
  3026. TransferUsedRegs(TmpUsedRegs);
  3027. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3028. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3029. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3030. begin
  3031. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3032. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3033. taicpu(hp1).opcode:=A_TEST;
  3034. { Shrink the TEST instruction down to the smallest possible size }
  3035. case taicpu(hp1).oper[0]^.val of
  3036. 0..255:
  3037. if (taicpu(hp1).opsize <> S_B)
  3038. {$ifndef x86_64}
  3039. and (
  3040. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3041. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3042. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3043. )
  3044. {$endif x86_64}
  3045. then
  3046. begin
  3047. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3048. { Only print debug message if the TEST instruction
  3049. is a different size before and after }
  3050. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3051. taicpu(hp1).opsize := S_B;
  3052. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3053. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3054. end;
  3055. 256..65535:
  3056. if (taicpu(hp1).opsize <> S_W) then
  3057. begin
  3058. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3059. { Only print debug message if the TEST instruction
  3060. is a different size before and after }
  3061. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3062. taicpu(hp1).opsize := S_W;
  3063. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3064. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3065. end;
  3066. {$ifdef x86_64}
  3067. 65536..$7FFFFFFF:
  3068. if (taicpu(hp1).opsize <> S_L) then
  3069. begin
  3070. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3071. { Only print debug message if the TEST instruction
  3072. is a different size before and after }
  3073. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3074. taicpu(hp1).opsize := S_L;
  3075. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3076. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3077. end;
  3078. {$endif x86_64}
  3079. else
  3080. ;
  3081. end;
  3082. RemoveInstruction(hp2);
  3083. RemoveCurrentP(p, hp1);
  3084. Result:=true;
  3085. exit;
  3086. end;
  3087. end;
  3088. end
  3089. else if IsMOVZXAcceptable and
  3090. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3091. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3092. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3093. then
  3094. begin
  3095. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3096. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3097. case taicpu(p).opsize of
  3098. S_B:
  3099. if (taicpu(hp1).oper[0]^.val = $ff) then
  3100. begin
  3101. { Convert:
  3102. movb x, %regl movb x, %regl
  3103. andw ffh, %regw andl ffh, %regd
  3104. To:
  3105. movzbw x, %regd movzbl x, %regd
  3106. (Identical registers, just different sizes)
  3107. }
  3108. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3109. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3110. case taicpu(hp1).opsize of
  3111. S_W: NewSize := S_BW;
  3112. S_L: NewSize := S_BL;
  3113. {$ifdef x86_64}
  3114. S_Q: NewSize := S_BQ;
  3115. {$endif x86_64}
  3116. else
  3117. InternalError(2018011510);
  3118. end;
  3119. end
  3120. else
  3121. NewSize := S_NO;
  3122. S_W:
  3123. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3124. begin
  3125. { Convert:
  3126. movw x, %regw
  3127. andl ffffh, %regd
  3128. To:
  3129. movzwl x, %regd
  3130. (Identical registers, just different sizes)
  3131. }
  3132. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3133. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3134. case taicpu(hp1).opsize of
  3135. S_L: NewSize := S_WL;
  3136. {$ifdef x86_64}
  3137. S_Q: NewSize := S_WQ;
  3138. {$endif x86_64}
  3139. else
  3140. InternalError(2018011511);
  3141. end;
  3142. end
  3143. else
  3144. NewSize := S_NO;
  3145. else
  3146. NewSize := S_NO;
  3147. end;
  3148. if NewSize <> S_NO then
  3149. begin
  3150. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3151. { The actual optimization }
  3152. taicpu(p).opcode := A_MOVZX;
  3153. taicpu(p).changeopsize(NewSize);
  3154. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3155. { Safeguard if "and" is followed by a conditional command }
  3156. TransferUsedRegs(TmpUsedRegs);
  3157. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3158. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3159. begin
  3160. { At this point, the "and" command is effectively equivalent to
  3161. "test %reg,%reg". This will be handled separately by the
  3162. Peephole Optimizer. [Kit] }
  3163. DebugMsg(SPeepholeOptimization + PreMessage +
  3164. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3165. end
  3166. else
  3167. begin
  3168. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3169. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3170. RemoveInstruction(hp1);
  3171. end;
  3172. Result := True;
  3173. Exit;
  3174. end;
  3175. end;
  3176. end;
  3177. if (taicpu(hp1).opcode = A_OR) and
  3178. (taicpu(p).oper[1]^.typ = top_reg) and
  3179. MatchOperand(taicpu(p).oper[0]^, 0) and
  3180. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3181. begin
  3182. { mov 0, %reg
  3183. or ###,%reg
  3184. Change to (only if the flags are not used):
  3185. mov ###,%reg
  3186. }
  3187. TransferUsedRegs(TmpUsedRegs);
  3188. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3189. DoOptimisation := True;
  3190. { Even if the flags are used, we might be able to do the optimisation
  3191. if the conditions are predictable }
  3192. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3193. begin
  3194. { Only perform if ### = %reg (the same register) or equal to 0,
  3195. so %reg is guaranteed to still have a value of zero }
  3196. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3197. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3198. begin
  3199. hp2 := hp1;
  3200. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3201. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3202. GetNextInstruction(hp2, hp3) do
  3203. begin
  3204. { Don't continue modifying if the flags state is getting changed }
  3205. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3206. Break;
  3207. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3208. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3209. begin
  3210. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3211. begin
  3212. { Condition is always true }
  3213. case taicpu(hp3).opcode of
  3214. A_Jcc:
  3215. begin
  3216. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3217. { Check for jump shortcuts before we destroy the condition }
  3218. DoJumpOptimizations(hp3, TempBool);
  3219. MakeUnconditional(taicpu(hp3));
  3220. Result := True;
  3221. end;
  3222. A_CMOVcc:
  3223. begin
  3224. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3225. taicpu(hp3).opcode := A_MOV;
  3226. taicpu(hp3).condition := C_None;
  3227. Result := True;
  3228. end;
  3229. A_SETcc:
  3230. begin
  3231. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3232. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3233. taicpu(hp3).opcode := A_MOV;
  3234. taicpu(hp3).ops := 2;
  3235. taicpu(hp3).condition := C_None;
  3236. taicpu(hp3).opsize := S_B;
  3237. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3238. taicpu(hp3).loadconst(0, 1);
  3239. Result := True;
  3240. end;
  3241. else
  3242. InternalError(2021090701);
  3243. end;
  3244. end
  3245. else if (taicpu(hp3).condition in [C_A, C_B, C_C, C_G, C_L, C_NE, C_NZ, C_O, C_S]) then
  3246. begin
  3247. { Condition is always false }
  3248. case taicpu(hp3).opcode of
  3249. A_Jcc:
  3250. begin
  3251. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3252. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3253. RemoveInstruction(hp3);
  3254. Result := True;
  3255. { Since hp3 was deleted, hp2 must not be updated }
  3256. Continue;
  3257. end;
  3258. A_CMOVcc:
  3259. begin
  3260. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3261. RemoveInstruction(hp3);
  3262. Result := True;
  3263. { Since hp3 was deleted, hp2 must not be updated }
  3264. Continue;
  3265. end;
  3266. A_SETcc:
  3267. begin
  3268. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3269. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3270. taicpu(hp3).opcode := A_MOV;
  3271. taicpu(hp3).ops := 2;
  3272. taicpu(hp3).condition := C_None;
  3273. taicpu(hp3).opsize := S_B;
  3274. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3275. taicpu(hp3).loadconst(0, 0);
  3276. Result := True;
  3277. end;
  3278. else
  3279. InternalError(2021090702);
  3280. end;
  3281. end
  3282. else
  3283. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3284. DoOptimisation := False;
  3285. end;
  3286. hp2 := hp3;
  3287. end;
  3288. { Flags are still in use - don't optimise }
  3289. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3290. DoOptimisation := False;
  3291. end
  3292. else
  3293. DoOptimisation := False;
  3294. end;
  3295. if DoOptimisation then
  3296. begin
  3297. {$ifdef x86_64}
  3298. { OR only supports 32-bit sign-extended constants for 64-bit
  3299. instructions, so compensate for this if the constant is
  3300. encoded as a value greater than or equal to 2^31 }
  3301. if (taicpu(hp1).opsize = S_Q) and
  3302. (taicpu(hp1).oper[0]^.typ = top_const) and
  3303. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3304. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3305. {$endif x86_64}
  3306. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3307. taicpu(hp1).opcode := A_MOV;
  3308. RemoveCurrentP(p, hp1);
  3309. Result := True;
  3310. Exit;
  3311. end;
  3312. end;
  3313. { Next instruction is also a MOV ? }
  3314. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3315. begin
  3316. if MatchOpType(taicpu(p), top_const, top_ref) and
  3317. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3318. TryConstMerge(p, hp1) then
  3319. begin
  3320. Result := True;
  3321. { In case we have four byte writes in a row, check for 2 more
  3322. right now so we don't have to wait for another iteration of
  3323. pass 1
  3324. }
  3325. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3326. case taicpu(p).opsize of
  3327. S_W:
  3328. begin
  3329. if GetNextInstruction(p, hp1) and
  3330. MatchInstruction(hp1, A_MOV, [S_B]) and
  3331. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3332. GetNextInstruction(hp1, hp2) and
  3333. MatchInstruction(hp2, A_MOV, [S_B]) and
  3334. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3335. { Try to merge the two bytes }
  3336. TryConstMerge(hp1, hp2) then
  3337. { Now try to merge the two words (hp2 will get deleted) }
  3338. TryConstMerge(p, hp1);
  3339. end;
  3340. S_L:
  3341. begin
  3342. { Though this only really benefits x86_64 and not i386, it
  3343. gets a potential optimisation done faster and hence
  3344. reduces the number of times OptPass1MOV is entered }
  3345. if GetNextInstruction(p, hp1) and
  3346. MatchInstruction(hp1, A_MOV, [S_W]) and
  3347. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3348. GetNextInstruction(hp1, hp2) and
  3349. MatchInstruction(hp2, A_MOV, [S_W]) and
  3350. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3351. { Try to merge the two words }
  3352. TryConstMerge(hp1, hp2) then
  3353. { This will always fail on i386, so don't bother
  3354. calling it unless we're doing x86_64 }
  3355. {$ifdef x86_64}
  3356. { Now try to merge the two longwords (hp2 will get deleted) }
  3357. TryConstMerge(p, hp1)
  3358. {$endif x86_64}
  3359. ;
  3360. end;
  3361. else
  3362. ;
  3363. end;
  3364. Exit;
  3365. end;
  3366. if (taicpu(p).oper[1]^.typ = top_reg) and
  3367. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3368. begin
  3369. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3370. TransferUsedRegs(TmpUsedRegs);
  3371. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3372. { we have
  3373. mov x, %treg
  3374. mov %treg, y
  3375. }
  3376. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3377. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3378. { we've got
  3379. mov x, %treg
  3380. mov %treg, y
  3381. with %treg is not used after }
  3382. case taicpu(p).oper[0]^.typ Of
  3383. { top_reg is covered by DeepMOVOpt }
  3384. top_const:
  3385. begin
  3386. { change
  3387. mov const, %treg
  3388. mov %treg, y
  3389. to
  3390. mov const, y
  3391. }
  3392. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3393. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3394. begin
  3395. if taicpu(hp1).oper[1]^.typ=top_reg then
  3396. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3397. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3398. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3399. RemoveInstruction(hp1);
  3400. Result:=true;
  3401. Exit;
  3402. end;
  3403. end;
  3404. top_ref:
  3405. case taicpu(hp1).oper[1]^.typ of
  3406. top_reg:
  3407. begin
  3408. { change
  3409. mov mem, %treg
  3410. mov %treg, %reg
  3411. to
  3412. mov mem, %reg"
  3413. }
  3414. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3415. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3416. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3417. RemoveInstruction(hp1);
  3418. Result:=true;
  3419. Exit;
  3420. end;
  3421. top_ref:
  3422. begin
  3423. {$ifdef x86_64}
  3424. { Look for the following to simplify:
  3425. mov x(mem1), %reg
  3426. mov %reg, y(mem2)
  3427. mov x+8(mem1), %reg
  3428. mov %reg, y+8(mem2)
  3429. Change to:
  3430. movdqu x(mem1), %xmmreg
  3431. movdqu %xmmreg, y(mem2)
  3432. ...but only as long as the memory blocks don't overlap
  3433. }
  3434. SourceRef := taicpu(p).oper[0]^.ref^;
  3435. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3436. if (taicpu(p).opsize = S_Q) and
  3437. GetNextInstruction(hp1, hp2) and
  3438. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3439. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3440. begin
  3441. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3442. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3443. Inc(SourceRef.offset, 8);
  3444. if UseAVX then
  3445. begin
  3446. MovAligned := A_VMOVDQA;
  3447. MovUnaligned := A_VMOVDQU;
  3448. end
  3449. else
  3450. begin
  3451. MovAligned := A_MOVDQA;
  3452. MovUnaligned := A_MOVDQU;
  3453. end;
  3454. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3455. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3456. begin
  3457. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3458. Inc(TargetRef.offset, 8);
  3459. if GetNextInstruction(hp2, hp3) and
  3460. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3461. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3462. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3463. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3464. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3465. begin
  3466. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3467. if NewMMReg <> NR_NO then
  3468. begin
  3469. { Remember that the offsets are 8 ahead }
  3470. if ((SourceRef.offset mod 16) = 8) and
  3471. (
  3472. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3473. (SourceRef.base = current_procinfo.framepointer) or
  3474. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3475. ) then
  3476. taicpu(p).opcode := MovAligned
  3477. else
  3478. taicpu(p).opcode := MovUnaligned;
  3479. taicpu(p).opsize := S_XMM;
  3480. taicpu(p).oper[1]^.reg := NewMMReg;
  3481. if ((TargetRef.offset mod 16) = 8) and
  3482. (
  3483. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3484. (TargetRef.base = current_procinfo.framepointer) or
  3485. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3486. ) then
  3487. taicpu(hp1).opcode := MovAligned
  3488. else
  3489. taicpu(hp1).opcode := MovUnaligned;
  3490. taicpu(hp1).opsize := S_XMM;
  3491. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3492. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3493. RemoveInstruction(hp2);
  3494. RemoveInstruction(hp3);
  3495. Result := True;
  3496. Exit;
  3497. end;
  3498. end;
  3499. end
  3500. else
  3501. begin
  3502. { See if the next references are 8 less rather than 8 greater }
  3503. Dec(SourceRef.offset, 16); { -8 the other way }
  3504. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3505. begin
  3506. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3507. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3508. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3509. GetNextInstruction(hp2, hp3) and
  3510. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3511. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3512. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3513. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3514. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3515. begin
  3516. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3517. if NewMMReg <> NR_NO then
  3518. begin
  3519. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3520. if ((SourceRef.offset mod 16) = 0) and
  3521. (
  3522. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3523. (SourceRef.base = current_procinfo.framepointer) or
  3524. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3525. ) then
  3526. taicpu(hp2).opcode := MovAligned
  3527. else
  3528. taicpu(hp2).opcode := MovUnaligned;
  3529. taicpu(hp2).opsize := S_XMM;
  3530. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3531. if ((TargetRef.offset mod 16) = 0) and
  3532. (
  3533. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3534. (TargetRef.base = current_procinfo.framepointer) or
  3535. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3536. ) then
  3537. taicpu(hp3).opcode := MovAligned
  3538. else
  3539. taicpu(hp3).opcode := MovUnaligned;
  3540. taicpu(hp3).opsize := S_XMM;
  3541. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3542. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3543. RemoveInstruction(hp1);
  3544. RemoveCurrentP(p, hp2);
  3545. Result := True;
  3546. Exit;
  3547. end;
  3548. end;
  3549. end;
  3550. end;
  3551. end;
  3552. {$endif x86_64}
  3553. end;
  3554. else
  3555. { The write target should be a reg or a ref }
  3556. InternalError(2021091601);
  3557. end;
  3558. else
  3559. ;
  3560. end
  3561. else
  3562. { %treg is used afterwards, but all eventualities
  3563. other than the first MOV instruction being a constant
  3564. are covered by DeepMOVOpt, so only check for that }
  3565. if (taicpu(p).oper[0]^.typ = top_const) and
  3566. (
  3567. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3568. not (cs_opt_size in current_settings.optimizerswitches) or
  3569. (taicpu(hp1).opsize = S_B)
  3570. ) and
  3571. (
  3572. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3573. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3574. ) then
  3575. begin
  3576. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3577. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3578. end;
  3579. end;
  3580. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3581. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3582. { mov reg1, mem1 or mov mem1, reg1
  3583. mov mem2, reg2 mov reg2, mem2}
  3584. begin
  3585. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3586. { mov reg1, mem1 or mov mem1, reg1
  3587. mov mem2, reg1 mov reg2, mem1}
  3588. begin
  3589. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3590. { Removes the second statement from
  3591. mov reg1, mem1/reg2
  3592. mov mem1/reg2, reg1 }
  3593. begin
  3594. if taicpu(p).oper[0]^.typ=top_reg then
  3595. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3596. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3597. RemoveInstruction(hp1);
  3598. Result:=true;
  3599. exit;
  3600. end
  3601. else
  3602. begin
  3603. TransferUsedRegs(TmpUsedRegs);
  3604. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3605. if (taicpu(p).oper[1]^.typ = top_ref) and
  3606. { mov reg1, mem1
  3607. mov mem2, reg1 }
  3608. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3609. GetNextInstruction(hp1, hp2) and
  3610. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3611. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3612. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3613. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3614. { change to
  3615. mov reg1, mem1 mov reg1, mem1
  3616. mov mem2, reg1 cmp reg1, mem2
  3617. cmp mem1, reg1
  3618. }
  3619. begin
  3620. RemoveInstruction(hp2);
  3621. taicpu(hp1).opcode := A_CMP;
  3622. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3623. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3624. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3625. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3626. end;
  3627. end;
  3628. end
  3629. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3630. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3631. begin
  3632. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3633. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3634. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3635. end
  3636. else
  3637. begin
  3638. TransferUsedRegs(TmpUsedRegs);
  3639. if GetNextInstruction(hp1, hp2) and
  3640. MatchOpType(taicpu(p),top_ref,top_reg) and
  3641. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3642. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3643. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3644. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3645. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3646. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3647. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3648. { mov mem1, %reg1
  3649. mov %reg1, mem2
  3650. mov mem2, reg2
  3651. to:
  3652. mov mem1, reg2
  3653. mov reg2, mem2}
  3654. begin
  3655. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3656. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3657. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3658. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3659. RemoveInstruction(hp2);
  3660. Result := True;
  3661. end
  3662. {$ifdef i386}
  3663. { this is enabled for i386 only, as the rules to create the reg sets below
  3664. are too complicated for x86-64, so this makes this code too error prone
  3665. on x86-64
  3666. }
  3667. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3668. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3669. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3670. { mov mem1, reg1 mov mem1, reg1
  3671. mov reg1, mem2 mov reg1, mem2
  3672. mov mem2, reg2 mov mem2, reg1
  3673. to: to:
  3674. mov mem1, reg1 mov mem1, reg1
  3675. mov mem1, reg2 mov reg1, mem2
  3676. mov reg1, mem2
  3677. or (if mem1 depends on reg1
  3678. and/or if mem2 depends on reg2)
  3679. to:
  3680. mov mem1, reg1
  3681. mov reg1, mem2
  3682. mov reg1, reg2
  3683. }
  3684. begin
  3685. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3686. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3687. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3688. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3689. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3690. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3691. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3692. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3693. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3694. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3695. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3696. end
  3697. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3698. begin
  3699. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3700. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3701. end
  3702. else
  3703. begin
  3704. RemoveInstruction(hp2);
  3705. end
  3706. {$endif i386}
  3707. ;
  3708. end;
  3709. end
  3710. { movl [mem1],reg1
  3711. movl [mem1],reg2
  3712. to
  3713. movl [mem1],reg1
  3714. movl reg1,reg2
  3715. }
  3716. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3717. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3718. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3719. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3720. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3721. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3722. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3723. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3724. begin
  3725. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3726. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3727. end;
  3728. { movl const1,[mem1]
  3729. movl [mem1],reg1
  3730. to
  3731. movl const1,reg1
  3732. movl reg1,[mem1]
  3733. }
  3734. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3735. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3736. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3737. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3738. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3739. begin
  3740. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3741. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3742. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3743. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3744. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3745. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3746. Result:=true;
  3747. exit;
  3748. end;
  3749. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3750. { Change:
  3751. movl %reg1,%reg2
  3752. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3753. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3754. To:
  3755. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3756. movl x(%reg1),%reg1
  3757. movl %reg1,%regX
  3758. }
  3759. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3760. begin
  3761. p_SourceReg := taicpu(p).oper[0]^.reg;
  3762. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3763. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3764. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3765. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3766. GetNextInstruction(hp1, hp2) and
  3767. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3768. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3769. begin
  3770. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3771. if RegInRef(p_TargetReg, SourceRef) and
  3772. { If %reg1 also appears in the second reference, then it will
  3773. not refer to the same memory block as the first reference }
  3774. not RegInRef(p_SourceReg, SourceRef) then
  3775. begin
  3776. { Check to see if the references match if %reg2 is changed to %reg1 }
  3777. if SourceRef.base = p_TargetReg then
  3778. SourceRef.base := p_SourceReg;
  3779. if SourceRef.index = p_TargetReg then
  3780. SourceRef.index := p_SourceReg;
  3781. { RefsEqual also checks to ensure both references are non-volatile }
  3782. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3783. begin
  3784. taicpu(hp2).loadreg(0, p_SourceReg);
  3785. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3786. Result := True;
  3787. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3788. begin
  3789. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3790. RemoveCurrentP(p, hp1);
  3791. Exit;
  3792. end
  3793. else
  3794. begin
  3795. { Check to see if %reg2 is no longer in use }
  3796. TransferUsedRegs(TmpUsedRegs);
  3797. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3798. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3799. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3800. begin
  3801. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3802. RemoveCurrentP(p, hp1);
  3803. Exit;
  3804. end;
  3805. end;
  3806. { If we reach this point, p and hp1 weren't actually modified,
  3807. so we can do a bit more work on this pass }
  3808. end;
  3809. end;
  3810. end;
  3811. end;
  3812. end;
  3813. {$ifdef x86_64}
  3814. { Change:
  3815. movl %reg1l,%reg2l
  3816. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3817. To:
  3818. movl %reg1l,%reg2l
  3819. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3820. If %reg1 = %reg3, convert to:
  3821. movl %reg1l,%reg2l
  3822. andl %reg1l,%reg1l
  3823. }
  3824. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3825. MatchOpType(taicpu(p), top_reg, top_reg) and
  3826. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3827. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3828. begin
  3829. TransferUsedRegs(TmpUsedRegs);
  3830. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3831. taicpu(hp1).opsize := S_L;
  3832. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3833. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3834. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3835. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3836. begin
  3837. { %reg1 = %reg3 }
  3838. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3839. taicpu(hp1).opcode := A_AND;
  3840. end
  3841. else
  3842. begin
  3843. { %reg1 <> %reg3 }
  3844. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3845. end;
  3846. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3847. begin
  3848. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3849. RemoveCurrentP(p, hp1);
  3850. Result := True;
  3851. Exit;
  3852. end
  3853. else
  3854. begin
  3855. { Initial instruction wasn't actually changed }
  3856. Include(OptsToCheck, aoc_ForceNewIteration);
  3857. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3858. appears below since %reg1 has technically changed }
  3859. if taicpu(hp1).opcode = A_AND then
  3860. Exit;
  3861. end;
  3862. end;
  3863. {$endif x86_64}
  3864. { search further than the next instruction for a mov (as long as it's not a jump) }
  3865. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3866. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3867. (taicpu(p).oper[1]^.typ = top_reg) and
  3868. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3869. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3870. begin
  3871. { we work with hp2 here, so hp1 can be still used later on when
  3872. checking for GetNextInstruction_p }
  3873. hp3 := hp1;
  3874. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3875. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3876. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3877. TransferUsedRegs(TmpUsedRegs);
  3878. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3879. if NotFirstIteration then
  3880. JumpTracking := TLinkedList.Create
  3881. else
  3882. JumpTracking := nil;
  3883. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3884. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3885. (hp2.typ=ait_instruction) do
  3886. begin
  3887. case taicpu(hp2).opcode of
  3888. A_POP:
  3889. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3890. begin
  3891. if not CrossJump and
  3892. not RegUsedBetween(p_TargetReg, p, hp2) then
  3893. begin
  3894. { We can remove the original MOV since the register
  3895. wasn't used between it and its popping from the stack }
  3896. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3897. RemoveCurrentp(p, hp1);
  3898. Result := True;
  3899. JumpTracking.Free;
  3900. Exit;
  3901. end;
  3902. { Can't go any further }
  3903. Break;
  3904. end;
  3905. A_MOV:
  3906. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3907. ((taicpu(p).oper[0]^.typ=top_const) or
  3908. ((taicpu(p).oper[0]^.typ=top_reg) and
  3909. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3910. )
  3911. ) then
  3912. begin
  3913. { we have
  3914. mov x, %treg
  3915. mov %treg, y
  3916. }
  3917. { We don't need to call UpdateUsedRegs for every instruction between
  3918. p and hp2 because the register we're concerned about will not
  3919. become deallocated (otherwise GetNextInstructionUsingReg would
  3920. have stopped at an earlier instruction). [Kit] }
  3921. TempRegUsed :=
  3922. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3923. RegReadByInstruction(p_TargetReg, hp3) or
  3924. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3925. case taicpu(p).oper[0]^.typ Of
  3926. top_reg:
  3927. begin
  3928. { change
  3929. mov %reg, %treg
  3930. mov %treg, y
  3931. to
  3932. mov %reg, y
  3933. }
  3934. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3935. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3936. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3937. begin
  3938. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3939. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3940. if TempRegUsed then
  3941. begin
  3942. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3943. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3944. { Set the start of the next GetNextInstructionUsingRegCond search
  3945. to start at the entry right before hp2 (which is about to be removed) }
  3946. hp3 := tai(hp2.Previous);
  3947. RemoveInstruction(hp2);
  3948. Include(OptsToCheck, aoc_ForceNewIteration);
  3949. { See if there's more we can optimise }
  3950. Continue;
  3951. end
  3952. else
  3953. begin
  3954. RemoveInstruction(hp2);
  3955. { We can remove the original MOV too }
  3956. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3957. RemoveCurrentP(p, hp1);
  3958. Result:=true;
  3959. JumpTracking.Free;
  3960. Exit;
  3961. end;
  3962. end
  3963. else
  3964. begin
  3965. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3966. taicpu(hp2).loadReg(0, p_SourceReg);
  3967. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3968. { Check to see if the register also appears in the reference }
  3969. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3970. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3971. { Don't remove the first instruction if the temporary register is in use }
  3972. if not TempRegUsed and
  3973. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3974. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3975. begin
  3976. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3977. RemoveCurrentP(p, hp1);
  3978. Result:=true;
  3979. JumpTracking.Free;
  3980. Exit;
  3981. end;
  3982. { No need to set Result to True here. If there's another instruction later
  3983. on that can be optimised, it will be detected when the main Pass 1 loop
  3984. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3985. end;
  3986. end;
  3987. top_const:
  3988. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3989. begin
  3990. { change
  3991. mov const, %treg
  3992. mov %treg, y
  3993. to
  3994. mov const, y
  3995. }
  3996. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3997. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3998. begin
  3999. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4000. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4001. if TempRegUsed then
  4002. begin
  4003. { Don't remove the first instruction if the temporary register is in use }
  4004. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4005. { No need to set Result to True. If there's another instruction later on
  4006. that can be optimised, it will be detected when the main Pass 1 loop
  4007. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4008. end
  4009. else
  4010. begin
  4011. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4012. RemoveCurrentP(p, hp1);
  4013. Result:=true;
  4014. Exit;
  4015. end;
  4016. end;
  4017. end;
  4018. else
  4019. Internalerror(2019103001);
  4020. end;
  4021. end
  4022. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4023. begin
  4024. if not CrossJump and
  4025. not RegUsedBetween(p_TargetReg, p, hp2) and
  4026. not RegReadByInstruction(p_TargetReg, hp2) then
  4027. begin
  4028. { Register is not used before it is overwritten }
  4029. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4030. RemoveCurrentp(p, hp1);
  4031. Result := True;
  4032. Exit;
  4033. end;
  4034. if (taicpu(p).oper[0]^.typ = top_const) and
  4035. (taicpu(hp2).oper[0]^.typ = top_const) then
  4036. begin
  4037. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4038. begin
  4039. { Same value - register hasn't changed }
  4040. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4041. RemoveInstruction(hp2);
  4042. Include(OptsToCheck, aoc_ForceNewIteration);
  4043. { See if there's more we can optimise }
  4044. Continue;
  4045. end;
  4046. end;
  4047. {$ifdef x86_64}
  4048. end
  4049. { Change:
  4050. movl %reg1l,%reg2l
  4051. ...
  4052. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4053. To:
  4054. movl %reg1l,%reg2l
  4055. ...
  4056. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4057. If %reg1 = %reg3, convert to:
  4058. movl %reg1l,%reg2l
  4059. ...
  4060. andl %reg1l,%reg1l
  4061. }
  4062. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4063. (taicpu(p).oper[0]^.typ = top_reg) and
  4064. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4065. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4066. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4067. begin
  4068. TempRegUsed :=
  4069. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4070. RegReadByInstruction(p_TargetReg, hp3) or
  4071. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4072. taicpu(hp2).opsize := S_L;
  4073. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4074. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4075. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4076. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4077. begin
  4078. { %reg1 = %reg3 }
  4079. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4080. taicpu(hp2).opcode := A_AND;
  4081. end
  4082. else
  4083. begin
  4084. { %reg1 <> %reg3 }
  4085. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4086. end;
  4087. if not TempRegUsed then
  4088. begin
  4089. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4090. RemoveCurrentP(p, hp1);
  4091. Result := True;
  4092. Exit;
  4093. end
  4094. else
  4095. begin
  4096. { Initial instruction wasn't actually changed }
  4097. Include(OptsToCheck, aoc_ForceNewIteration);
  4098. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4099. appears below since %reg1 has technically changed }
  4100. if taicpu(hp2).opcode = A_AND then
  4101. Break;
  4102. end;
  4103. {$endif x86_64}
  4104. end;
  4105. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4106. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4107. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4108. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4109. begin
  4110. {
  4111. Change from:
  4112. mov ###, %reg
  4113. ...
  4114. movs/z %reg,%reg (Same register, just different sizes)
  4115. To:
  4116. movs/z ###, %reg (Longer version)
  4117. ...
  4118. (remove)
  4119. }
  4120. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4121. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4122. { Keep the first instruction as mov if ### is a constant }
  4123. if taicpu(p).oper[0]^.typ = top_const then
  4124. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4125. else
  4126. begin
  4127. taicpu(p).opcode := taicpu(hp2).opcode;
  4128. taicpu(p).opsize := taicpu(hp2).opsize;
  4129. end;
  4130. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4131. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4132. RemoveInstruction(hp2);
  4133. Result := True;
  4134. JumpTracking.Free;
  4135. Exit;
  4136. end;
  4137. else
  4138. { Move down to the if-block below };
  4139. end;
  4140. { Also catches MOV/S/Z instructions that aren't modified }
  4141. if taicpu(p).oper[0]^.typ = top_reg then
  4142. begin
  4143. p_SourceReg := taicpu(p).oper[0]^.reg;
  4144. if
  4145. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4146. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4147. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4148. begin
  4149. Result := True;
  4150. { Just in case something didn't get modified (e.g. an
  4151. implicit register). Also, if it does read from this
  4152. register, then there's no longer an advantage to
  4153. changing the register on subsequent instructions.}
  4154. if not RegReadByInstruction(p_TargetReg, hp2) then
  4155. begin
  4156. { If a conditional jump was crossed, do not delete
  4157. the original MOV no matter what }
  4158. if not CrossJump and
  4159. { RegEndOfLife returns True if the register is
  4160. deallocated before the next instruction or has
  4161. been loaded with a new value }
  4162. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4163. begin
  4164. { We can remove the original MOV }
  4165. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4166. RemoveCurrentp(p, hp1);
  4167. JumpTracking.Free;
  4168. Result := True;
  4169. Exit;
  4170. end;
  4171. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4172. begin
  4173. { See if there's more we can optimise }
  4174. hp3 := hp2;
  4175. Continue;
  4176. end;
  4177. end;
  4178. end;
  4179. end;
  4180. { Break out of the while loop under normal circumstances }
  4181. Break;
  4182. end;
  4183. JumpTracking.Free;
  4184. end;
  4185. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4186. (taicpu(p).oper[1]^.typ = top_reg) and
  4187. (taicpu(p).opsize = S_L) and
  4188. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4189. (hp2.typ = ait_instruction) and
  4190. (taicpu(hp2).opcode = A_AND) and
  4191. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4192. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4193. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4194. ) then
  4195. begin
  4196. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4197. begin
  4198. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4199. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4200. begin
  4201. { Optimize out:
  4202. mov x, %reg
  4203. and ffffffffh, %reg
  4204. }
  4205. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4206. RemoveInstruction(hp2);
  4207. Result:=true;
  4208. exit;
  4209. end;
  4210. end;
  4211. end;
  4212. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4213. x >= RetOffset) as it doesn't do anything (it writes either to a
  4214. parameter or to the temporary storage room for the function
  4215. result)
  4216. }
  4217. if IsExitCode(hp1) and
  4218. (taicpu(p).oper[1]^.typ = top_ref) and
  4219. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4220. (
  4221. (
  4222. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4223. not (
  4224. assigned(current_procinfo.procdef.funcretsym) and
  4225. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4226. )
  4227. ) or
  4228. { Also discard writes to the stack that are below the base pointer,
  4229. as this is temporary storage rather than a function result on the
  4230. stack, say. }
  4231. (
  4232. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4233. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4234. )
  4235. ) then
  4236. begin
  4237. RemoveCurrentp(p, hp1);
  4238. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4239. RemoveLastDeallocForFuncRes(p);
  4240. Result:=true;
  4241. exit;
  4242. end;
  4243. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4244. begin
  4245. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4246. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4247. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4248. begin
  4249. { change
  4250. mov reg1, mem1
  4251. test/cmp x, mem1
  4252. to
  4253. mov reg1, mem1
  4254. test/cmp x, reg1
  4255. }
  4256. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4257. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4258. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4259. Result := True;
  4260. Exit;
  4261. end;
  4262. if DoMovCmpMemOpt(p, hp1) then
  4263. begin
  4264. Result := True;
  4265. Exit;
  4266. end;
  4267. end;
  4268. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4269. { If the flags register is in use, don't change the instruction to an
  4270. ADD otherwise this will scramble the flags. [Kit] }
  4271. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4272. begin
  4273. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4274. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4275. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4276. ) or
  4277. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4278. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4279. )
  4280. ) then
  4281. { mov reg1,ref
  4282. lea reg2,[reg1,reg2]
  4283. to
  4284. add reg2,ref}
  4285. begin
  4286. TransferUsedRegs(TmpUsedRegs);
  4287. { reg1 may not be used afterwards }
  4288. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4289. begin
  4290. Taicpu(hp1).opcode:=A_ADD;
  4291. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4292. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4293. RemoveCurrentp(p, hp1);
  4294. result:=true;
  4295. exit;
  4296. end;
  4297. end;
  4298. { If the LEA instruction can be converted into an arithmetic instruction,
  4299. it may be possible to then fold it in the next optimisation, otherwise
  4300. there's nothing more that can be optimised here. }
  4301. if not ConvertLEA(taicpu(hp1)) then
  4302. Exit;
  4303. end;
  4304. if (taicpu(p).oper[1]^.typ = top_reg) and
  4305. (hp1.typ = ait_instruction) and
  4306. GetNextInstruction(hp1, hp2) and
  4307. MatchInstruction(hp2,A_MOV,[]) and
  4308. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4309. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4310. (
  4311. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4312. {$ifdef x86_64}
  4313. or
  4314. (
  4315. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4316. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4317. )
  4318. {$endif x86_64}
  4319. ) then
  4320. begin
  4321. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4322. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4323. { change movsX/movzX reg/ref, reg2
  4324. add/sub/or/... reg3/$const, reg2
  4325. mov reg2 reg/ref
  4326. dealloc reg2
  4327. to
  4328. add/sub/or/... reg3/$const, reg/ref }
  4329. begin
  4330. TransferUsedRegs(TmpUsedRegs);
  4331. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4332. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4333. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4334. begin
  4335. { by example:
  4336. movswl %si,%eax movswl %si,%eax p
  4337. decl %eax addl %edx,%eax hp1
  4338. movw %ax,%si movw %ax,%si hp2
  4339. ->
  4340. movswl %si,%eax movswl %si,%eax p
  4341. decw %eax addw %edx,%eax hp1
  4342. movw %ax,%si movw %ax,%si hp2
  4343. }
  4344. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4345. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4346. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4347. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4348. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4349. {
  4350. ->
  4351. movswl %si,%eax movswl %si,%eax p
  4352. decw %si addw %dx,%si hp1
  4353. movw %ax,%si movw %ax,%si hp2
  4354. }
  4355. case taicpu(hp1).ops of
  4356. 1:
  4357. begin
  4358. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4359. if taicpu(hp1).oper[0]^.typ=top_reg then
  4360. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4361. end;
  4362. 2:
  4363. begin
  4364. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4365. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4366. (taicpu(hp1).opcode<>A_SHL) and
  4367. (taicpu(hp1).opcode<>A_SHR) and
  4368. (taicpu(hp1).opcode<>A_SAR) then
  4369. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4370. end;
  4371. else
  4372. internalerror(2008042701);
  4373. end;
  4374. {
  4375. ->
  4376. decw %si addw %dx,%si p
  4377. }
  4378. RemoveInstruction(hp2);
  4379. RemoveCurrentP(p, hp1);
  4380. Result:=True;
  4381. Exit;
  4382. end;
  4383. end;
  4384. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4385. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4386. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4387. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4388. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4389. )
  4390. {$ifdef i386}
  4391. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4392. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4393. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4394. {$endif i386}
  4395. then
  4396. { change movsX/movzX reg/ref, reg2
  4397. add/sub/or/... regX/$const, reg2
  4398. mov reg2, reg3
  4399. dealloc reg2
  4400. to
  4401. movsX/movzX reg/ref, reg3
  4402. add/sub/or/... reg3/$const, reg3
  4403. }
  4404. begin
  4405. TransferUsedRegs(TmpUsedRegs);
  4406. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4407. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4408. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4409. begin
  4410. { by example:
  4411. movswl %si,%eax movswl %si,%eax p
  4412. decl %eax addl %edx,%eax hp1
  4413. movw %ax,%si movw %ax,%si hp2
  4414. ->
  4415. movswl %si,%eax movswl %si,%eax p
  4416. decw %eax addw %edx,%eax hp1
  4417. movw %ax,%si movw %ax,%si hp2
  4418. }
  4419. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4420. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4421. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4422. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4423. { limit size of constants as well to avoid assembler errors, but
  4424. check opsize to avoid overflow when left shifting the 1 }
  4425. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4426. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4427. {$ifdef x86_64}
  4428. { Be careful of, for example:
  4429. movl %reg1,%reg2
  4430. addl %reg3,%reg2
  4431. movq %reg2,%reg4
  4432. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4433. }
  4434. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4435. begin
  4436. taicpu(hp2).changeopsize(S_L);
  4437. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4438. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4439. end;
  4440. {$endif x86_64}
  4441. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4442. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4443. if taicpu(p).oper[0]^.typ=top_reg then
  4444. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4445. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4446. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4447. {
  4448. ->
  4449. movswl %si,%eax movswl %si,%eax p
  4450. decw %si addw %dx,%si hp1
  4451. movw %ax,%si movw %ax,%si hp2
  4452. }
  4453. case taicpu(hp1).ops of
  4454. 1:
  4455. begin
  4456. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4457. if taicpu(hp1).oper[0]^.typ=top_reg then
  4458. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4459. end;
  4460. 2:
  4461. begin
  4462. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4463. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4464. (taicpu(hp1).opcode<>A_SHL) and
  4465. (taicpu(hp1).opcode<>A_SHR) and
  4466. (taicpu(hp1).opcode<>A_SAR) then
  4467. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4468. end;
  4469. else
  4470. internalerror(2018111801);
  4471. end;
  4472. {
  4473. ->
  4474. decw %si addw %dx,%si p
  4475. }
  4476. RemoveInstruction(hp2);
  4477. end;
  4478. end;
  4479. end;
  4480. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4481. GetNextInstruction(hp1, hp2) and
  4482. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4483. MatchOperand(Taicpu(p).oper[0]^,0) and
  4484. (Taicpu(p).oper[1]^.typ = top_reg) and
  4485. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4486. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4487. { mov reg1,0
  4488. bts reg1,operand1 --> mov reg1,operand2
  4489. or reg1,operand2 bts reg1,operand1}
  4490. begin
  4491. Taicpu(hp2).opcode:=A_MOV;
  4492. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4493. asml.remove(hp1);
  4494. insertllitem(hp2,hp2.next,hp1);
  4495. RemoveCurrentp(p, hp1);
  4496. Result:=true;
  4497. exit;
  4498. end;
  4499. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4500. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4501. GetNextInstruction(hp1, hp2) and
  4502. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4503. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4504. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4505. { change
  4506. mov reg1,reg2
  4507. sub reg3,reg2
  4508. cmp reg3,reg1
  4509. into
  4510. mov reg1,reg2
  4511. sub reg3,reg2
  4512. }
  4513. begin
  4514. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4515. RemoveInstruction(hp2);
  4516. Result:=true;
  4517. exit;
  4518. end;
  4519. {
  4520. mov ref,reg0
  4521. <op> reg0,reg1
  4522. dealloc reg0
  4523. to
  4524. <op> ref,reg1
  4525. }
  4526. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4527. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4528. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4529. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4530. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4531. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4532. begin
  4533. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4534. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4535. RemoveCurrentp(p, hp1);
  4536. Result:=true;
  4537. exit;
  4538. end;
  4539. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4540. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4541. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4542. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4543. begin
  4544. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4545. {$ifdef x86_64}
  4546. { Convert:
  4547. movq x(ref),%reg64
  4548. shrq y,%reg64
  4549. To:
  4550. movl x+4(ref),%reg32
  4551. shrl y-32,%reg32 (Remove if y = 32)
  4552. }
  4553. if (taicpu(p).opsize = S_Q) and
  4554. (taicpu(hp1).opcode = A_SHR) and
  4555. (taicpu(hp1).oper[0]^.val >= 32) then
  4556. begin
  4557. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4558. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4559. { Convert to 32-bit }
  4560. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4561. taicpu(p).opsize := S_L;
  4562. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4563. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4564. if (taicpu(hp1).oper[0]^.val = 32) then
  4565. begin
  4566. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4567. RemoveInstruction(hp1);
  4568. end
  4569. else
  4570. begin
  4571. { This will potentially open up more arithmetic operations since
  4572. the peephole optimizer now has a big hint that only the lower
  4573. 32 bits are currently in use (and opcodes are smaller in size) }
  4574. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4575. taicpu(hp1).opsize := S_L;
  4576. Dec(taicpu(hp1).oper[0]^.val, 32);
  4577. DebugMsg(SPeepholeOptimization + PreMessage +
  4578. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4579. end;
  4580. Result := True;
  4581. Exit;
  4582. end;
  4583. {$endif x86_64}
  4584. { Convert:
  4585. movl x(ref),%reg
  4586. shrl $24,%reg
  4587. To:
  4588. movzbl x+3(ref),%reg
  4589. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4590. Also accept sar instead of shr, but convert to movsx instead of movzx
  4591. }
  4592. if taicpu(hp1).opcode = A_SHR then
  4593. MovUnaligned := A_MOVZX
  4594. else
  4595. MovUnaligned := A_MOVSX;
  4596. NewSize := S_NO;
  4597. NewOffset := 0;
  4598. case taicpu(p).opsize of
  4599. S_B:
  4600. { No valid combinations };
  4601. S_W:
  4602. if (taicpu(hp1).oper[0]^.val = 8) then
  4603. begin
  4604. NewSize := S_BW;
  4605. NewOffset := 1;
  4606. end;
  4607. S_L:
  4608. case taicpu(hp1).oper[0]^.val of
  4609. 16:
  4610. begin
  4611. NewSize := S_WL;
  4612. NewOffset := 2;
  4613. end;
  4614. 24:
  4615. begin
  4616. NewSize := S_BL;
  4617. NewOffset := 3;
  4618. end;
  4619. else
  4620. ;
  4621. end;
  4622. {$ifdef x86_64}
  4623. S_Q:
  4624. case taicpu(hp1).oper[0]^.val of
  4625. 32:
  4626. begin
  4627. if taicpu(hp1).opcode = A_SAR then
  4628. begin
  4629. { 32-bit to 64-bit is a distinct instruction }
  4630. MovUnaligned := A_MOVSXD;
  4631. NewSize := S_LQ;
  4632. NewOffset := 4;
  4633. end
  4634. else
  4635. { Should have been handled by MovShr2Mov above }
  4636. InternalError(2022081811);
  4637. end;
  4638. 48:
  4639. begin
  4640. NewSize := S_WQ;
  4641. NewOffset := 6;
  4642. end;
  4643. 56:
  4644. begin
  4645. NewSize := S_BQ;
  4646. NewOffset := 7;
  4647. end;
  4648. else
  4649. ;
  4650. end;
  4651. {$endif x86_64}
  4652. else
  4653. InternalError(2022081810);
  4654. end;
  4655. if (NewSize <> S_NO) and
  4656. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4657. begin
  4658. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4659. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4660. debug_op2str(MovUnaligned);
  4661. {$ifdef x86_64}
  4662. if MovUnaligned <> A_MOVSXD then
  4663. { Don't add size suffix for MOVSXD }
  4664. {$endif x86_64}
  4665. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4666. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4667. taicpu(p).opcode := MovUnaligned;
  4668. taicpu(p).opsize := NewSize;
  4669. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4670. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4671. RemoveInstruction(hp1);
  4672. Result := True;
  4673. Exit;
  4674. end;
  4675. end;
  4676. { Backward optimisation shared with OptPass2MOV }
  4677. if FuncMov2Func(p, hp1) then
  4678. begin
  4679. Result := True;
  4680. Exit;
  4681. end;
  4682. end;
  4683. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4684. var
  4685. hp1 : tai;
  4686. begin
  4687. Result:=false;
  4688. if taicpu(p).ops <> 2 then
  4689. exit;
  4690. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4691. GetNextInstruction(p,hp1) then
  4692. begin
  4693. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4694. (taicpu(hp1).ops = 2) then
  4695. begin
  4696. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4697. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4698. { movXX reg1, mem1 or movXX mem1, reg1
  4699. movXX mem2, reg2 movXX reg2, mem2}
  4700. begin
  4701. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4702. { movXX reg1, mem1 or movXX mem1, reg1
  4703. movXX mem2, reg1 movXX reg2, mem1}
  4704. begin
  4705. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4706. begin
  4707. { Removes the second statement from
  4708. movXX reg1, mem1/reg2
  4709. movXX mem1/reg2, reg1
  4710. }
  4711. if taicpu(p).oper[0]^.typ=top_reg then
  4712. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4713. { Removes the second statement from
  4714. movXX mem1/reg1, reg2
  4715. movXX reg2, mem1/reg1
  4716. }
  4717. if (taicpu(p).oper[1]^.typ=top_reg) and
  4718. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4719. begin
  4720. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4721. RemoveInstruction(hp1);
  4722. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4723. Result:=true;
  4724. exit;
  4725. end
  4726. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4727. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4728. begin
  4729. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4730. RemoveInstruction(hp1);
  4731. Result:=true;
  4732. exit;
  4733. end;
  4734. end
  4735. end;
  4736. end;
  4737. end;
  4738. end;
  4739. end;
  4740. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4741. var
  4742. hp1 : tai;
  4743. begin
  4744. result:=false;
  4745. { replace
  4746. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4747. MovX %mreg2,%mreg1
  4748. dealloc %mreg2
  4749. by
  4750. <Op>X %mreg2,%mreg1
  4751. ?
  4752. }
  4753. if GetNextInstruction(p,hp1) and
  4754. { we mix single and double opperations here because we assume that the compiler
  4755. generates vmovapd only after double operations and vmovaps only after single operations }
  4756. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4757. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4758. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4759. (taicpu(p).oper[0]^.typ=top_reg) then
  4760. begin
  4761. TransferUsedRegs(TmpUsedRegs);
  4762. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4763. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4764. begin
  4765. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4766. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4767. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4768. RemoveInstruction(hp1);
  4769. result:=true;
  4770. end;
  4771. end;
  4772. end;
  4773. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4774. var
  4775. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  4776. JumpLabel, JumpLabel_dist: TAsmLabel;
  4777. FirstValue, SecondValue: TCGInt;
  4778. TempBool: Boolean;
  4779. begin
  4780. Result := False;
  4781. if (taicpu(p).oper[0]^.typ = top_const) and
  4782. (taicpu(p).oper[0]^.val <> -1) then
  4783. begin
  4784. { Convert unsigned maximum constants to -1 to aid optimisation }
  4785. case taicpu(p).opsize of
  4786. S_B:
  4787. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4788. begin
  4789. taicpu(p).oper[0]^.val := -1;
  4790. Result := True;
  4791. Exit;
  4792. end;
  4793. S_W:
  4794. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4795. begin
  4796. taicpu(p).oper[0]^.val := -1;
  4797. Result := True;
  4798. Exit;
  4799. end;
  4800. S_L:
  4801. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4802. begin
  4803. taicpu(p).oper[0]^.val := -1;
  4804. Result := True;
  4805. Exit;
  4806. end;
  4807. {$ifdef x86_64}
  4808. S_Q:
  4809. { Storing anything greater than $7FFFFFFF is not possible so do
  4810. nothing };
  4811. {$endif x86_64}
  4812. else
  4813. InternalError(2021121001);
  4814. end;
  4815. end;
  4816. if GetNextInstruction(p, hp1) and
  4817. TrySwapMovCmp(p, hp1) then
  4818. begin
  4819. Result := True;
  4820. Exit;
  4821. end;
  4822. if MatchInstruction(hp1, A_Jcc, []) then
  4823. begin
  4824. TempBool := True;
  4825. if DoJumpOptimizations(hp1, TempBool) or
  4826. not TempBool then
  4827. begin
  4828. Result := True;
  4829. if Assigned(hp1) then
  4830. begin
  4831. if (hp1.typ in [ait_align]) then
  4832. SkipAligns(hp1, hp1);
  4833. { CollapseZeroDistJump will be set to the label after the
  4834. jump if it optimises, whether or not it's live or dead }
  4835. if (hp1.typ in [ait_label]) and
  4836. not (tai_label(hp1).labsym.is_used) then
  4837. GetNextInstruction(hp1, hp1);
  4838. end;
  4839. TransferUsedRegs(TmpUsedRegs);
  4840. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4841. if not Assigned(hp1) or
  4842. (
  4843. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4844. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4845. ) then
  4846. begin
  4847. { No more conditional jumps; conditional statement is no longer required }
  4848. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4849. RemoveCurrentP(p);
  4850. end;
  4851. Exit;
  4852. end;
  4853. end;
  4854. { Search for:
  4855. test $x,(reg/ref)
  4856. jne @lbl1
  4857. test $y,(reg/ref) (same register or reference)
  4858. jne @lbl1
  4859. Change to:
  4860. test $(x or y),(reg/ref)
  4861. jne @lbl1
  4862. (Note, this doesn't work with je instead of jne)
  4863. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4864. Also search for:
  4865. test $x,(reg/ref)
  4866. je @lbl1
  4867. ...
  4868. test $y,(reg/ref)
  4869. je/jne @lbl2
  4870. If (x or y) = x, then the second jump is deterministic
  4871. }
  4872. if (
  4873. (
  4874. (taicpu(p).oper[0]^.typ = top_const) or
  4875. (
  4876. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4877. (taicpu(p).oper[0]^.typ = top_reg) and
  4878. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4879. )
  4880. ) and
  4881. MatchInstruction(hp1, A_JCC, [])
  4882. ) then
  4883. begin
  4884. if (taicpu(p).oper[0]^.typ = top_reg) and
  4885. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4886. FirstValue := -1
  4887. else
  4888. FirstValue := taicpu(p).oper[0]^.val;
  4889. { If we have several test/jne's in a row, it might be the case that
  4890. the second label doesn't go to the same location, but the one
  4891. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4892. so accommodate for this with a while loop.
  4893. }
  4894. hp1_last := hp1;
  4895. while (
  4896. (
  4897. (taicpu(p).oper[1]^.typ = top_reg) and
  4898. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  4899. ) or GetNextInstruction(hp1_last, p_dist)
  4900. ) and (p_dist.typ = ait_instruction) do
  4901. begin
  4902. if (
  4903. (
  4904. (taicpu(p_dist).opcode = A_TEST) and
  4905. (
  4906. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4907. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4908. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4909. )
  4910. ) or
  4911. (
  4912. { cmp 0,%reg = test %reg,%reg }
  4913. (taicpu(p_dist).opcode = A_CMP) and
  4914. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4915. )
  4916. ) and
  4917. { Make sure the destination operands are actually the same }
  4918. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4919. GetNextInstruction(p_dist, hp1_dist) and
  4920. MatchInstruction(hp1_dist, A_JCC, []) then
  4921. begin
  4922. if
  4923. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4924. (
  4925. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4926. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4927. ) then
  4928. SecondValue := -1
  4929. else
  4930. SecondValue := taicpu(p_dist).oper[0]^.val;
  4931. { If both of the TEST constants are identical, delete the
  4932. second TEST that is unnecessary (be careful though, just
  4933. in case the flags are modified in between) }
  4934. if (FirstValue = SecondValue) then
  4935. begin
  4936. { We have to check the entire range }
  4937. TempBool := not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist);
  4938. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4939. begin
  4940. { Since the second jump's condition is a subset of the first, we
  4941. know it will never branch because the first jump dominates it.
  4942. Get it out of the way now rather than wait for the jump
  4943. optimisations for a speed boost. }
  4944. if IsJumpToLabel(taicpu(hp1_dist)) then
  4945. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4946. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4947. RemoveInstruction(hp1_dist);
  4948. Result := True;
  4949. end
  4950. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4951. begin
  4952. { If the inverse of the first condition is a subset of the second,
  4953. the second one will definitely branch if the first one doesn't }
  4954. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4955. { We can remove the TEST instruction too }
  4956. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4957. RemoveInstruction(p_dist);
  4958. MakeUnconditional(taicpu(hp1_dist));
  4959. RemoveDeadCodeAfterJump(hp1_dist);
  4960. { Since the jump is now unconditional, we can't
  4961. continue any further with this particular
  4962. optimisation. The original TEST is still intact
  4963. though, so there might be something else we can
  4964. do }
  4965. Include(OptsToCheck, aoc_ForceNewIteration);
  4966. Break;
  4967. end;
  4968. if Result or
  4969. { If a jump wasn't removed or made unconditional, only
  4970. remove the identical TEST instruction if the flags
  4971. weren't modified }
  4972. TempBool then
  4973. begin
  4974. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4975. RemoveInstruction(p_dist);
  4976. { If the jump was removed or made unconditional, we
  4977. don't need to allocate NR_DEFAULTFLAGS over the
  4978. entire range }
  4979. if not Result then
  4980. begin
  4981. { Mark the flags as 'in use' over the entire range }
  4982. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4983. { Speed gain - continue search from the Jcc instruction }
  4984. hp1_last := hp1_dist;
  4985. { Only the TEST instruction was removed, and the
  4986. original was unchanged, so we can safely do
  4987. another iteration of the while loop }
  4988. Include(OptsToCheck, aoc_ForceNewIteration);
  4989. Continue;
  4990. end;
  4991. Exit;
  4992. end;
  4993. end;
  4994. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4995. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4996. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4997. then the second jump will never branch, so it can also be
  4998. removed regardless of where it goes }
  4999. (
  5000. (FirstValue = -1) or
  5001. (SecondValue = -1) or
  5002. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5003. ) and
  5004. (
  5005. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5006. { Always adjacent under -O2 and under }
  5007. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5008. (
  5009. GetNextInstruction(hp1, hp1_last) and
  5010. (hp1_last = p_dist)
  5011. )
  5012. ) then
  5013. begin
  5014. { Same jump location... can be a register since nothing's changed }
  5015. { If any of the entries are equivalent to test %reg,%reg, then the
  5016. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5017. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5018. if IsJumpToLabel(taicpu(hp1_dist)) then
  5019. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5020. { Only remove the second test if no jumps or other conditional instructions follow }
  5021. TransferUsedRegs(TmpUsedRegs);
  5022. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5023. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5024. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5025. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5026. begin
  5027. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5028. RemoveInstruction(p_dist);
  5029. { Remove the first jump, not the second, to keep
  5030. any register deallocations between the second
  5031. TEST/JNE pair in the same place. Aids future
  5032. optimisation. }
  5033. RemoveInstruction(hp1);
  5034. end
  5035. else
  5036. begin
  5037. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5038. { Remove second jump in this instance }
  5039. RemoveInstruction(hp1_dist);
  5040. end;
  5041. Result := True;
  5042. Exit;
  5043. end;
  5044. end;
  5045. if { If -O2 and under, it may stop on any old instruction }
  5046. (cs_opt_level3 in current_settings.optimizerswitches) and
  5047. (taicpu(p).oper[1]^.typ = top_reg) and
  5048. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5049. begin
  5050. hp1_last := p_dist;
  5051. Continue;
  5052. end;
  5053. Break;
  5054. end;
  5055. end;
  5056. { Search for:
  5057. test %reg,%reg
  5058. j(c1) @lbl1
  5059. ...
  5060. @lbl:
  5061. test %reg,%reg (same register)
  5062. j(c2) @lbl2
  5063. If c2 is a subset of c1, change to:
  5064. test %reg,%reg
  5065. j(c1) @lbl2
  5066. (@lbl1 may become a dead label as a result)
  5067. }
  5068. if (taicpu(p).oper[1]^.typ = top_reg) and
  5069. (taicpu(p).oper[0]^.typ = top_reg) and
  5070. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5071. MatchInstruction(hp1, A_JCC, []) and
  5072. IsJumpToLabel(taicpu(hp1)) then
  5073. begin
  5074. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5075. p_label := nil;
  5076. if Assigned(JumpLabel) then
  5077. p_label := getlabelwithsym(JumpLabel);
  5078. if Assigned(p_label) and
  5079. GetNextInstruction(p_label, p_dist) and
  5080. MatchInstruction(p_dist, A_TEST, []) and
  5081. { It's fine if the second test uses smaller sub-registers }
  5082. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5083. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5084. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5085. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5086. GetNextInstruction(p_dist, hp1_dist) and
  5087. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5088. begin
  5089. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5090. if JumpLabel = JumpLabel_dist then
  5091. { This is an infinite loop }
  5092. Exit;
  5093. { Best optimisation when the first condition is a subset (or equal) of the second }
  5094. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5095. begin
  5096. { Any registers used here will already be allocated }
  5097. if Assigned(JumpLabel) then
  5098. JumpLabel.DecRefs;
  5099. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5100. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5101. Result := True;
  5102. Exit;
  5103. end;
  5104. end;
  5105. end;
  5106. end;
  5107. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5108. var
  5109. hp1, hp2: tai;
  5110. ActiveReg: TRegister;
  5111. OldOffset: asizeint;
  5112. ThisConst: TCGInt;
  5113. function RegDeallocated: Boolean;
  5114. begin
  5115. TransferUsedRegs(TmpUsedRegs);
  5116. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5117. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5118. end;
  5119. begin
  5120. result:=false;
  5121. hp1 := nil;
  5122. { replace
  5123. addX const,%reg1
  5124. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5125. dealloc %reg1
  5126. by
  5127. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5128. }
  5129. if MatchOpType(taicpu(p),top_const,top_reg) then
  5130. begin
  5131. ActiveReg := taicpu(p).oper[1]^.reg;
  5132. { Ensures the entire register was updated }
  5133. if (taicpu(p).opsize >= S_L) and
  5134. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5135. MatchInstruction(hp1,A_LEA,[]) and
  5136. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5137. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5138. (
  5139. { Cover the case where the register in the reference is also the destination register }
  5140. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5141. (
  5142. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5143. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5144. RegDeallocated
  5145. )
  5146. ) then
  5147. begin
  5148. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5149. {$push}
  5150. {$R-}{$Q-}
  5151. { Explicitly disable overflow checking for these offset calculation
  5152. as those do not matter for the final result }
  5153. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5154. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5155. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5156. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5157. {$pop}
  5158. {$ifdef x86_64}
  5159. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5160. begin
  5161. { Overflow; abort }
  5162. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5163. end
  5164. else
  5165. {$endif x86_64}
  5166. begin
  5167. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5168. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5169. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5170. RemoveCurrentP(p, hp1)
  5171. else
  5172. RemoveCurrentP(p);
  5173. result:=true;
  5174. Exit;
  5175. end;
  5176. end;
  5177. if (
  5178. { Save calling GetNextInstructionUsingReg again }
  5179. Assigned(hp1) or
  5180. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5181. ) and
  5182. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5183. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5184. begin
  5185. if taicpu(hp1).oper[0]^.typ = top_const then
  5186. begin
  5187. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5188. if taicpu(hp1).opcode = A_ADD then
  5189. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5190. else
  5191. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5192. Result := True;
  5193. { Handle any overflows }
  5194. case taicpu(p).opsize of
  5195. S_B:
  5196. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5197. S_W:
  5198. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5199. S_L:
  5200. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5201. {$ifdef x86_64}
  5202. S_Q:
  5203. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5204. { Overflow; abort }
  5205. Result := False
  5206. else
  5207. taicpu(p).oper[0]^.val := ThisConst;
  5208. {$endif x86_64}
  5209. else
  5210. InternalError(2021102610);
  5211. end;
  5212. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5213. if Result then
  5214. begin
  5215. if (taicpu(p).oper[0]^.val < 0) and
  5216. (
  5217. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5218. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5219. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5220. ) then
  5221. begin
  5222. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5223. taicpu(p).opcode := A_SUB;
  5224. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5225. end
  5226. else
  5227. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5228. RemoveInstruction(hp1);
  5229. end;
  5230. end
  5231. else
  5232. begin
  5233. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5234. TransferUsedRegs(TmpUsedRegs);
  5235. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5236. hp2 := p;
  5237. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5238. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5239. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5240. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5241. begin
  5242. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5243. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5244. Asml.Remove(p);
  5245. Asml.InsertAfter(p, hp1);
  5246. p := hp1;
  5247. Result := True;
  5248. Exit;
  5249. end;
  5250. end;
  5251. end;
  5252. if DoArithCombineOpt(p) then
  5253. Result:=true;
  5254. end;
  5255. end;
  5256. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5257. var
  5258. hp1, hp2: tai;
  5259. ref: Integer;
  5260. saveref: treference;
  5261. offsetcalc: Int64;
  5262. TempReg: TRegister;
  5263. Multiple: TCGInt;
  5264. Adjacent, IntermediateRegDiscarded: Boolean;
  5265. begin
  5266. Result:=false;
  5267. { play save and throw an error if LEA uses a seg register prefix,
  5268. this is most likely an error somewhere else }
  5269. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5270. internalerror(2022022001);
  5271. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5272. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5273. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5274. (
  5275. { do not mess with leas accessing the stack pointer
  5276. unless it's a null operation }
  5277. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5278. (
  5279. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5280. (taicpu(p).oper[0]^.ref^.offset = 0)
  5281. )
  5282. ) and
  5283. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5284. begin
  5285. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5286. begin
  5287. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5288. begin
  5289. taicpu(p).opcode := A_MOV;
  5290. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5291. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5292. end
  5293. else
  5294. begin
  5295. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5296. RemoveCurrentP(p);
  5297. end;
  5298. Result:=true;
  5299. exit;
  5300. end
  5301. else if (
  5302. { continue to use lea to adjust the stack pointer,
  5303. it is the recommended way, but only if not optimizing for size }
  5304. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5305. (cs_opt_size in current_settings.optimizerswitches)
  5306. ) and
  5307. { If the flags register is in use, don't change the instruction
  5308. to an ADD otherwise this will scramble the flags. [Kit] }
  5309. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5310. ConvertLEA(taicpu(p)) then
  5311. begin
  5312. Result:=true;
  5313. exit;
  5314. end;
  5315. end;
  5316. { Don't optimise if the stack or frame pointer is the destination register }
  5317. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5318. Exit;
  5319. if GetNextInstruction(p,hp1) and
  5320. (hp1.typ=ait_instruction) then
  5321. begin
  5322. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5323. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5324. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5325. begin
  5326. TransferUsedRegs(TmpUsedRegs);
  5327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5328. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5329. begin
  5330. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5331. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5332. RemoveInstruction(hp1);
  5333. result:=true;
  5334. exit;
  5335. end;
  5336. end;
  5337. { changes
  5338. lea <ref1>, reg1
  5339. <op> ...,<ref. with reg1>,...
  5340. to
  5341. <op> ...,<ref1>,... }
  5342. { find a reference which uses reg1 }
  5343. if (taicpu(hp1).ops>=1) and (taicpu(hp1).oper[0]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^) then
  5344. ref:=0
  5345. else if (taicpu(hp1).ops>=2) and (taicpu(hp1).oper[1]^.typ=top_ref) and RegInOp(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^) then
  5346. ref:=1
  5347. else
  5348. ref:=-1;
  5349. if (ref<>-1) and
  5350. { reg1 must be either the base or the index }
  5351. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5352. begin
  5353. { reg1 can be removed from the reference }
  5354. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5355. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5356. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5357. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5358. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5359. else
  5360. Internalerror(2019111201);
  5361. { check if the can insert all data of the lea into the second instruction }
  5362. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5363. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5364. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5365. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5366. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5367. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5368. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5369. {$ifdef x86_64}
  5370. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5371. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5372. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5373. )
  5374. {$endif x86_64}
  5375. then
  5376. begin
  5377. { reg1 might not used by the second instruction after it is remove from the reference }
  5378. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5379. begin
  5380. TransferUsedRegs(TmpUsedRegs);
  5381. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5382. { reg1 is not updated so it might not be used afterwards }
  5383. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5384. begin
  5385. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5386. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5387. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5388. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5389. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5390. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5391. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5392. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5393. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5394. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5395. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5396. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5397. RemoveCurrentP(p, hp1);
  5398. result:=true;
  5399. exit;
  5400. end
  5401. end;
  5402. end;
  5403. { recover }
  5404. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5405. end;
  5406. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5407. if Adjacent or
  5408. { Check further ahead (up to 2 instructions ahead for -O2) }
  5409. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5410. begin
  5411. { Check common LEA/LEA conditions }
  5412. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5413. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5414. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5415. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5416. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5417. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5418. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5419. (
  5420. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5421. calling it (since it calls GetNextInstruction) }
  5422. Adjacent or
  5423. (
  5424. (
  5425. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5426. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5427. ) and (
  5428. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5429. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5430. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5431. )
  5432. )
  5433. ) then
  5434. begin
  5435. TransferUsedRegs(TmpUsedRegs);
  5436. hp2 := p;
  5437. repeat
  5438. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5439. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5440. IntermediateRegDiscarded :=
  5441. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5442. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5443. { changes
  5444. lea offset1(regX,scale), reg1
  5445. lea offset2(reg1,reg1), reg2
  5446. to
  5447. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5448. and
  5449. lea offset1(regX,scale1), reg1
  5450. lea offset2(reg1,scale2), reg2
  5451. to
  5452. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5453. and
  5454. lea offset1(regX,scale1), reg1
  5455. lea offset2(reg3,reg1,scale2), reg2
  5456. to
  5457. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5458. ... so long as the final scale does not exceed 8
  5459. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5460. }
  5461. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5462. (
  5463. { Don't optimise if size is a concern and the intermediate register remains in use }
  5464. IntermediateRegDiscarded or
  5465. not (cs_opt_size in current_settings.optimizerswitches)
  5466. ) and
  5467. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5468. (
  5469. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5470. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5471. ) and (
  5472. (
  5473. { lea (reg1,scale2), reg2 variant }
  5474. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5475. (
  5476. Adjacent or
  5477. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5478. ) and
  5479. (
  5480. (
  5481. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5482. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5483. ) or (
  5484. { lea (regX,regX), reg1 variant }
  5485. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5486. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5487. )
  5488. )
  5489. ) or (
  5490. { lea (reg1,reg1), reg1 variant }
  5491. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5492. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5493. )
  5494. ) then
  5495. begin
  5496. { Make everything homogeneous to make calculations easier }
  5497. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5498. begin
  5499. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5500. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5501. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5502. else
  5503. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5504. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5505. end;
  5506. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5507. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5508. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5509. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5510. begin
  5511. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5512. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5513. begin
  5514. { Put the register to change in the index register }
  5515. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5516. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5517. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5518. end;
  5519. { Change lea (reg,reg) to lea(,reg,2) }
  5520. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5521. begin
  5522. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5523. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5524. end;
  5525. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5526. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5527. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5528. { Just to prevent miscalculations }
  5529. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5530. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5531. else
  5532. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5533. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5534. if IntermediateRegDiscarded then
  5535. begin
  5536. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5537. RemoveCurrentP(p);
  5538. end
  5539. else
  5540. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5541. result:=true;
  5542. exit;
  5543. end;
  5544. end;
  5545. { changes
  5546. lea offset1(regX), reg1
  5547. lea offset2(reg1), reg2
  5548. to
  5549. lea offset1+offset2(regX), reg2 }
  5550. if (
  5551. { Don't optimise if size is a concern and the intermediate register remains in use }
  5552. IntermediateRegDiscarded or
  5553. not (cs_opt_size in current_settings.optimizerswitches)
  5554. ) and
  5555. (
  5556. (
  5557. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5558. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  5559. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5560. ) or (
  5561. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5562. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5563. (
  5564. (
  5565. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5566. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5567. ) or (
  5568. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5569. (
  5570. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5571. (
  5572. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5573. (
  5574. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5575. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5576. )
  5577. )
  5578. )
  5579. )
  5580. )
  5581. )
  5582. ) then
  5583. begin
  5584. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5585. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5586. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5587. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5588. begin
  5589. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5590. begin
  5591. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5592. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5593. { if the register is used as index and base, we have to increase for base as well
  5594. and adapt base }
  5595. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5596. begin
  5597. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5598. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5599. end;
  5600. end
  5601. else
  5602. begin
  5603. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5604. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5605. end;
  5606. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5607. begin
  5608. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5609. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5610. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5611. end;
  5612. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5613. if IntermediateRegDiscarded then
  5614. begin
  5615. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5616. RemoveCurrentP(p);
  5617. end
  5618. else
  5619. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  5620. result:=true;
  5621. exit;
  5622. end;
  5623. end;
  5624. end;
  5625. { Change:
  5626. leal/q $x(%reg1),%reg2
  5627. ...
  5628. shll/q $y,%reg2
  5629. To:
  5630. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5631. }
  5632. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5633. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5634. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5635. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5636. (taicpu(hp1).oper[0]^.val <= 3) then
  5637. begin
  5638. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5639. TransferUsedRegs(TmpUsedRegs);
  5640. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5641. if
  5642. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5643. (this works even if scalefactor is zero) }
  5644. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5645. { Ensure offset doesn't go out of bounds }
  5646. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5647. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5648. (
  5649. (
  5650. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5651. (
  5652. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5653. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5654. (
  5655. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5656. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5657. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5658. )
  5659. )
  5660. ) or (
  5661. (
  5662. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5663. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5664. ) and
  5665. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5666. )
  5667. ) then
  5668. begin
  5669. repeat
  5670. with taicpu(p).oper[0]^.ref^ do
  5671. begin
  5672. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5673. if index = base then
  5674. begin
  5675. if Multiple > 4 then
  5676. { Optimisation will no longer work because resultant
  5677. scale factor will exceed 8 }
  5678. Break;
  5679. base := NR_NO;
  5680. scalefactor := 2;
  5681. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5682. end
  5683. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5684. begin
  5685. { Scale factor only works on the index register }
  5686. index := base;
  5687. base := NR_NO;
  5688. end;
  5689. { For safety }
  5690. if scalefactor <= 1 then
  5691. begin
  5692. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5693. scalefactor := Multiple;
  5694. end
  5695. else
  5696. begin
  5697. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5698. scalefactor := scalefactor * Multiple;
  5699. end;
  5700. offset := offset * Multiple;
  5701. end;
  5702. RemoveInstruction(hp1);
  5703. Result := True;
  5704. Exit;
  5705. { This repeat..until loop exists for the benefit of Break }
  5706. until True;
  5707. end;
  5708. end;
  5709. end;
  5710. end;
  5711. end;
  5712. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5713. var
  5714. hp1 : tai;
  5715. SubInstr: Boolean;
  5716. ThisConst: TCGInt;
  5717. const
  5718. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5719. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5720. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5721. begin
  5722. Result := False;
  5723. if taicpu(p).oper[0]^.typ <> top_const then
  5724. { Should have been confirmed before calling }
  5725. InternalError(2021102601);
  5726. SubInstr := (taicpu(p).opcode = A_SUB);
  5727. if GetLastInstruction(p, hp1) and
  5728. (hp1.typ = ait_instruction) and
  5729. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5730. begin
  5731. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5732. { Bad size }
  5733. InternalError(2022042001);
  5734. case taicpu(hp1).opcode Of
  5735. A_INC:
  5736. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5737. begin
  5738. if SubInstr then
  5739. ThisConst := taicpu(p).oper[0]^.val - 1
  5740. else
  5741. ThisConst := taicpu(p).oper[0]^.val + 1;
  5742. end
  5743. else
  5744. Exit;
  5745. A_DEC:
  5746. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5747. begin
  5748. if SubInstr then
  5749. ThisConst := taicpu(p).oper[0]^.val + 1
  5750. else
  5751. ThisConst := taicpu(p).oper[0]^.val - 1;
  5752. end
  5753. else
  5754. Exit;
  5755. A_SUB:
  5756. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5757. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5758. begin
  5759. if SubInstr then
  5760. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5761. else
  5762. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5763. end
  5764. else
  5765. Exit;
  5766. A_ADD:
  5767. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5768. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5769. begin
  5770. if SubInstr then
  5771. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5772. else
  5773. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5774. end
  5775. else
  5776. Exit;
  5777. else
  5778. Exit;
  5779. end;
  5780. { Check that the values are in range }
  5781. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5782. { Overflow; abort }
  5783. Exit;
  5784. if (ThisConst = 0) then
  5785. begin
  5786. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5787. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5788. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5789. RemoveInstruction(hp1);
  5790. hp1 := tai(p.next);
  5791. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5792. if not GetLastInstruction(hp1, p) then
  5793. p := hp1;
  5794. end
  5795. else
  5796. begin
  5797. if taicpu(hp1).opercnt=1 then
  5798. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5799. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5800. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5801. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5802. else
  5803. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5804. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5805. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5806. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5807. RemoveInstruction(hp1);
  5808. taicpu(p).loadconst(0, ThisConst);
  5809. end;
  5810. Result := True;
  5811. end;
  5812. end;
  5813. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  5814. begin
  5815. Result := False;
  5816. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5817. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5818. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5819. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5820. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5821. (
  5822. (
  5823. (taicpu(hp1).opcode = A_TEST)
  5824. ) or (
  5825. (taicpu(hp1).opcode = A_CMP) and
  5826. { A sanity check more than anything }
  5827. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5828. )
  5829. ) then
  5830. begin
  5831. { change
  5832. mov mem, %reg
  5833. ...
  5834. cmp/test x, %reg / test %reg,%reg
  5835. (reg deallocated)
  5836. to
  5837. cmp/test x, mem / cmp 0, mem
  5838. }
  5839. TransferUsedRegs(TmpUsedRegs);
  5840. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5841. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5842. begin
  5843. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5844. if (taicpu(hp1).opcode = A_TEST) and
  5845. (
  5846. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5847. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5848. ) then
  5849. begin
  5850. taicpu(hp1).opcode := A_CMP;
  5851. taicpu(hp1).loadconst(0, 0);
  5852. end;
  5853. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5854. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5855. RemoveCurrentP(p);
  5856. if (p <> hp1) then
  5857. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  5858. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  5859. { Make sure the flags are allocated across the CMP instruction }
  5860. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5861. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  5862. Result := True;
  5863. Exit;
  5864. end;
  5865. end;
  5866. end;
  5867. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5868. var
  5869. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5870. ThisReg, SecondReg: TRegister;
  5871. JumpLoc: TAsmLabel;
  5872. NewSize: TOpSize;
  5873. begin
  5874. Result := False;
  5875. {
  5876. Convert:
  5877. j<c> .L1
  5878. .L2:
  5879. mov 1,reg
  5880. jmp .L3 (or ret, although it might not be a RET yet)
  5881. .L1:
  5882. mov 0,reg
  5883. jmp .L3 (or ret)
  5884. ( As long as .L3 <> .L1 or .L2)
  5885. To:
  5886. mov 0,reg
  5887. set<not(c)> reg
  5888. jmp .L3 (or ret)
  5889. .L2:
  5890. mov 1,reg
  5891. jmp .L3 (or ret)
  5892. .L1:
  5893. mov 0,reg
  5894. jmp .L3 (or ret)
  5895. }
  5896. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5897. Exit;
  5898. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5899. if GetNextInstruction(hp_label, hp2) and
  5900. MatchInstruction(hp2,A_MOV,[]) and
  5901. (taicpu(hp2).oper[0]^.typ = top_const) and
  5902. (
  5903. (
  5904. (taicpu(hp2).oper[1]^.typ = top_reg)
  5905. {$ifdef i386}
  5906. { Under i386, ESI, EDI, EBP and ESP
  5907. don't have an 8-bit representation }
  5908. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5909. {$endif i386}
  5910. ) or (
  5911. {$ifdef i386}
  5912. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5913. {$endif i386}
  5914. (taicpu(hp2).opsize = S_B)
  5915. )
  5916. ) and
  5917. GetNextInstruction(hp2, hp3) and
  5918. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5919. (
  5920. (taicpu(hp3).opcode=A_RET) or
  5921. (
  5922. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5923. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5924. )
  5925. ) and
  5926. GetNextInstruction(hp3, hp4) and
  5927. SkipAligns(hp4, hp4) and
  5928. (hp4.typ=ait_label) and
  5929. (tai_label(hp4).labsym=JumpLoc) and
  5930. (
  5931. not (cs_opt_size in current_settings.optimizerswitches) or
  5932. { If the initial jump is the label's only reference, then it will
  5933. become a dead label if the other conditions are met and hence
  5934. remove at least 2 instructions, including a jump }
  5935. (JumpLoc.getrefs = 1)
  5936. ) and
  5937. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5938. that will be optimised out }
  5939. GetNextInstruction(hp4, hp5) and
  5940. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5941. (taicpu(hp5).oper[0]^.typ = top_const) and
  5942. (
  5943. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5944. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5945. ) and
  5946. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5947. GetNextInstruction(hp5,hp6) and
  5948. (
  5949. (hp6.typ<>ait_label) or
  5950. SkipLabels(hp6, hp6)
  5951. ) and
  5952. (hp6.typ=ait_instruction) then
  5953. begin
  5954. { First, let's look at the two jumps that are hp3 and hp6 }
  5955. if not
  5956. (
  5957. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5958. (
  5959. (taicpu(hp6).opcode=A_RET) or
  5960. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5961. )
  5962. ) then
  5963. { If condition is False, then the JMP/RET instructions matched conventionally }
  5964. begin
  5965. { See if one of the jumps can be instantly converted into a RET }
  5966. if (taicpu(hp3).opcode=A_JMP) then
  5967. begin
  5968. { Reuse hp5 }
  5969. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5970. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5971. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5972. Exit;
  5973. if MatchInstruction(hp5, A_RET, []) then
  5974. begin
  5975. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5976. ConvertJumpToRET(hp3, hp5);
  5977. Result := True;
  5978. end
  5979. else
  5980. Exit;
  5981. end;
  5982. if (taicpu(hp6).opcode=A_JMP) then
  5983. begin
  5984. { Reuse hp5 }
  5985. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5986. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5987. Exit;
  5988. if MatchInstruction(hp5, A_RET, []) then
  5989. begin
  5990. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5991. ConvertJumpToRET(hp6, hp5);
  5992. Result := True;
  5993. end
  5994. else
  5995. Exit;
  5996. end;
  5997. if not
  5998. (
  5999. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6000. (
  6001. (taicpu(hp6).opcode=A_RET) or
  6002. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6003. )
  6004. ) then
  6005. { Still doesn't match }
  6006. Exit;
  6007. end;
  6008. if (taicpu(hp2).oper[0]^.val = 1) then
  6009. begin
  6010. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6011. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6012. end
  6013. else
  6014. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6015. if taicpu(hp2).opsize=S_B then
  6016. begin
  6017. if taicpu(hp2).oper[1]^.typ = top_reg then
  6018. begin
  6019. SecondReg := taicpu(hp2).oper[1]^.reg;
  6020. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6021. end
  6022. else
  6023. begin
  6024. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6025. SecondReg := NR_NO;
  6026. end;
  6027. hp_pos := p;
  6028. hp_allocstart := hp4;
  6029. end
  6030. else
  6031. begin
  6032. { Will be a register because the size can't be S_B otherwise }
  6033. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6034. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6035. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6036. if (cs_opt_size in current_settings.optimizerswitches) then
  6037. begin
  6038. { Favour using MOVZX when optimising for size }
  6039. case taicpu(hp2).opsize of
  6040. S_W:
  6041. NewSize := S_BW;
  6042. S_L:
  6043. NewSize := S_BL;
  6044. {$ifdef x86_64}
  6045. S_Q:
  6046. begin
  6047. NewSize := S_BL;
  6048. { Will implicitly zero-extend to 64-bit }
  6049. setsubreg(SecondReg, R_SUBD);
  6050. end;
  6051. {$endif x86_64}
  6052. else
  6053. InternalError(2022101301);
  6054. end;
  6055. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6056. { Inserting it right before p will guarantee that the flags are also tracked }
  6057. Asml.InsertBefore(hp5, p);
  6058. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6059. hp_pos := hp5;
  6060. hp_allocstart := hp4;
  6061. end
  6062. else
  6063. begin
  6064. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6065. { Inserting it right before p will guarantee that the flags are also tracked }
  6066. Asml.InsertBefore(hp5, p);
  6067. hp_pos := p;
  6068. hp_allocstart := hp5;
  6069. end;
  6070. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6071. end;
  6072. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6073. taicpu(hp4).condition := taicpu(p).condition;
  6074. asml.InsertBefore(hp4, hp_pos);
  6075. if taicpu(hp3).is_jmp then
  6076. begin
  6077. JumpLoc.decrefs;
  6078. MakeUnconditional(taicpu(p));
  6079. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6080. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  6081. end
  6082. else
  6083. ConvertJumpToRET(p, hp3);
  6084. if SecondReg <> NR_NO then
  6085. { Ensure the destination register is allocated over this region }
  6086. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6087. if (JumpLoc.getrefs = 0) then
  6088. RemoveDeadCodeAfterJump(hp3);
  6089. Result:=true;
  6090. exit;
  6091. end;
  6092. end;
  6093. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6094. var
  6095. hp1, hp2: tai;
  6096. ActiveReg: TRegister;
  6097. OldOffset: asizeint;
  6098. ThisConst: TCGInt;
  6099. function RegDeallocated: Boolean;
  6100. begin
  6101. TransferUsedRegs(TmpUsedRegs);
  6102. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6103. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6104. end;
  6105. begin
  6106. Result:=false;
  6107. hp1 := nil;
  6108. { replace
  6109. subX const,%reg1
  6110. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6111. dealloc %reg1
  6112. by
  6113. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6114. }
  6115. if MatchOpType(taicpu(p),top_const,top_reg) then
  6116. begin
  6117. ActiveReg := taicpu(p).oper[1]^.reg;
  6118. { Ensures the entire register was updated }
  6119. if (taicpu(p).opsize >= S_L) and
  6120. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6121. MatchInstruction(hp1,A_LEA,[]) and
  6122. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6123. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6124. (
  6125. { Cover the case where the register in the reference is also the destination register }
  6126. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6127. (
  6128. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6129. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6130. RegDeallocated
  6131. )
  6132. ) then
  6133. begin
  6134. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6135. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  6136. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6137. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  6138. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6139. {$ifdef x86_64}
  6140. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6141. begin
  6142. { Overflow; abort }
  6143. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6144. end
  6145. else
  6146. {$endif x86_64}
  6147. begin
  6148. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6149. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6150. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6151. RemoveCurrentP(p, hp1)
  6152. else
  6153. RemoveCurrentP(p);
  6154. result:=true;
  6155. Exit;
  6156. end;
  6157. end;
  6158. if (
  6159. { Save calling GetNextInstructionUsingReg again }
  6160. Assigned(hp1) or
  6161. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6162. ) and
  6163. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6164. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6165. begin
  6166. if taicpu(hp1).oper[0]^.typ = top_const then
  6167. begin
  6168. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6169. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6170. Result := True;
  6171. { Handle any overflows }
  6172. case taicpu(p).opsize of
  6173. S_B:
  6174. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6175. S_W:
  6176. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6177. S_L:
  6178. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6179. {$ifdef x86_64}
  6180. S_Q:
  6181. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6182. { Overflow; abort }
  6183. Result := False
  6184. else
  6185. taicpu(p).oper[0]^.val := ThisConst;
  6186. {$endif x86_64}
  6187. else
  6188. InternalError(2021102611);
  6189. end;
  6190. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6191. if Result then
  6192. begin
  6193. if (taicpu(p).oper[0]^.val < 0) and
  6194. (
  6195. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6196. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6197. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6198. ) then
  6199. begin
  6200. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6201. taicpu(p).opcode := A_SUB;
  6202. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6203. end
  6204. else
  6205. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6206. RemoveInstruction(hp1);
  6207. end;
  6208. end
  6209. else
  6210. begin
  6211. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6212. TransferUsedRegs(TmpUsedRegs);
  6213. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6214. hp2 := p;
  6215. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6216. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6217. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6218. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6219. begin
  6220. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6221. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6222. Asml.Remove(p);
  6223. Asml.InsertAfter(p, hp1);
  6224. p := hp1;
  6225. Result := True;
  6226. Exit;
  6227. end;
  6228. end;
  6229. end;
  6230. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6231. { * change "sub/add const1, reg" or "dec reg" followed by
  6232. "sub const2, reg" to one "sub ..., reg" }
  6233. {$ifdef i386}
  6234. if (taicpu(p).oper[0]^.val = 2) and
  6235. (ActiveReg = NR_ESP) and
  6236. { Don't do the sub/push optimization if the sub }
  6237. { comes from setting up the stack frame (JM) }
  6238. (not(GetLastInstruction(p,hp1)) or
  6239. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6240. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6241. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6242. begin
  6243. hp1 := tai(p.next);
  6244. while Assigned(hp1) and
  6245. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6246. not RegReadByInstruction(NR_ESP,hp1) and
  6247. not RegModifiedByInstruction(NR_ESP,hp1) do
  6248. hp1 := tai(hp1.next);
  6249. if Assigned(hp1) and
  6250. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6251. begin
  6252. taicpu(hp1).changeopsize(S_L);
  6253. if taicpu(hp1).oper[0]^.typ=top_reg then
  6254. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6255. hp1 := tai(p.next);
  6256. RemoveCurrentp(p, hp1);
  6257. Result:=true;
  6258. exit;
  6259. end;
  6260. end;
  6261. {$endif i386}
  6262. if DoArithCombineOpt(p) then
  6263. Result:=true;
  6264. end;
  6265. end;
  6266. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6267. var
  6268. TmpBool1,TmpBool2 : Boolean;
  6269. tmpref : treference;
  6270. hp1,hp2: tai;
  6271. mask, shiftval: tcgint;
  6272. begin
  6273. Result:=false;
  6274. { All these optimisations work on "shl/sal const,%reg" }
  6275. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6276. Exit;
  6277. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6278. (taicpu(p).oper[0]^.val <= 3) then
  6279. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6280. begin
  6281. { should we check the next instruction? }
  6282. TmpBool1 := True;
  6283. { have we found an add/sub which could be
  6284. integrated in the lea? }
  6285. TmpBool2 := False;
  6286. reference_reset(tmpref,2,[]);
  6287. TmpRef.index := taicpu(p).oper[1]^.reg;
  6288. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6289. while TmpBool1 and
  6290. GetNextInstruction(p, hp1) and
  6291. (tai(hp1).typ = ait_instruction) and
  6292. ((((taicpu(hp1).opcode = A_ADD) or
  6293. (taicpu(hp1).opcode = A_SUB)) and
  6294. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6295. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6296. (((taicpu(hp1).opcode = A_INC) or
  6297. (taicpu(hp1).opcode = A_DEC)) and
  6298. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6299. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6300. ((taicpu(hp1).opcode = A_LEA) and
  6301. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6302. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6303. (not GetNextInstruction(hp1,hp2) or
  6304. not instrReadsFlags(hp2)) Do
  6305. begin
  6306. TmpBool1 := False;
  6307. if taicpu(hp1).opcode=A_LEA then
  6308. begin
  6309. if (TmpRef.base = NR_NO) and
  6310. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6311. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6312. { Segment register isn't a concern here }
  6313. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6314. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6315. begin
  6316. TmpBool1 := True;
  6317. TmpBool2 := True;
  6318. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6319. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6320. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6321. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6322. RemoveInstruction(hp1);
  6323. end
  6324. end
  6325. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6326. begin
  6327. TmpBool1 := True;
  6328. TmpBool2 := True;
  6329. case taicpu(hp1).opcode of
  6330. A_ADD:
  6331. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6332. A_SUB:
  6333. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6334. else
  6335. internalerror(2019050536);
  6336. end;
  6337. RemoveInstruction(hp1);
  6338. end
  6339. else
  6340. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6341. (((taicpu(hp1).opcode = A_ADD) and
  6342. (TmpRef.base = NR_NO)) or
  6343. (taicpu(hp1).opcode = A_INC) or
  6344. (taicpu(hp1).opcode = A_DEC)) then
  6345. begin
  6346. TmpBool1 := True;
  6347. TmpBool2 := True;
  6348. case taicpu(hp1).opcode of
  6349. A_ADD:
  6350. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6351. A_INC:
  6352. inc(TmpRef.offset);
  6353. A_DEC:
  6354. dec(TmpRef.offset);
  6355. else
  6356. internalerror(2019050535);
  6357. end;
  6358. RemoveInstruction(hp1);
  6359. end;
  6360. end;
  6361. if TmpBool2
  6362. {$ifndef x86_64}
  6363. or
  6364. ((current_settings.optimizecputype < cpu_Pentium2) and
  6365. (taicpu(p).oper[0]^.val <= 3) and
  6366. not(cs_opt_size in current_settings.optimizerswitches))
  6367. {$endif x86_64}
  6368. then
  6369. begin
  6370. if not(TmpBool2) and
  6371. (taicpu(p).oper[0]^.val=1) then
  6372. begin
  6373. taicpu(p).opcode := A_ADD;
  6374. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6375. end
  6376. else
  6377. begin
  6378. taicpu(p).opcode := A_LEA;
  6379. taicpu(p).loadref(0, TmpRef);
  6380. end;
  6381. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6382. Result := True;
  6383. end;
  6384. end
  6385. {$ifndef x86_64}
  6386. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6387. begin
  6388. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6389. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6390. (unlike shl, which is only Tairable in the U pipe) }
  6391. if taicpu(p).oper[0]^.val=1 then
  6392. begin
  6393. taicpu(p).opcode := A_ADD;
  6394. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6395. Result := True;
  6396. end
  6397. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6398. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6399. else if (taicpu(p).opsize = S_L) and
  6400. (taicpu(p).oper[0]^.val<= 3) then
  6401. begin
  6402. reference_reset(tmpref,2,[]);
  6403. TmpRef.index := taicpu(p).oper[1]^.reg;
  6404. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6405. taicpu(p).opcode := A_LEA;
  6406. taicpu(p).loadref(0, TmpRef);
  6407. Result := True;
  6408. end;
  6409. end
  6410. {$endif x86_64}
  6411. else if
  6412. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6413. (
  6414. (
  6415. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6416. SetAndTest(hp1, hp2)
  6417. {$ifdef x86_64}
  6418. ) or
  6419. (
  6420. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6421. GetNextInstruction(hp1, hp2) and
  6422. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6423. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6424. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6425. {$endif x86_64}
  6426. )
  6427. ) and
  6428. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6429. begin
  6430. { Change:
  6431. shl x, %reg1
  6432. mov -(1<<x), %reg2
  6433. and %reg2, %reg1
  6434. Or:
  6435. shl x, %reg1
  6436. and -(1<<x), %reg1
  6437. To just:
  6438. shl x, %reg1
  6439. Since the and operation only zeroes bits that are already zero from the shl operation
  6440. }
  6441. case taicpu(p).oper[0]^.val of
  6442. 8:
  6443. mask:=$FFFFFFFFFFFFFF00;
  6444. 16:
  6445. mask:=$FFFFFFFFFFFF0000;
  6446. 32:
  6447. mask:=$FFFFFFFF00000000;
  6448. 63:
  6449. { Constant pre-calculated to prevent overflow errors with Int64 }
  6450. mask:=$8000000000000000;
  6451. else
  6452. begin
  6453. if taicpu(p).oper[0]^.val >= 64 then
  6454. { Shouldn't happen realistically, since the register
  6455. is guaranteed to be set to zero at this point }
  6456. mask := 0
  6457. else
  6458. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6459. end;
  6460. end;
  6461. if taicpu(hp1).oper[0]^.val = mask then
  6462. begin
  6463. { Everything checks out, perform the optimisation, as long as
  6464. the FLAGS register isn't being used}
  6465. TransferUsedRegs(TmpUsedRegs);
  6466. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6467. {$ifdef x86_64}
  6468. if (hp1 <> hp2) then
  6469. begin
  6470. { "shl/mov/and" version }
  6471. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6472. { Don't do the optimisation if the FLAGS register is in use }
  6473. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6474. begin
  6475. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6476. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6477. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6478. begin
  6479. RemoveInstruction(hp1);
  6480. Result := True;
  6481. end;
  6482. { Only set Result to True if the 'mov' instruction was removed }
  6483. RemoveInstruction(hp2);
  6484. end;
  6485. end
  6486. else
  6487. {$endif x86_64}
  6488. begin
  6489. { "shl/and" version }
  6490. { Don't do the optimisation if the FLAGS register is in use }
  6491. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6492. begin
  6493. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6494. RemoveInstruction(hp1);
  6495. Result := True;
  6496. end;
  6497. end;
  6498. Exit;
  6499. end
  6500. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6501. begin
  6502. { Even if the mask doesn't allow for its removal, we might be
  6503. able to optimise the mask for the "shl/and" version, which
  6504. may permit other peephole optimisations }
  6505. {$ifdef DEBUG_AOPTCPU}
  6506. mask := taicpu(hp1).oper[0]^.val and mask;
  6507. if taicpu(hp1).oper[0]^.val <> mask then
  6508. begin
  6509. DebugMsg(
  6510. SPeepholeOptimization +
  6511. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6512. ' to $' + debug_tostr(mask) +
  6513. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6514. taicpu(hp1).oper[0]^.val := mask;
  6515. end;
  6516. {$else DEBUG_AOPTCPU}
  6517. { If debugging is off, just set the operand even if it's the same }
  6518. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6519. {$endif DEBUG_AOPTCPU}
  6520. end;
  6521. end;
  6522. {
  6523. change
  6524. shl/sal const,reg
  6525. <op> ...(...,reg,1),...
  6526. into
  6527. <op> ...(...,reg,1 shl const),...
  6528. if const in 1..3
  6529. }
  6530. if MatchOpType(taicpu(p), top_const, top_reg) and
  6531. (taicpu(p).oper[0]^.val in [1..3]) and
  6532. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6533. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6534. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6535. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6536. MatchOpType(taicpu(hp1),top_ref))
  6537. ) and
  6538. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6539. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6540. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6541. begin
  6542. TransferUsedRegs(TmpUsedRegs);
  6543. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6544. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6545. begin
  6546. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6547. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6548. RemoveCurrentP(p);
  6549. Result:=true;
  6550. exit;
  6551. end;
  6552. end;
  6553. if MatchOpType(taicpu(p), top_const, top_reg) and
  6554. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6555. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6556. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6557. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6558. begin
  6559. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6560. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6561. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6562. {$ifdef x86_64}
  6563. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6564. {$endif x86_64}
  6565. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6566. begin
  6567. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6568. taicpu(hp1).opcode:=A_MOV;
  6569. taicpu(hp1).oper[0]^.val:=0;
  6570. end
  6571. else
  6572. begin
  6573. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6574. taicpu(hp1).oper[0]^.val:=shiftval;
  6575. end;
  6576. RemoveCurrentP(p);
  6577. Result:=true;
  6578. exit;
  6579. end;
  6580. end;
  6581. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6582. begin
  6583. case shr_size of
  6584. S_B:
  6585. { No valid combinations }
  6586. Result := False;
  6587. S_W:
  6588. Result := (Shift >= 8) and (movz_size = S_BW);
  6589. S_L:
  6590. Result :=
  6591. (Shift >= 24) { Any opsize is valid for this shift } or
  6592. ((Shift >= 16) and (movz_size = S_WL));
  6593. {$ifdef x86_64}
  6594. S_Q:
  6595. Result :=
  6596. (Shift >= 56) { Any opsize is valid for this shift } or
  6597. ((Shift >= 48) and (movz_size = S_WL));
  6598. {$endif x86_64}
  6599. else
  6600. InternalError(2022081510);
  6601. end;
  6602. end;
  6603. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6604. var
  6605. hp1, hp2: tai;
  6606. Shift: TCGInt;
  6607. LimitSize: Topsize;
  6608. DoNotMerge: Boolean;
  6609. begin
  6610. Result := False;
  6611. { All these optimisations work on "shr const,%reg" }
  6612. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6613. Exit;
  6614. DoNotMerge := False;
  6615. Shift := taicpu(p).oper[0]^.val;
  6616. LimitSize := taicpu(p).opsize;
  6617. hp1 := p;
  6618. repeat
  6619. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6620. Exit;
  6621. case taicpu(hp1).opcode of
  6622. A_TEST, A_CMP, A_Jcc:
  6623. { Skip over conditional jumps and relevant comparisons }
  6624. Continue;
  6625. A_MOVZX:
  6626. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6627. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6628. begin
  6629. { Since the original register is being read as is, subsequent
  6630. SHRs must not be merged at this point }
  6631. DoNotMerge := True;
  6632. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6633. begin
  6634. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6635. begin
  6636. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6637. taicpu(hp1).opcode := A_MOV;
  6638. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6639. case taicpu(hp1).opsize of
  6640. S_BW:
  6641. taicpu(hp1).opsize := S_W;
  6642. S_BL, S_WL:
  6643. taicpu(hp1).opsize := S_L;
  6644. else
  6645. InternalError(2022081503);
  6646. end;
  6647. { p itself hasn't changed, so no need to set Result to True }
  6648. Include(OptsToCheck, aoc_ForceNewIteration);
  6649. { See if there's anything afterwards that can be
  6650. optimised, since the input register hasn't changed }
  6651. Continue;
  6652. end;
  6653. { NOTE: If the MOVZX instruction reads and writes the same
  6654. register, defer this to the post-peephole optimisation stage }
  6655. Exit;
  6656. end;
  6657. end;
  6658. A_SHL, A_SAL, A_SHR:
  6659. if (taicpu(hp1).opsize <= LimitSize) and
  6660. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6661. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6662. begin
  6663. { Make sure the sizes don't exceed the register size limit
  6664. (measured by the shift value falling below the limit) }
  6665. if taicpu(hp1).opsize < LimitSize then
  6666. LimitSize := taicpu(hp1).opsize;
  6667. if taicpu(hp1).opcode = A_SHR then
  6668. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6669. else
  6670. begin
  6671. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6672. DoNotMerge := True;
  6673. end;
  6674. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6675. Exit;
  6676. { Since we've established that the combined shift is within
  6677. limits, we can actually combine the adjacent SHR
  6678. instructions even if they're different sizes }
  6679. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6680. begin
  6681. hp2 := tai(hp1.Previous);
  6682. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6683. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6684. RemoveInstruction(hp1);
  6685. hp1 := hp2;
  6686. { Though p has changed, only the constant has, and its
  6687. effects can still be detected on the next iteration of
  6688. the repeat..until loop }
  6689. Include(OptsToCheck, aoc_ForceNewIteration);
  6690. end;
  6691. { Move onto the next instruction }
  6692. Continue;
  6693. end;
  6694. else
  6695. ;
  6696. end;
  6697. Break;
  6698. until False;
  6699. end;
  6700. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6701. var
  6702. CurrentRef: TReference;
  6703. FullReg: TRegister;
  6704. hp1, hp2: tai;
  6705. begin
  6706. Result := False;
  6707. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6708. Exit;
  6709. { We assume you've checked if the operand is actually a reference by
  6710. this point. If it isn't, you'll most likely get an access violation }
  6711. CurrentRef := first_mov.oper[1]^.ref^;
  6712. { Memory must be aligned }
  6713. if (CurrentRef.offset mod 4) <> 0 then
  6714. Exit;
  6715. Inc(CurrentRef.offset);
  6716. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6717. if MatchOperand(second_mov.oper[0]^, 0) and
  6718. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6719. GetNextInstruction(second_mov, hp1) and
  6720. (hp1.typ = ait_instruction) and
  6721. (taicpu(hp1).opcode = A_MOV) and
  6722. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6723. (taicpu(hp1).oper[0]^.val = 0) then
  6724. begin
  6725. Inc(CurrentRef.offset);
  6726. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6727. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6728. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6729. begin
  6730. case taicpu(hp1).opsize of
  6731. S_B:
  6732. if GetNextInstruction(hp1, hp2) and
  6733. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6734. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6735. (taicpu(hp2).oper[0]^.val = 0) then
  6736. begin
  6737. Inc(CurrentRef.offset);
  6738. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6739. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6740. (taicpu(hp2).opsize = S_B) then
  6741. begin
  6742. RemoveInstruction(hp1);
  6743. RemoveInstruction(hp2);
  6744. first_mov.opsize := S_L;
  6745. if first_mov.oper[0]^.typ = top_reg then
  6746. begin
  6747. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6748. { Reuse second_mov as a MOVZX instruction }
  6749. second_mov.opcode := A_MOVZX;
  6750. second_mov.opsize := S_BL;
  6751. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6752. second_mov.loadreg(1, FullReg);
  6753. first_mov.oper[0]^.reg := FullReg;
  6754. asml.Remove(second_mov);
  6755. asml.InsertBefore(second_mov, first_mov);
  6756. end
  6757. else
  6758. { It's a value }
  6759. begin
  6760. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6761. RemoveInstruction(second_mov);
  6762. end;
  6763. Result := True;
  6764. Exit;
  6765. end;
  6766. end;
  6767. S_W:
  6768. begin
  6769. RemoveInstruction(hp1);
  6770. first_mov.opsize := S_L;
  6771. if first_mov.oper[0]^.typ = top_reg then
  6772. begin
  6773. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6774. { Reuse second_mov as a MOVZX instruction }
  6775. second_mov.opcode := A_MOVZX;
  6776. second_mov.opsize := S_BL;
  6777. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6778. second_mov.loadreg(1, FullReg);
  6779. first_mov.oper[0]^.reg := FullReg;
  6780. asml.Remove(second_mov);
  6781. asml.InsertBefore(second_mov, first_mov);
  6782. end
  6783. else
  6784. { It's a value }
  6785. begin
  6786. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6787. RemoveInstruction(second_mov);
  6788. end;
  6789. Result := True;
  6790. Exit;
  6791. end;
  6792. else
  6793. ;
  6794. end;
  6795. end;
  6796. end;
  6797. end;
  6798. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6799. { returns true if a "continue" should be done after this optimization }
  6800. var
  6801. hp1, hp2, hp3: tai;
  6802. begin
  6803. Result := false;
  6804. hp3 := nil;
  6805. if MatchOpType(taicpu(p),top_ref) and
  6806. GetNextInstruction(p, hp1) and
  6807. (hp1.typ = ait_instruction) and
  6808. (((taicpu(hp1).opcode = A_FLD) and
  6809. (taicpu(p).opcode = A_FSTP)) or
  6810. ((taicpu(p).opcode = A_FISTP) and
  6811. (taicpu(hp1).opcode = A_FILD))) and
  6812. MatchOpType(taicpu(hp1),top_ref) and
  6813. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6814. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6815. begin
  6816. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6817. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6818. GetNextInstruction(hp1, hp2) and
  6819. (((hp2.typ = ait_instruction) and
  6820. IsExitCode(hp2) and
  6821. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6822. not(assigned(current_procinfo.procdef.funcretsym) and
  6823. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6824. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6825. { fstp <temp>
  6826. fld <temp>
  6827. <dealloc> <temp>
  6828. }
  6829. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6830. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6831. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6832. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6833. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6834. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6835. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6836. )
  6837. )
  6838. ) then
  6839. begin
  6840. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6841. RemoveInstruction(hp1);
  6842. RemoveCurrentP(p, hp2);
  6843. { first case: exit code }
  6844. if hp2.typ = ait_instruction then
  6845. RemoveLastDeallocForFuncRes(p);
  6846. Result := true;
  6847. end
  6848. else
  6849. { we can do this only in fast math mode as fstp is rounding ...
  6850. ... still disabled as it breaks the compiler and/or rtl }
  6851. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6852. { ... or if another fstp equal to the first one follows }
  6853. GetNextInstruction(hp1,hp2) and
  6854. (hp2.typ = ait_instruction) and
  6855. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6856. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6857. begin
  6858. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6859. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6860. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6861. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6862. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6863. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6864. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6865. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6866. ) then
  6867. begin
  6868. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6869. RemoveCurrentP(p,hp2);
  6870. RemoveInstruction(hp1);
  6871. Result := true;
  6872. end
  6873. else if { fst can't store an extended/comp value }
  6874. (taicpu(p).opsize <> S_FX) and
  6875. (taicpu(p).opsize <> S_IQ) then
  6876. begin
  6877. if (taicpu(p).opcode = A_FSTP) then
  6878. taicpu(p).opcode := A_FST
  6879. else
  6880. taicpu(p).opcode := A_FIST;
  6881. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6882. RemoveInstruction(hp1);
  6883. Result := true;
  6884. end;
  6885. end;
  6886. end;
  6887. end;
  6888. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6889. var
  6890. hp1, hp2, hp3: tai;
  6891. begin
  6892. result:=false;
  6893. if MatchOpType(taicpu(p),top_reg) and
  6894. GetNextInstruction(p, hp1) and
  6895. (hp1.typ = Ait_Instruction) and
  6896. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6897. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6898. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6899. { change to
  6900. fld reg fxxx reg,st
  6901. fxxxp st, st1 (hp1)
  6902. Remark: non commutative operations must be reversed!
  6903. }
  6904. begin
  6905. case taicpu(hp1).opcode Of
  6906. A_FMULP,A_FADDP,
  6907. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6908. begin
  6909. case taicpu(hp1).opcode Of
  6910. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6911. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6912. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6913. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6914. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6915. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6916. else
  6917. internalerror(2019050534);
  6918. end;
  6919. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6920. taicpu(hp1).oper[1]^.reg := NR_ST;
  6921. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6922. RemoveCurrentP(p, hp1);
  6923. Result:=true;
  6924. exit;
  6925. end;
  6926. else
  6927. ;
  6928. end;
  6929. end
  6930. else
  6931. if MatchOpType(taicpu(p),top_ref) and
  6932. GetNextInstruction(p, hp2) and
  6933. (hp2.typ = Ait_Instruction) and
  6934. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6935. (taicpu(p).opsize in [S_FS, S_FL]) and
  6936. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6937. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6938. if GetLastInstruction(p, hp1) and
  6939. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6940. MatchOpType(taicpu(hp1),top_ref) and
  6941. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6942. if ((taicpu(hp2).opcode = A_FMULP) or
  6943. (taicpu(hp2).opcode = A_FADDP)) then
  6944. { change to
  6945. fld/fst mem1 (hp1) fld/fst mem1
  6946. fld mem1 (p) fadd/
  6947. faddp/ fmul st, st
  6948. fmulp st, st1 (hp2) }
  6949. begin
  6950. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6951. RemoveCurrentP(p, hp1);
  6952. if (taicpu(hp2).opcode = A_FADDP) then
  6953. taicpu(hp2).opcode := A_FADD
  6954. else
  6955. taicpu(hp2).opcode := A_FMUL;
  6956. taicpu(hp2).oper[1]^.reg := NR_ST;
  6957. end
  6958. else
  6959. { change to
  6960. fld/fst mem1 (hp1) fld/fst mem1
  6961. fld mem1 (p) fld st
  6962. }
  6963. begin
  6964. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6965. taicpu(p).changeopsize(S_FL);
  6966. taicpu(p).loadreg(0,NR_ST);
  6967. end
  6968. else
  6969. begin
  6970. case taicpu(hp2).opcode Of
  6971. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6972. { change to
  6973. fld/fst mem1 (hp1) fld/fst mem1
  6974. fld mem2 (p) fxxx mem2
  6975. fxxxp st, st1 (hp2) }
  6976. begin
  6977. case taicpu(hp2).opcode Of
  6978. A_FADDP: taicpu(p).opcode := A_FADD;
  6979. A_FMULP: taicpu(p).opcode := A_FMUL;
  6980. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6981. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6982. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6983. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6984. else
  6985. internalerror(2019050533);
  6986. end;
  6987. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6988. RemoveInstruction(hp2);
  6989. end
  6990. else
  6991. ;
  6992. end
  6993. end
  6994. end;
  6995. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6996. begin
  6997. Result := condition_in(cond1, cond2) or
  6998. { Not strictly subsets due to the actual flags checked, but because we're
  6999. comparing integers, E is a subset of AE and GE and their aliases }
  7000. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7001. end;
  7002. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7003. var
  7004. v: TCGInt;
  7005. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7006. FirstMatch, TempBool: Boolean;
  7007. NewReg: TRegister;
  7008. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7009. begin
  7010. Result:=false;
  7011. { All these optimisations need a next instruction }
  7012. if not GetNextInstruction(p, hp1) then
  7013. Exit;
  7014. { Search for:
  7015. cmp ###,###
  7016. j(c1) @lbl1
  7017. ...
  7018. @lbl:
  7019. cmp ###,### (same comparison as above)
  7020. j(c2) @lbl2
  7021. If c1 is a subset of c2, change to:
  7022. cmp ###,###
  7023. j(c1) @lbl2
  7024. (@lbl1 may become a dead label as a result)
  7025. }
  7026. { Also handle cases where there are multiple jumps in a row }
  7027. p_jump := hp1;
  7028. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7029. begin
  7030. if IsJumpToLabel(taicpu(p_jump)) then
  7031. begin
  7032. { Do jump optimisations first in case the condition becomes
  7033. unnecessary }
  7034. TempBool := True;
  7035. if DoJumpOptimizations(p_jump, TempBool) or
  7036. not TempBool then
  7037. begin
  7038. if Assigned(p_jump) then
  7039. begin
  7040. hp1 := p_jump;
  7041. if (p_jump.typ in [ait_align]) then
  7042. SkipAligns(p_jump, p_jump);
  7043. { CollapseZeroDistJump will be set to the label after the
  7044. jump if it optimises, whether or not it's live or dead }
  7045. if (p_jump.typ in [ait_label]) and
  7046. not (tai_label(p_jump).labsym.is_used) then
  7047. GetNextInstruction(p_jump, p_jump);
  7048. end;
  7049. TransferUsedRegs(TmpUsedRegs);
  7050. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7051. if not Assigned(p_jump) or
  7052. (
  7053. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7054. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7055. ) then
  7056. begin
  7057. { No more conditional jumps; conditional statement is no longer required }
  7058. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7059. RemoveCurrentP(p);
  7060. Result := True;
  7061. Exit;
  7062. end;
  7063. hp1 := p_jump;
  7064. Include(OptsToCheck, aoc_ForceNewIteration);
  7065. Continue;
  7066. end;
  7067. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7068. if GetNextInstruction(p_jump, hp2) and
  7069. (
  7070. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7071. not TempBool
  7072. ) then
  7073. begin
  7074. hp1 := p_jump;
  7075. Include(OptsToCheck, aoc_ForceNewIteration);
  7076. Continue;
  7077. end;
  7078. p_label := nil;
  7079. if Assigned(JumpLabel) then
  7080. p_label := getlabelwithsym(JumpLabel);
  7081. if Assigned(p_label) and
  7082. GetNextInstruction(p_label, p_dist) and
  7083. MatchInstruction(p_dist, A_CMP, []) and
  7084. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7085. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7086. GetNextInstruction(p_dist, hp1_dist) and
  7087. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7088. begin
  7089. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7090. if JumpLabel = JumpLabel_dist then
  7091. { This is an infinite loop }
  7092. Exit;
  7093. { Best optimisation when the first condition is a subset (or equal) of the second }
  7094. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7095. begin
  7096. { Any registers used here will already be allocated }
  7097. if Assigned(JumpLabel) then
  7098. JumpLabel.DecRefs;
  7099. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7100. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7101. Result := True;
  7102. { Don't exit yet. Since p and p_jump haven't actually been
  7103. removed, we can check for more on this iteration }
  7104. end
  7105. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7106. GetNextInstruction(hp1_dist, hp1_label) and
  7107. SkipAligns(hp1_label, hp1_label) and
  7108. (hp1_label.typ = ait_label) then
  7109. begin
  7110. JumpLabel_far := tai_label(hp1_label).labsym;
  7111. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7112. { This is an infinite loop }
  7113. Exit;
  7114. if Assigned(JumpLabel_far) then
  7115. begin
  7116. { In this situation, if the first jump branches, the second one will never,
  7117. branch so change the destination label to after the second jump }
  7118. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7119. if Assigned(JumpLabel) then
  7120. JumpLabel.DecRefs;
  7121. JumpLabel_far.IncRefs;
  7122. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7123. Result := True;
  7124. { Don't exit yet. Since p and p_jump haven't actually been
  7125. removed, we can check for more on this iteration }
  7126. Continue;
  7127. end;
  7128. end;
  7129. end;
  7130. end;
  7131. { Search for:
  7132. cmp ###,###
  7133. j(c1) @lbl1
  7134. cmp ###,### (same as first)
  7135. Remove second cmp
  7136. }
  7137. if GetNextInstruction(p_jump, hp2) and
  7138. (
  7139. (
  7140. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7141. (
  7142. (
  7143. MatchOpType(taicpu(p), top_const, top_reg) and
  7144. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7145. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7146. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7147. ) or (
  7148. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7149. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7150. )
  7151. )
  7152. ) or (
  7153. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7154. MatchOperand(taicpu(p).oper[0]^, 0) and
  7155. (taicpu(p).oper[1]^.typ = top_reg) and
  7156. MatchInstruction(hp2, A_TEST, []) and
  7157. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7158. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7159. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7160. )
  7161. ) then
  7162. begin
  7163. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7164. RemoveInstruction(hp2);
  7165. Result := True;
  7166. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7167. end;
  7168. GetNextInstruction(p_jump, p_jump);
  7169. end;
  7170. if (
  7171. { Don't call GetNextInstruction again if we already have it }
  7172. (hp1 = p_jump) or
  7173. GetNextInstruction(p, hp1)
  7174. ) and
  7175. MatchInstruction(hp1, A_Jcc, []) and
  7176. IsJumpToLabel(taicpu(hp1)) and
  7177. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7178. GetNextInstruction(hp1, hp2) then
  7179. begin
  7180. {
  7181. cmp x, y (or "cmp y, x")
  7182. je @lbl
  7183. mov x, y
  7184. @lbl:
  7185. (x and y can be constants, registers or references)
  7186. Change to:
  7187. mov x, y (x and y will always be equal in the end)
  7188. @lbl: (may beceome a dead label)
  7189. Also:
  7190. cmp x, y (or "cmp y, x")
  7191. jne @lbl
  7192. mov x, y
  7193. @lbl:
  7194. (x and y can be constants, registers or references)
  7195. Change to:
  7196. Absolutely nothing! (Except @lbl if it's still live)
  7197. }
  7198. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7199. (
  7200. (
  7201. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7202. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7203. ) or (
  7204. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7205. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7206. )
  7207. ) and
  7208. GetNextInstruction(hp2, hp1_label) and
  7209. SkipAligns(hp1_label, hp1_label) and
  7210. (hp1_label.typ = ait_label) and
  7211. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7212. begin
  7213. tai_label(hp1_label).labsym.DecRefs;
  7214. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7215. begin
  7216. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7217. RemoveInstruction(hp2);
  7218. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7219. end
  7220. else
  7221. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7222. RemoveInstruction(hp1);
  7223. RemoveCurrentp(p, hp2);
  7224. Result := True;
  7225. Exit;
  7226. end;
  7227. {
  7228. Try to optimise the following:
  7229. cmp $x,### ($x and $y can be registers or constants)
  7230. je @lbl1 (only reference)
  7231. cmp $y,### (### are identical)
  7232. @Lbl:
  7233. sete %reg1
  7234. Change to:
  7235. cmp $x,###
  7236. sete %reg2 (allocate new %reg2)
  7237. cmp $y,###
  7238. sete %reg1
  7239. orb %reg2,%reg1
  7240. (dealloc %reg2)
  7241. This adds an instruction (so don't perform under -Os), but it removes
  7242. a conditional branch.
  7243. }
  7244. if not (cs_opt_size in current_settings.optimizerswitches) and
  7245. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7246. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7247. { The first operand of CMP instructions can only be a register or
  7248. immediate anyway, so no need to check }
  7249. GetNextInstruction(hp2, p_label) and
  7250. (p_label.typ = ait_label) and
  7251. (tai_label(p_label).labsym.getrefs = 1) and
  7252. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7253. GetNextInstruction(p_label, p_dist) and
  7254. MatchInstruction(p_dist, A_SETcc, []) and
  7255. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7256. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7257. begin
  7258. TransferUsedRegs(TmpUsedRegs);
  7259. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7260. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7261. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7262. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7263. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7264. { Get the instruction after the SETcc instruction so we can
  7265. allocate a new register over the entire range }
  7266. GetNextInstruction(p_dist, hp1_dist) then
  7267. begin
  7268. { Register can appear in p if it's not used afterwards, so only
  7269. allocate between hp1 and hp1_dist }
  7270. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7271. if NewReg <> NR_NO then
  7272. begin
  7273. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7274. { Change the jump instruction into a SETcc instruction }
  7275. taicpu(hp1).opcode := A_SETcc;
  7276. taicpu(hp1).opsize := S_B;
  7277. taicpu(hp1).loadreg(0, NewReg);
  7278. { This is now a dead label }
  7279. tai_label(p_label).labsym.decrefs;
  7280. { Prefer adding before the next instruction so the FLAGS
  7281. register is deallicated first }
  7282. AsmL.InsertBefore(
  7283. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7284. hp1_dist
  7285. );
  7286. Result := True;
  7287. { Don't exit yet, as p wasn't changed and hp1, while
  7288. modified, is still intact and might be optimised by the
  7289. SETcc optimisation below }
  7290. end;
  7291. end;
  7292. end;
  7293. end;
  7294. if taicpu(p).oper[0]^.typ = top_const then
  7295. begin
  7296. if (taicpu(p).oper[0]^.val = 0) and
  7297. (taicpu(p).oper[1]^.typ = top_reg) and
  7298. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7299. begin
  7300. hp2 := p;
  7301. FirstMatch := True;
  7302. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7303. anything meaningful once it's converted to "test %reg,%reg";
  7304. additionally, some jumps will always (or never) branch, so
  7305. evaluate every jump immediately following the
  7306. comparison, optimising the conditions if possible.
  7307. Similarly with SETcc... those that are always set to 0 or 1
  7308. are changed to MOV instructions }
  7309. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7310. (
  7311. GetNextInstruction(hp2, hp1) and
  7312. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7313. ) do
  7314. begin
  7315. FirstMatch := False;
  7316. case taicpu(hp1).condition of
  7317. C_B, C_C, C_NAE, C_O:
  7318. { For B/NAE:
  7319. Will never branch since an unsigned integer can never be below zero
  7320. For C/O:
  7321. Result cannot overflow because 0 is being subtracted
  7322. }
  7323. begin
  7324. if taicpu(hp1).opcode = A_Jcc then
  7325. begin
  7326. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7327. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7328. RemoveInstruction(hp1);
  7329. { Since hp1 was deleted, hp2 must not be updated }
  7330. Continue;
  7331. end
  7332. else
  7333. begin
  7334. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7335. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7336. taicpu(hp1).opcode := A_MOV;
  7337. taicpu(hp1).ops := 2;
  7338. taicpu(hp1).condition := C_None;
  7339. taicpu(hp1).opsize := S_B;
  7340. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7341. taicpu(hp1).loadconst(0, 0);
  7342. end;
  7343. end;
  7344. C_BE, C_NA:
  7345. begin
  7346. { Will only branch if equal to zero }
  7347. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7348. taicpu(hp1).condition := C_E;
  7349. end;
  7350. C_A, C_NBE:
  7351. begin
  7352. { Will only branch if not equal to zero }
  7353. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7354. taicpu(hp1).condition := C_NE;
  7355. end;
  7356. C_AE, C_NB, C_NC, C_NO:
  7357. begin
  7358. { Will always branch }
  7359. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7360. if taicpu(hp1).opcode = A_Jcc then
  7361. begin
  7362. MakeUnconditional(taicpu(hp1));
  7363. { Any jumps/set that follow will now be dead code }
  7364. RemoveDeadCodeAfterJump(taicpu(hp1));
  7365. Break;
  7366. end
  7367. else
  7368. begin
  7369. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7370. taicpu(hp1).opcode := A_MOV;
  7371. taicpu(hp1).ops := 2;
  7372. taicpu(hp1).condition := C_None;
  7373. taicpu(hp1).opsize := S_B;
  7374. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7375. taicpu(hp1).loadconst(0, 1);
  7376. end;
  7377. end;
  7378. C_None:
  7379. InternalError(2020012201);
  7380. C_P, C_PE, C_NP, C_PO:
  7381. { We can't handle parity checks and they should never be generated
  7382. after a general-purpose CMP (it's used in some floating-point
  7383. comparisons that don't use CMP) }
  7384. InternalError(2020012202);
  7385. else
  7386. { Zero/Equality, Sign, their complements and all of the
  7387. signed comparisons do not need to be converted };
  7388. end;
  7389. hp2 := hp1;
  7390. end;
  7391. { Convert the instruction to a TEST }
  7392. taicpu(p).opcode := A_TEST;
  7393. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7394. Result := True;
  7395. Exit;
  7396. end
  7397. else if (taicpu(p).oper[0]^.val = 1) and
  7398. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7399. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7400. begin
  7401. { Convert; To:
  7402. cmp $1,r/m cmp $0,r/m
  7403. jl @lbl jle @lbl
  7404. (Also do inverted conditions)
  7405. }
  7406. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7407. taicpu(p).oper[0]^.val := 0;
  7408. if taicpu(hp1).condition in [C_L, C_NGE] then
  7409. taicpu(hp1).condition := C_LE
  7410. else
  7411. taicpu(hp1).condition := C_NLE;
  7412. { If the instruction is now "cmp $0,%reg", convert it to a
  7413. TEST (and effectively do the work of the "cmp $0,%reg" in
  7414. the block above)
  7415. }
  7416. if (taicpu(p).oper[1]^.typ = top_reg) then
  7417. begin
  7418. taicpu(p).opcode := A_TEST;
  7419. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7420. end;
  7421. Result := True;
  7422. Exit;
  7423. end
  7424. else if (taicpu(p).oper[1]^.typ = top_reg)
  7425. {$ifdef x86_64}
  7426. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7427. {$endif x86_64}
  7428. then
  7429. begin
  7430. { cmp register,$8000 neg register
  7431. je target --> jo target
  7432. .... only if register is deallocated before jump.}
  7433. case Taicpu(p).opsize of
  7434. S_B: v:=$80;
  7435. S_W: v:=$8000;
  7436. S_L: v:=qword($80000000);
  7437. else
  7438. internalerror(2013112905);
  7439. end;
  7440. if (taicpu(p).oper[0]^.val=v) and
  7441. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7442. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7443. begin
  7444. TransferUsedRegs(TmpUsedRegs);
  7445. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7446. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7447. begin
  7448. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7449. Taicpu(p).opcode:=A_NEG;
  7450. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7451. Taicpu(p).clearop(1);
  7452. Taicpu(p).ops:=1;
  7453. if Taicpu(hp1).condition=C_E then
  7454. Taicpu(hp1).condition:=C_O
  7455. else
  7456. Taicpu(hp1).condition:=C_NO;
  7457. Result:=true;
  7458. exit;
  7459. end;
  7460. end;
  7461. end;
  7462. end;
  7463. if TrySwapMovCmp(p, hp1) then
  7464. begin
  7465. Result := True;
  7466. Exit;
  7467. end;
  7468. end;
  7469. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7470. var
  7471. hp1: tai;
  7472. begin
  7473. {
  7474. remove the second (v)pxor from
  7475. pxor reg,reg
  7476. ...
  7477. pxor reg,reg
  7478. }
  7479. Result:=false;
  7480. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7481. MatchOpType(taicpu(p),top_reg,top_reg) and
  7482. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7483. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7484. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7485. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7486. begin
  7487. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7488. RemoveInstruction(hp1);
  7489. Result:=true;
  7490. Exit;
  7491. end
  7492. {
  7493. replace
  7494. pxor reg1,reg1
  7495. movapd/s reg1,reg2
  7496. dealloc reg1
  7497. by
  7498. pxor reg2,reg2
  7499. }
  7500. else if GetNextInstruction(p,hp1) and
  7501. { we mix single and double opperations here because we assume that the compiler
  7502. generates vmovapd only after double operations and vmovaps only after single operations }
  7503. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7504. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7505. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7506. (taicpu(p).oper[0]^.typ=top_reg) then
  7507. begin
  7508. TransferUsedRegs(TmpUsedRegs);
  7509. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7510. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7511. begin
  7512. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7513. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7514. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7515. RemoveInstruction(hp1);
  7516. result:=true;
  7517. end;
  7518. end;
  7519. end;
  7520. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7521. var
  7522. hp1: tai;
  7523. begin
  7524. {
  7525. remove the second (v)pxor from
  7526. (v)pxor reg,reg
  7527. ...
  7528. (v)pxor reg,reg
  7529. }
  7530. Result:=false;
  7531. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7532. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7533. begin
  7534. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7535. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7536. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7537. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7538. begin
  7539. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7540. RemoveInstruction(hp1);
  7541. Result:=true;
  7542. Exit;
  7543. end;
  7544. {$ifdef x86_64}
  7545. {
  7546. replace
  7547. vpxor reg1,reg1,reg1
  7548. vmov reg,mem
  7549. by
  7550. movq $0,mem
  7551. }
  7552. if GetNextInstruction(p,hp1) and
  7553. MatchInstruction(hp1,A_VMOVSD,[]) and
  7554. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7555. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7556. begin
  7557. TransferUsedRegs(TmpUsedRegs);
  7558. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7559. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7560. begin
  7561. taicpu(hp1).loadconst(0,0);
  7562. taicpu(hp1).opcode:=A_MOV;
  7563. taicpu(hp1).opsize:=S_Q;
  7564. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7565. RemoveCurrentP(p);
  7566. result:=true;
  7567. Exit;
  7568. end;
  7569. end;
  7570. {$endif x86_64}
  7571. end
  7572. {
  7573. replace
  7574. vpxor reg1,reg1,reg2
  7575. by
  7576. vpxor reg2,reg2,reg2
  7577. to avoid unncessary data dependencies
  7578. }
  7579. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7580. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7581. begin
  7582. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7583. { avoid unncessary data dependency }
  7584. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7585. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7586. result:=true;
  7587. exit;
  7588. end;
  7589. Result:=OptPass1VOP(p);
  7590. end;
  7591. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7592. var
  7593. hp1 : tai;
  7594. begin
  7595. result:=false;
  7596. { replace
  7597. IMul const,%mreg1,%mreg2
  7598. Mov %reg2,%mreg3
  7599. dealloc %mreg3
  7600. by
  7601. Imul const,%mreg1,%mreg23
  7602. }
  7603. if (taicpu(p).ops=3) and
  7604. GetNextInstruction(p,hp1) and
  7605. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7606. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7607. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7608. begin
  7609. TransferUsedRegs(TmpUsedRegs);
  7610. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7611. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7612. begin
  7613. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7614. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7615. RemoveInstruction(hp1);
  7616. result:=true;
  7617. end;
  7618. end;
  7619. end;
  7620. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7621. var
  7622. hp1 : tai;
  7623. begin
  7624. result:=false;
  7625. { replace
  7626. IMul %reg0,%reg1,%reg2
  7627. Mov %reg2,%reg3
  7628. dealloc %reg2
  7629. by
  7630. Imul %reg0,%reg1,%reg3
  7631. }
  7632. if GetNextInstruction(p,hp1) and
  7633. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7634. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7635. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7636. begin
  7637. TransferUsedRegs(TmpUsedRegs);
  7638. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7639. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7640. begin
  7641. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7642. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7643. RemoveInstruction(hp1);
  7644. result:=true;
  7645. end;
  7646. end;
  7647. end;
  7648. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7649. var
  7650. hp1: tai;
  7651. begin
  7652. Result:=false;
  7653. { get rid of
  7654. (v)cvtss2sd reg0,<reg1,>reg2
  7655. (v)cvtss2sd reg2,<reg2,>reg0
  7656. }
  7657. if GetNextInstruction(p,hp1) and
  7658. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7659. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7660. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7661. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7662. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7663. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7664. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7665. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7666. )
  7667. ) then
  7668. begin
  7669. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7670. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7671. begin
  7672. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7673. RemoveCurrentP(p);
  7674. RemoveInstruction(hp1);
  7675. end
  7676. else
  7677. begin
  7678. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7679. if taicpu(hp1).opcode=A_CVTSD2SS then
  7680. begin
  7681. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7682. taicpu(p).opcode:=A_MOVAPS;
  7683. end
  7684. else
  7685. begin
  7686. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7687. taicpu(p).opcode:=A_VMOVAPS;
  7688. end;
  7689. taicpu(p).ops:=2;
  7690. RemoveInstruction(hp1);
  7691. end;
  7692. Result:=true;
  7693. Exit;
  7694. end;
  7695. end;
  7696. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7697. var
  7698. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7699. ThisReg: TRegister;
  7700. begin
  7701. Result := False;
  7702. if not GetNextInstruction(p,hp1) then
  7703. Exit;
  7704. {
  7705. convert
  7706. j<c> .L1
  7707. mov 1,reg
  7708. jmp .L2
  7709. .L1
  7710. mov 0,reg
  7711. .L2
  7712. into
  7713. mov 0,reg
  7714. set<not(c)> reg
  7715. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7716. would destroy the flag contents
  7717. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7718. executed at the same time as a previous comparison.
  7719. set<not(c)> reg
  7720. movzx reg, reg
  7721. }
  7722. if MatchInstruction(hp1,A_MOV,[]) and
  7723. (taicpu(hp1).oper[0]^.typ = top_const) and
  7724. (
  7725. (
  7726. (taicpu(hp1).oper[1]^.typ = top_reg)
  7727. {$ifdef i386}
  7728. { Under i386, ESI, EDI, EBP and ESP
  7729. don't have an 8-bit representation }
  7730. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7731. {$endif i386}
  7732. ) or (
  7733. {$ifdef i386}
  7734. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7735. {$endif i386}
  7736. (taicpu(hp1).opsize = S_B)
  7737. )
  7738. ) and
  7739. GetNextInstruction(hp1,hp2) and
  7740. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7741. GetNextInstruction(hp2,hp3) and
  7742. SkipAligns(hp3, hp3) and
  7743. (hp3.typ=ait_label) and
  7744. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7745. GetNextInstruction(hp3,hp4) and
  7746. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7747. (taicpu(hp4).oper[0]^.typ = top_const) and
  7748. (
  7749. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7750. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7751. ) and
  7752. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7753. GetNextInstruction(hp4,hp5) and
  7754. SkipAligns(hp5, hp5) and
  7755. (hp5.typ=ait_label) and
  7756. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7757. begin
  7758. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7759. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7760. tai_label(hp3).labsym.DecRefs;
  7761. { If this isn't the only reference to the middle label, we can
  7762. still make a saving - only that the first jump and everything
  7763. that follows will remain. }
  7764. if (tai_label(hp3).labsym.getrefs = 0) then
  7765. begin
  7766. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7767. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7768. else
  7769. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7770. { remove jump, first label and second MOV (also catching any aligns) }
  7771. repeat
  7772. if not GetNextInstruction(hp2, hp3) then
  7773. InternalError(2021040810);
  7774. RemoveInstruction(hp2);
  7775. hp2 := hp3;
  7776. until hp2 = hp5;
  7777. { Don't decrement reference count before the removal loop
  7778. above, otherwise GetNextInstruction won't stop on the
  7779. the label }
  7780. tai_label(hp5).labsym.DecRefs;
  7781. end
  7782. else
  7783. begin
  7784. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7785. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7786. else
  7787. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7788. end;
  7789. taicpu(p).opcode:=A_SETcc;
  7790. taicpu(p).opsize:=S_B;
  7791. taicpu(p).is_jmp:=False;
  7792. if taicpu(hp1).opsize=S_B then
  7793. begin
  7794. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7795. if taicpu(hp1).oper[1]^.typ = top_reg then
  7796. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7797. RemoveInstruction(hp1);
  7798. end
  7799. else
  7800. begin
  7801. { Will be a register because the size can't be S_B otherwise }
  7802. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7803. taicpu(p).loadreg(0, ThisReg);
  7804. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7805. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7806. begin
  7807. case taicpu(hp1).opsize of
  7808. S_W:
  7809. taicpu(hp1).opsize := S_BW;
  7810. S_L:
  7811. taicpu(hp1).opsize := S_BL;
  7812. {$ifdef x86_64}
  7813. S_Q:
  7814. begin
  7815. taicpu(hp1).opsize := S_BL;
  7816. { Change the destination register to 32-bit }
  7817. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7818. end;
  7819. {$endif x86_64}
  7820. else
  7821. InternalError(2021040820);
  7822. end;
  7823. taicpu(hp1).opcode := A_MOVZX;
  7824. taicpu(hp1).loadreg(0, ThisReg);
  7825. end
  7826. else
  7827. begin
  7828. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7829. { hp1 is already a MOV instruction with the correct register }
  7830. taicpu(hp1).loadconst(0, 0);
  7831. { Inserting it right before p will guarantee that the flags are also tracked }
  7832. asml.Remove(hp1);
  7833. asml.InsertBefore(hp1, p);
  7834. end;
  7835. end;
  7836. Result:=true;
  7837. exit;
  7838. end
  7839. else if (hp1.typ = ait_label) then
  7840. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7841. end;
  7842. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7843. var
  7844. hp1, hp2, hp3: tai;
  7845. SourceRef, TargetRef: TReference;
  7846. CurrentReg: TRegister;
  7847. begin
  7848. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7849. if not UseAVX then
  7850. InternalError(2021100501);
  7851. Result := False;
  7852. { Look for the following to simplify:
  7853. vmovdqa/u x(mem1), %xmmreg
  7854. vmovdqa/u %xmmreg, y(mem2)
  7855. vmovdqa/u x+16(mem1), %xmmreg
  7856. vmovdqa/u %xmmreg, y+16(mem2)
  7857. Change to:
  7858. vmovdqa/u x(mem1), %ymmreg
  7859. vmovdqa/u %ymmreg, y(mem2)
  7860. vpxor %ymmreg, %ymmreg, %ymmreg
  7861. ( The VPXOR instruction is to zero the upper half, thus removing the
  7862. need to call the potentially expensive VZEROUPPER instruction. Other
  7863. peephole optimisations can remove VPXOR if it's unnecessary )
  7864. }
  7865. TransferUsedRegs(TmpUsedRegs);
  7866. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7867. { NOTE: In the optimisations below, if the references dictate that an
  7868. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7869. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7870. if (taicpu(p).opsize = S_XMM) and
  7871. MatchOpType(taicpu(p), top_ref, top_reg) and
  7872. GetNextInstruction(p, hp1) and
  7873. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7874. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7875. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7876. begin
  7877. SourceRef := taicpu(p).oper[0]^.ref^;
  7878. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7879. if GetNextInstruction(hp1, hp2) and
  7880. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7881. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7882. begin
  7883. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7884. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7885. Inc(SourceRef.offset, 16);
  7886. { Reuse the register in the first block move }
  7887. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7888. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7889. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7890. begin
  7891. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7892. Inc(TargetRef.offset, 16);
  7893. if GetNextInstruction(hp2, hp3) and
  7894. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7895. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7896. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7897. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7898. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7899. begin
  7900. { Update the register tracking to the new size }
  7901. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7902. { Remember that the offsets are 16 ahead }
  7903. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7904. if not (
  7905. ((SourceRef.offset mod 32) = 16) and
  7906. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7907. ) then
  7908. taicpu(p).opcode := A_VMOVDQU;
  7909. taicpu(p).opsize := S_YMM;
  7910. taicpu(p).oper[1]^.reg := CurrentReg;
  7911. if not (
  7912. ((TargetRef.offset mod 32) = 16) and
  7913. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7914. ) then
  7915. taicpu(hp1).opcode := A_VMOVDQU;
  7916. taicpu(hp1).opsize := S_YMM;
  7917. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7918. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7919. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7920. if (pi_uses_ymm in current_procinfo.flags) then
  7921. RemoveInstruction(hp2)
  7922. else
  7923. begin
  7924. taicpu(hp2).opcode := A_VPXOR;
  7925. taicpu(hp2).opsize := S_YMM;
  7926. taicpu(hp2).loadreg(0, CurrentReg);
  7927. taicpu(hp2).loadreg(1, CurrentReg);
  7928. taicpu(hp2).loadreg(2, CurrentReg);
  7929. taicpu(hp2).ops := 3;
  7930. end;
  7931. RemoveInstruction(hp3);
  7932. Result := True;
  7933. Exit;
  7934. end;
  7935. end
  7936. else
  7937. begin
  7938. { See if the next references are 16 less rather than 16 greater }
  7939. Dec(SourceRef.offset, 32); { -16 the other way }
  7940. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7941. begin
  7942. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7943. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7944. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7945. GetNextInstruction(hp2, hp3) and
  7946. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7947. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7948. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7949. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7950. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7951. begin
  7952. { Update the register tracking to the new size }
  7953. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7954. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7955. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7956. if not(
  7957. ((SourceRef.offset mod 32) = 0) and
  7958. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7959. ) then
  7960. taicpu(hp2).opcode := A_VMOVDQU;
  7961. taicpu(hp2).opsize := S_YMM;
  7962. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7963. if not (
  7964. ((TargetRef.offset mod 32) = 0) and
  7965. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7966. ) then
  7967. taicpu(hp3).opcode := A_VMOVDQU;
  7968. taicpu(hp3).opsize := S_YMM;
  7969. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7970. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7971. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7972. if (pi_uses_ymm in current_procinfo.flags) then
  7973. RemoveInstruction(hp1)
  7974. else
  7975. begin
  7976. taicpu(hp1).opcode := A_VPXOR;
  7977. taicpu(hp1).opsize := S_YMM;
  7978. taicpu(hp1).loadreg(0, CurrentReg);
  7979. taicpu(hp1).loadreg(1, CurrentReg);
  7980. taicpu(hp1).loadreg(2, CurrentReg);
  7981. taicpu(hp1).ops := 3;
  7982. Asml.Remove(hp1);
  7983. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7984. end;
  7985. RemoveCurrentP(p, hp2);
  7986. Result := True;
  7987. Exit;
  7988. end;
  7989. end;
  7990. end;
  7991. end;
  7992. end;
  7993. end;
  7994. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7995. var
  7996. hp2, hp3, first_assignment: tai;
  7997. IncCount, OperIdx: Integer;
  7998. OrigLabel: TAsmLabel;
  7999. begin
  8000. Count := 0;
  8001. Result := False;
  8002. first_assignment := nil;
  8003. if (LoopCount >= 20) then
  8004. begin
  8005. { Guard against infinite loops }
  8006. Exit;
  8007. end;
  8008. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8009. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8010. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8011. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8012. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8013. Exit;
  8014. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8015. {
  8016. change
  8017. jmp .L1
  8018. ...
  8019. .L1:
  8020. mov ##, ## ( multiple movs possible )
  8021. jmp/ret
  8022. into
  8023. mov ##, ##
  8024. jmp/ret
  8025. }
  8026. if not Assigned(hp1) then
  8027. begin
  8028. hp1 := GetLabelWithSym(OrigLabel);
  8029. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8030. Exit;
  8031. end;
  8032. hp2 := hp1;
  8033. while Assigned(hp2) do
  8034. begin
  8035. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  8036. SkipLabels(hp2,hp2);
  8037. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8038. Break;
  8039. case taicpu(hp2).opcode of
  8040. A_MOVSD:
  8041. begin
  8042. if taicpu(hp2).ops = 0 then
  8043. { Wrong MOVSD }
  8044. Break;
  8045. Inc(Count);
  8046. if Count >= 5 then
  8047. { Too many to be worthwhile }
  8048. Break;
  8049. GetNextInstruction(hp2, hp2);
  8050. Continue;
  8051. end;
  8052. A_MOV,
  8053. A_MOVD,
  8054. A_MOVQ,
  8055. A_MOVSX,
  8056. {$ifdef x86_64}
  8057. A_MOVSXD,
  8058. {$endif x86_64}
  8059. A_MOVZX,
  8060. A_MOVAPS,
  8061. A_MOVUPS,
  8062. A_MOVSS,
  8063. A_MOVAPD,
  8064. A_MOVUPD,
  8065. A_MOVDQA,
  8066. A_MOVDQU,
  8067. A_VMOVSS,
  8068. A_VMOVAPS,
  8069. A_VMOVUPS,
  8070. A_VMOVSD,
  8071. A_VMOVAPD,
  8072. A_VMOVUPD,
  8073. A_VMOVDQA,
  8074. A_VMOVDQU:
  8075. begin
  8076. Inc(Count);
  8077. if Count >= 5 then
  8078. { Too many to be worthwhile }
  8079. Break;
  8080. GetNextInstruction(hp2, hp2);
  8081. Continue;
  8082. end;
  8083. A_JMP:
  8084. begin
  8085. { Guard against infinite loops }
  8086. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8087. Exit;
  8088. { Analyse this jump first in case it also duplicates assignments }
  8089. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8090. begin
  8091. { Something did change! }
  8092. Result := True;
  8093. Inc(Count, IncCount);
  8094. if Count >= 5 then
  8095. begin
  8096. { Too many to be worthwhile }
  8097. Exit;
  8098. end;
  8099. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8100. Break;
  8101. end;
  8102. Result := True;
  8103. Break;
  8104. end;
  8105. A_RET:
  8106. begin
  8107. Result := True;
  8108. Break;
  8109. end;
  8110. else
  8111. Break;
  8112. end;
  8113. end;
  8114. if Result then
  8115. begin
  8116. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8117. if Count = 0 then
  8118. begin
  8119. Result := False;
  8120. Exit;
  8121. end;
  8122. hp3 := p;
  8123. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8124. while True do
  8125. begin
  8126. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  8127. SkipLabels(hp1,hp1);
  8128. if (hp1.typ <> ait_instruction) then
  8129. InternalError(2021040720);
  8130. case taicpu(hp1).opcode of
  8131. A_JMP:
  8132. begin
  8133. { Change the original jump to the new destination }
  8134. OrigLabel.decrefs;
  8135. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8136. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8137. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8138. if not Assigned(first_assignment) then
  8139. InternalError(2021040810)
  8140. else
  8141. p := first_assignment;
  8142. Exit;
  8143. end;
  8144. A_RET:
  8145. begin
  8146. { Now change the jump into a RET instruction }
  8147. ConvertJumpToRET(p, hp1);
  8148. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8149. if not Assigned(first_assignment) then
  8150. InternalError(2021040811)
  8151. else
  8152. p := first_assignment;
  8153. Exit;
  8154. end;
  8155. else
  8156. begin
  8157. { Duplicate the MOV instruction }
  8158. hp3:=tai(hp1.getcopy);
  8159. if first_assignment = nil then
  8160. first_assignment := hp3;
  8161. asml.InsertBefore(hp3, p);
  8162. { Make sure the compiler knows about any final registers written here }
  8163. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8164. with taicpu(hp3).oper[OperIdx]^ do
  8165. begin
  8166. case typ of
  8167. top_ref:
  8168. begin
  8169. if (ref^.base <> NR_NO) and
  8170. (getsupreg(ref^.base) <> RS_ESP) and
  8171. (getsupreg(ref^.base) <> RS_EBP)
  8172. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8173. then
  8174. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  8175. if (ref^.index <> NR_NO) and
  8176. (getsupreg(ref^.index) <> RS_ESP) and
  8177. (getsupreg(ref^.index) <> RS_EBP)
  8178. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8179. (ref^.index <> ref^.base) then
  8180. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  8181. end;
  8182. top_reg:
  8183. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8184. else
  8185. ;
  8186. end;
  8187. end;
  8188. end;
  8189. end;
  8190. if not GetNextInstruction(hp1, hp1) then
  8191. { Should have dropped out earlier }
  8192. InternalError(2021040710);
  8193. end;
  8194. end;
  8195. end;
  8196. const
  8197. WriteOp: array[0..3] of set of TInsChange = (
  8198. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8199. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8200. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8201. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8202. RegWriteFlags: array[0..7] of set of TInsChange = (
  8203. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8204. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8205. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8206. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8207. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8208. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8209. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8210. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8211. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8212. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8213. var
  8214. hp2: tai;
  8215. X: Integer;
  8216. begin
  8217. { If we have something like:
  8218. op ###,###
  8219. mov ###,###
  8220. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8221. interfere in regards to what they write to.
  8222. NOTE: p must be a 2-operand instruction
  8223. }
  8224. Result := False;
  8225. if (hp1.typ <> ait_instruction) or
  8226. taicpu(hp1).is_jmp or
  8227. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8228. Exit;
  8229. { NOP is a pipeline fence, likely marking the beginning of the function
  8230. epilogue, so drop out. Similarly, drop out if POP or RET are
  8231. encountered }
  8232. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8233. Exit;
  8234. if (taicpu(hp1).opcode = A_MOVSD) and
  8235. (taicpu(hp1).ops = 0) then
  8236. { Wrong MOVSD }
  8237. Exit;
  8238. { Check for writes to specific registers first }
  8239. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8240. for X := 0 to 7 do
  8241. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8242. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8243. Exit;
  8244. for X := 0 to taicpu(hp1).ops - 1 do
  8245. begin
  8246. { Check to see if this operand writes to something }
  8247. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8248. { And matches something in the CMP/TEST instruction }
  8249. (
  8250. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8251. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8252. (
  8253. { If it's a register, make sure the register written to doesn't
  8254. appear in the cmp instruction as part of a reference }
  8255. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8256. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8257. )
  8258. ) then
  8259. Exit;
  8260. end;
  8261. { Check p to make sure it doesn't write to something that affects hp1 }
  8262. { Check for writes to specific registers first }
  8263. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8264. for X := 0 to 7 do
  8265. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8266. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8267. Exit;
  8268. for X := 0 to taicpu(p).ops - 1 do
  8269. begin
  8270. { Check to see if this operand writes to something }
  8271. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8272. { And matches something in hp1 }
  8273. (taicpu(p).oper[X]^.typ = top_reg) and
  8274. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8275. Exit;
  8276. end;
  8277. { The instruction can be safely moved }
  8278. asml.Remove(hp1);
  8279. { Try to insert after the last instructions where the FLAGS register is not
  8280. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8281. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8282. asml.InsertBefore(hp1, hp2)
  8283. { Failing that, try to insert after the last instructions where the
  8284. FLAGS register is not yet in use }
  8285. else if GetLastInstruction(p, hp2) and
  8286. (
  8287. (hp2.typ <> ait_instruction) or
  8288. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8289. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8290. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8291. ) then
  8292. asml.InsertAfter(hp1, hp2)
  8293. else
  8294. { Note, if p.Previous is nil (even if it should logically never be the
  8295. case), FindRegAllocBackward immediately exits with False and so we
  8296. safely land here (we can't just pass p because FindRegAllocBackward
  8297. immediately exits on an instruction). [Kit] }
  8298. asml.InsertBefore(hp1, p);
  8299. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8300. { We can't trust UsedRegs because we're looking backwards, although we
  8301. know the registers are allocated after p at the very least, so manually
  8302. create tai_regalloc objects if needed }
  8303. for X := 0 to taicpu(hp1).ops - 1 do
  8304. case taicpu(hp1).oper[X]^.typ of
  8305. top_reg:
  8306. begin
  8307. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8308. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8309. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8310. end;
  8311. top_ref:
  8312. begin
  8313. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8314. begin
  8315. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8316. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8317. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8318. end;
  8319. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8320. begin
  8321. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8322. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8323. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8324. end;
  8325. end;
  8326. else
  8327. ;
  8328. end;
  8329. Result := True;
  8330. end;
  8331. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8332. var
  8333. hp2: tai;
  8334. X: Integer;
  8335. begin
  8336. { If we have something like:
  8337. cmp ###,%reg1
  8338. mov 0,%reg2
  8339. And no modified registers are shared, move the instruction to before
  8340. the comparison as this means it can be optimised without worrying
  8341. about the FLAGS register. (CMP/MOV is generated by
  8342. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8343. As long as the second instruction doesn't use the flags or one of the
  8344. registers used by CMP or TEST (also check any references that use the
  8345. registers), then it can be moved prior to the comparison.
  8346. }
  8347. Result := False;
  8348. if not TrySwapMovOp(p, hp1) then
  8349. Exit;
  8350. if taicpu(hp1).opcode = A_LEA then
  8351. { The flags will be overwritten by the CMP/TEST instruction }
  8352. ConvertLEA(taicpu(hp1));
  8353. Result := True;
  8354. { Can we move it one further back? }
  8355. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8356. { Check to see if CMP/TEST is a comparison against zero }
  8357. (
  8358. (
  8359. (taicpu(p).opcode = A_CMP) and
  8360. MatchOperand(taicpu(p).oper[0]^, 0)
  8361. ) or
  8362. (
  8363. (taicpu(p).opcode = A_TEST) and
  8364. (
  8365. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8366. MatchOperand(taicpu(p).oper[0]^, -1)
  8367. )
  8368. )
  8369. ) and
  8370. { These instructions set the zero flag if the result is zero }
  8371. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8372. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8373. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8374. TrySwapMovOp(hp2, hp1);
  8375. end;
  8376. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8377. function IsXCHGAcceptable: Boolean; inline;
  8378. begin
  8379. { Always accept if optimising for size }
  8380. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8381. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8382. than 3, so it becomes a saving compared to three MOVs with two of
  8383. them able to execute simultaneously. [Kit] }
  8384. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8385. end;
  8386. var
  8387. NewRef: TReference;
  8388. hp1, hp2, hp3, hp4: Tai;
  8389. {$ifndef x86_64}
  8390. OperIdx: Integer;
  8391. {$endif x86_64}
  8392. NewInstr : Taicpu;
  8393. NewAligh : Tai_align;
  8394. DestLabel: TAsmLabel;
  8395. TempTracking: TAllUsedRegs;
  8396. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8397. var
  8398. NextInstr: tai;
  8399. begin
  8400. Result := False;
  8401. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8402. if not GetNextInstruction(InputInstr, NextInstr) or
  8403. (
  8404. { The FLAGS register isn't always tracked properly, so do not
  8405. perform this optimisation if a conditional statement follows }
  8406. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8407. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8408. ) then
  8409. begin
  8410. reference_reset(NewRef, 1, []);
  8411. NewRef.base := taicpu(p).oper[0]^.reg;
  8412. NewRef.scalefactor := 1;
  8413. if taicpu(InputInstr).opcode = A_ADD then
  8414. begin
  8415. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8416. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8417. end
  8418. else
  8419. begin
  8420. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8421. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8422. end;
  8423. taicpu(p).opcode := A_LEA;
  8424. taicpu(p).loadref(0, NewRef);
  8425. RemoveInstruction(InputInstr);
  8426. Result := True;
  8427. end;
  8428. end;
  8429. begin
  8430. Result:=false;
  8431. { This optimisation adds an instruction, so only do it for speed }
  8432. if not (cs_opt_size in current_settings.optimizerswitches) and
  8433. MatchOpType(taicpu(p), top_const, top_reg) and
  8434. (taicpu(p).oper[0]^.val = 0) then
  8435. begin
  8436. { To avoid compiler warning }
  8437. DestLabel := nil;
  8438. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8439. InternalError(2021040750);
  8440. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8441. Exit;
  8442. case hp1.typ of
  8443. ait_align,
  8444. ait_label:
  8445. begin
  8446. { Change:
  8447. mov $0,%reg mov $0,%reg
  8448. @Lbl1: @Lbl1:
  8449. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8450. je @Lbl2 jne @Lbl2
  8451. To: To:
  8452. mov $0,%reg mov $0,%reg
  8453. jmp @Lbl2 jmp @Lbl3
  8454. (align) (align)
  8455. @Lbl1: @Lbl1:
  8456. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8457. je @Lbl2 je @Lbl2
  8458. @Lbl3: <-- Only if label exists
  8459. (Not if it's optimised for size)
  8460. }
  8461. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8462. Exit;
  8463. if (hp2.typ = ait_instruction) and
  8464. (
  8465. { Register sizes must exactly match }
  8466. (
  8467. (taicpu(hp2).opcode = A_CMP) and
  8468. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8469. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8470. ) or (
  8471. (taicpu(hp2).opcode = A_TEST) and
  8472. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8473. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8474. )
  8475. ) and GetNextInstruction(hp2, hp3) and
  8476. (hp3.typ = ait_instruction) and
  8477. (taicpu(hp3).opcode = A_JCC) and
  8478. (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
  8479. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8480. begin
  8481. { Check condition of jump }
  8482. { Always true? }
  8483. if condition_in(C_E, taicpu(hp3).condition) then
  8484. begin
  8485. { Copy label symbol and obtain matching label entry for the
  8486. conditional jump, as this will be our destination}
  8487. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8488. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8489. Result := True;
  8490. end
  8491. { Always false? }
  8492. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8493. begin
  8494. { This is only worth it if there's a jump to take }
  8495. case hp2.typ of
  8496. ait_instruction:
  8497. begin
  8498. if taicpu(hp2).opcode = A_JMP then
  8499. begin
  8500. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8501. { An unconditional jump follows the conditional jump which will always be false,
  8502. so use this jump's destination for the new jump }
  8503. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8504. Result := True;
  8505. end
  8506. else if taicpu(hp2).opcode = A_JCC then
  8507. begin
  8508. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8509. if condition_in(C_E, taicpu(hp2).condition) then
  8510. begin
  8511. { A second conditional jump follows the conditional jump which will always be false,
  8512. while the second jump is always True, so use this jump's destination for the new jump }
  8513. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8514. Result := True;
  8515. end;
  8516. { Don't risk it if the jump isn't always true (Result remains False) }
  8517. end;
  8518. end;
  8519. else
  8520. { If anything else don't optimise };
  8521. end;
  8522. end;
  8523. if Result then
  8524. begin
  8525. { Just so we have something to insert as a paremeter}
  8526. reference_reset(NewRef, 1, []);
  8527. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8528. { Now actually load the correct parameter (this also
  8529. increases the reference count) }
  8530. NewInstr.loadsymbol(0, DestLabel, 0);
  8531. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8532. begin
  8533. { Get instruction before original label (may not be p under -O3) }
  8534. if not GetLastInstruction(hp1, hp2) then
  8535. { Shouldn't fail here }
  8536. InternalError(2021040701);
  8537. { Before the aligns too }
  8538. while (hp2.typ = ait_align) do
  8539. if not GetLastInstruction(hp2, hp2) then
  8540. { Shouldn't fail here }
  8541. InternalError(2021040702);
  8542. end
  8543. else
  8544. hp2 := p;
  8545. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8546. AsmL.InsertAfter(NewInstr, hp2);
  8547. { Add new alignment field }
  8548. (* AsmL.InsertAfter(
  8549. cai_align.create_max(
  8550. current_settings.alignment.jumpalign,
  8551. current_settings.alignment.jumpalignskipmax
  8552. ),
  8553. NewInstr
  8554. ); *)
  8555. end;
  8556. Exit;
  8557. end;
  8558. end;
  8559. else
  8560. ;
  8561. end;
  8562. end;
  8563. if not GetNextInstruction(p, hp1) then
  8564. Exit;
  8565. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8566. and DoMovCmpMemOpt(p, hp1) then
  8567. begin
  8568. Result := True;
  8569. Exit;
  8570. end
  8571. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8572. begin
  8573. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8574. further, but we can't just put this jump optimisation in pass 1
  8575. because it tends to perform worse when conditional jumps are
  8576. nearby (e.g. when converting CMOV instructions). [Kit] }
  8577. CopyUsedRegs(TempTracking);
  8578. UpdateUsedRegs(tai(p.Next));
  8579. if OptPass2JMP(hp1) then
  8580. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8581. Result := OptPass1MOV(p);
  8582. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8583. returned True and the instruction is still a MOV, thus checking
  8584. the optimisations below }
  8585. { If OptPass2JMP returned False, no optimisations were done to
  8586. the jump and there are no further optimisations that can be done
  8587. to the MOV instruction on this pass }
  8588. { Restore register state }
  8589. RestoreUsedRegs(TempTracking);
  8590. ReleaseUsedRegs(TempTracking);
  8591. end
  8592. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8593. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8594. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8595. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8596. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8597. begin
  8598. { Change:
  8599. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8600. addl/q $x,%reg2 subl/q $x,%reg2
  8601. To:
  8602. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8603. }
  8604. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8605. { be lazy, checking separately for sub would be slightly better }
  8606. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8607. begin
  8608. TransferUsedRegs(TmpUsedRegs);
  8609. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8610. if TryMovArith2Lea(hp1) then
  8611. begin
  8612. Result := True;
  8613. Exit;
  8614. end
  8615. end
  8616. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8617. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8618. { Same as above, but also adds or subtracts to %reg2 in between.
  8619. It's still valid as long as the flags aren't in use }
  8620. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8621. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8622. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8623. { be lazy, checking separately for sub would be slightly better }
  8624. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8625. begin
  8626. TransferUsedRegs(TmpUsedRegs);
  8627. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8628. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8629. if TryMovArith2Lea(hp2) then
  8630. begin
  8631. Result := True;
  8632. Exit;
  8633. end;
  8634. end;
  8635. end
  8636. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8637. {$ifdef x86_64}
  8638. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8639. {$else x86_64}
  8640. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8641. {$endif x86_64}
  8642. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8643. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8644. { mov reg1, reg2 mov reg1, reg2
  8645. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8646. begin
  8647. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8648. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8649. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8650. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8651. TransferUsedRegs(TmpUsedRegs);
  8652. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8653. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8654. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8655. then
  8656. begin
  8657. RemoveCurrentP(p, hp1);
  8658. Result:=true;
  8659. end;
  8660. exit;
  8661. end
  8662. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8663. IsXCHGAcceptable and
  8664. { XCHG doesn't support 8-byte registers }
  8665. (taicpu(p).opsize <> S_B) and
  8666. MatchInstruction(hp1, A_MOV, []) and
  8667. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8668. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8669. GetNextInstruction(hp1, hp2) and
  8670. MatchInstruction(hp2, A_MOV, []) and
  8671. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8672. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8673. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8674. begin
  8675. { mov %reg1,%reg2
  8676. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8677. mov %reg2,%reg3
  8678. (%reg2 not used afterwards)
  8679. Note that xchg takes 3 cycles to execute, and generally mov's take
  8680. only one cycle apiece, but the first two mov's can be executed in
  8681. parallel, only taking 2 cycles overall. Older processors should
  8682. therefore only optimise for size. [Kit]
  8683. }
  8684. TransferUsedRegs(TmpUsedRegs);
  8685. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8686. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8687. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8688. begin
  8689. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8690. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8691. taicpu(hp1).opcode := A_XCHG;
  8692. RemoveCurrentP(p, hp1);
  8693. RemoveInstruction(hp2);
  8694. Result := True;
  8695. Exit;
  8696. end;
  8697. end
  8698. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8699. MatchInstruction(hp1, A_SAR, []) then
  8700. begin
  8701. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8702. begin
  8703. { the use of %edx also covers the opsize being S_L }
  8704. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8705. begin
  8706. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8707. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8708. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8709. begin
  8710. { Change:
  8711. movl %eax,%edx
  8712. sarl $31,%edx
  8713. To:
  8714. cltd
  8715. }
  8716. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8717. RemoveInstruction(hp1);
  8718. taicpu(p).opcode := A_CDQ;
  8719. taicpu(p).opsize := S_NO;
  8720. taicpu(p).clearop(1);
  8721. taicpu(p).clearop(0);
  8722. taicpu(p).ops:=0;
  8723. Result := True;
  8724. end
  8725. else if (cs_opt_size in current_settings.optimizerswitches) and
  8726. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8727. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8728. begin
  8729. { Change:
  8730. movl %edx,%eax
  8731. sarl $31,%edx
  8732. To:
  8733. movl %edx,%eax
  8734. cltd
  8735. Note that this creates a dependency between the two instructions,
  8736. so only perform if optimising for size.
  8737. }
  8738. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8739. taicpu(hp1).opcode := A_CDQ;
  8740. taicpu(hp1).opsize := S_NO;
  8741. taicpu(hp1).clearop(1);
  8742. taicpu(hp1).clearop(0);
  8743. taicpu(hp1).ops:=0;
  8744. end;
  8745. {$ifndef x86_64}
  8746. end
  8747. { Don't bother if CMOV is supported, because a more optimal
  8748. sequence would have been generated for the Abs() intrinsic }
  8749. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8750. { the use of %eax also covers the opsize being S_L }
  8751. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8752. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8753. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8754. GetNextInstruction(hp1, hp2) and
  8755. MatchInstruction(hp2, A_XOR, [S_L]) and
  8756. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8757. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8758. GetNextInstruction(hp2, hp3) and
  8759. MatchInstruction(hp3, A_SUB, [S_L]) and
  8760. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8761. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8762. begin
  8763. { Change:
  8764. movl %eax,%edx
  8765. sarl $31,%eax
  8766. xorl %eax,%edx
  8767. subl %eax,%edx
  8768. (Instruction that uses %edx)
  8769. (%eax deallocated)
  8770. (%edx deallocated)
  8771. To:
  8772. cltd
  8773. xorl %edx,%eax <-- Note the registers have swapped
  8774. subl %edx,%eax
  8775. (Instruction that uses %eax) <-- %eax rather than %edx
  8776. }
  8777. TransferUsedRegs(TmpUsedRegs);
  8778. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8779. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8780. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8781. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8782. begin
  8783. if GetNextInstruction(hp3, hp4) and
  8784. not RegModifiedByInstruction(NR_EDX, hp4) and
  8785. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8786. begin
  8787. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8788. taicpu(p).opcode := A_CDQ;
  8789. taicpu(p).clearop(1);
  8790. taicpu(p).clearop(0);
  8791. taicpu(p).ops:=0;
  8792. RemoveInstruction(hp1);
  8793. taicpu(hp2).loadreg(0, NR_EDX);
  8794. taicpu(hp2).loadreg(1, NR_EAX);
  8795. taicpu(hp3).loadreg(0, NR_EDX);
  8796. taicpu(hp3).loadreg(1, NR_EAX);
  8797. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8798. { Convert references in the following instruction (hp4) from %edx to %eax }
  8799. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8800. with taicpu(hp4).oper[OperIdx]^ do
  8801. case typ of
  8802. top_reg:
  8803. if getsupreg(reg) = RS_EDX then
  8804. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8805. top_ref:
  8806. begin
  8807. if getsupreg(reg) = RS_EDX then
  8808. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8809. if getsupreg(reg) = RS_EDX then
  8810. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8811. end;
  8812. else
  8813. ;
  8814. end;
  8815. end;
  8816. end;
  8817. {$else x86_64}
  8818. end;
  8819. end
  8820. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8821. { the use of %rdx also covers the opsize being S_Q }
  8822. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8823. begin
  8824. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8825. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8826. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8827. begin
  8828. { Change:
  8829. movq %rax,%rdx
  8830. sarq $63,%rdx
  8831. To:
  8832. cqto
  8833. }
  8834. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8835. RemoveInstruction(hp1);
  8836. taicpu(p).opcode := A_CQO;
  8837. taicpu(p).opsize := S_NO;
  8838. taicpu(p).clearop(1);
  8839. taicpu(p).clearop(0);
  8840. taicpu(p).ops:=0;
  8841. Result := True;
  8842. end
  8843. else if (cs_opt_size in current_settings.optimizerswitches) and
  8844. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8845. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8846. begin
  8847. { Change:
  8848. movq %rdx,%rax
  8849. sarq $63,%rdx
  8850. To:
  8851. movq %rdx,%rax
  8852. cqto
  8853. Note that this creates a dependency between the two instructions,
  8854. so only perform if optimising for size.
  8855. }
  8856. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8857. taicpu(hp1).opcode := A_CQO;
  8858. taicpu(hp1).opsize := S_NO;
  8859. taicpu(hp1).clearop(1);
  8860. taicpu(hp1).clearop(0);
  8861. taicpu(hp1).ops:=0;
  8862. {$endif x86_64}
  8863. end;
  8864. end;
  8865. end
  8866. else if MatchInstruction(hp1, A_MOV, []) and
  8867. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8868. { Though "GetNextInstruction" could be factored out, along with
  8869. the instructions that depend on hp2, it is an expensive call that
  8870. should be delayed for as long as possible, hence we do cheaper
  8871. checks first that are likely to be False. [Kit] }
  8872. begin
  8873. if (
  8874. (
  8875. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8876. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8877. (
  8878. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8879. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8880. )
  8881. ) or
  8882. (
  8883. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8884. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8885. (
  8886. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8887. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8888. )
  8889. )
  8890. ) and
  8891. GetNextInstruction(hp1, hp2) and
  8892. MatchInstruction(hp2, A_SAR, []) and
  8893. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8894. begin
  8895. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8896. begin
  8897. { Change:
  8898. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8899. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8900. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8901. To:
  8902. movl r/m,%eax <- Note the change in register
  8903. cltd
  8904. }
  8905. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8906. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8907. taicpu(p).loadreg(1, NR_EAX);
  8908. taicpu(hp1).opcode := A_CDQ;
  8909. taicpu(hp1).clearop(1);
  8910. taicpu(hp1).clearop(0);
  8911. taicpu(hp1).ops:=0;
  8912. RemoveInstruction(hp2);
  8913. (*
  8914. {$ifdef x86_64}
  8915. end
  8916. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8917. { This code sequence does not get generated - however it might become useful
  8918. if and when 128-bit signed integer types make an appearance, so the code
  8919. is kept here for when it is eventually needed. [Kit] }
  8920. (
  8921. (
  8922. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8923. (
  8924. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8925. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8926. )
  8927. ) or
  8928. (
  8929. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8930. (
  8931. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8932. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8933. )
  8934. )
  8935. ) and
  8936. GetNextInstruction(hp1, hp2) and
  8937. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8938. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8939. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8940. begin
  8941. { Change:
  8942. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8943. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8944. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8945. To:
  8946. movq r/m,%rax <- Note the change in register
  8947. cqto
  8948. }
  8949. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8950. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8951. taicpu(p).loadreg(1, NR_RAX);
  8952. taicpu(hp1).opcode := A_CQO;
  8953. taicpu(hp1).clearop(1);
  8954. taicpu(hp1).clearop(0);
  8955. taicpu(hp1).ops:=0;
  8956. RemoveInstruction(hp2);
  8957. {$endif x86_64}
  8958. *)
  8959. end;
  8960. end;
  8961. {$ifdef x86_64}
  8962. end
  8963. else if (taicpu(p).opsize = S_L) and
  8964. (taicpu(p).oper[1]^.typ = top_reg) and
  8965. (
  8966. MatchInstruction(hp1, A_MOV,[]) and
  8967. (taicpu(hp1).opsize = S_L) and
  8968. (taicpu(hp1).oper[1]^.typ = top_reg)
  8969. ) and (
  8970. GetNextInstruction(hp1, hp2) and
  8971. (tai(hp2).typ=ait_instruction) and
  8972. (taicpu(hp2).opsize = S_Q) and
  8973. (
  8974. (
  8975. MatchInstruction(hp2, A_ADD,[]) and
  8976. (taicpu(hp2).opsize = S_Q) and
  8977. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8978. (
  8979. (
  8980. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8981. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8982. ) or (
  8983. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8984. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8985. )
  8986. )
  8987. ) or (
  8988. MatchInstruction(hp2, A_LEA,[]) and
  8989. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8990. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8991. (
  8992. (
  8993. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8994. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8995. ) or (
  8996. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8997. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8998. )
  8999. ) and (
  9000. (
  9001. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9002. ) or (
  9003. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9004. )
  9005. )
  9006. )
  9007. )
  9008. ) and (
  9009. GetNextInstruction(hp2, hp3) and
  9010. MatchInstruction(hp3, A_SHR,[]) and
  9011. (taicpu(hp3).opsize = S_Q) and
  9012. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9013. (taicpu(hp3).oper[0]^.val = 1) and
  9014. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  9015. ) then
  9016. begin
  9017. { Change movl x, reg1d movl x, reg1d
  9018. movl y, reg2d movl y, reg2d
  9019. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  9020. shrq $1, reg1q shrq $1, reg1q
  9021. ( reg1d and reg2d can be switched around in the first two instructions )
  9022. To movl x, reg1d
  9023. addl y, reg1d
  9024. rcrl $1, reg1d
  9025. This corresponds to the common expression (x + y) shr 1, where
  9026. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  9027. smaller code, but won't account for x + y causing an overflow). [Kit]
  9028. }
  9029. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  9030. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  9031. { Change first MOV command to have the same register as the final output }
  9032. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  9033. else
  9034. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  9035. { Change second MOV command to an ADD command. This is easier than
  9036. converting the existing command because it means we don't have to
  9037. touch 'y', which might be a complicated reference, and also the
  9038. fact that the third command might either be ADD or LEA. [Kit] }
  9039. taicpu(hp1).opcode := A_ADD;
  9040. { Delete old ADD/LEA instruction }
  9041. RemoveInstruction(hp2);
  9042. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  9043. taicpu(hp3).opcode := A_RCR;
  9044. taicpu(hp3).changeopsize(S_L);
  9045. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  9046. {$endif x86_64}
  9047. end;
  9048. if FuncMov2Func(p, hp1) then
  9049. begin
  9050. Result := True;
  9051. Exit;
  9052. end;
  9053. end;
  9054. {$push}
  9055. {$q-}{$r-}
  9056. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  9057. var
  9058. ThisReg: TRegister;
  9059. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  9060. TargetSubReg: TSubRegister;
  9061. hp1, hp2: tai;
  9062. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  9063. { Store list of found instructions so we don't have to call
  9064. GetNextInstructionUsingReg multiple times }
  9065. InstrList: array of taicpu;
  9066. InstrMax, Index: Integer;
  9067. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  9068. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  9069. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  9070. WorkingValue: TCgInt;
  9071. PreMessage: string;
  9072. { Data flow analysis }
  9073. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  9074. BitwiseOnly, OrXorUsed,
  9075. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  9076. function CheckOverflowConditions: Boolean;
  9077. begin
  9078. Result := True;
  9079. if (TestValSignedMax > SignedUpperLimit) then
  9080. UpperSignedOverflow := True;
  9081. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  9082. LowerSignedOverflow := True;
  9083. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  9084. LowerUnsignedOverflow := True;
  9085. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  9086. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  9087. begin
  9088. { Absolute overflow }
  9089. Result := False;
  9090. Exit;
  9091. end;
  9092. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  9093. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  9094. ShiftDownOverflow := True;
  9095. if (TestValMin < 0) or (TestValMax < 0) then
  9096. begin
  9097. LowerUnsignedOverflow := True;
  9098. UpperUnsignedOverflow := True;
  9099. end;
  9100. end;
  9101. function AdjustInitialLoadAndSize: Boolean;
  9102. begin
  9103. Result := False;
  9104. if not p_removed then
  9105. begin
  9106. if TargetSize = MinSize then
  9107. begin
  9108. { Convert the input MOVZX to a MOV }
  9109. if (taicpu(p).oper[0]^.typ = top_reg) and
  9110. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9111. begin
  9112. { Or remove it completely! }
  9113. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  9114. RemoveCurrentP(p);
  9115. p_removed := True;
  9116. end
  9117. else
  9118. begin
  9119. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  9120. taicpu(p).opcode := A_MOV;
  9121. taicpu(p).oper[1]^.reg := ThisReg;
  9122. taicpu(p).opsize := TargetSize;
  9123. end;
  9124. Result := True;
  9125. end
  9126. else if TargetSize <> MaxSize then
  9127. begin
  9128. case MaxSize of
  9129. S_L:
  9130. if TargetSize = S_W then
  9131. begin
  9132. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  9133. taicpu(p).opsize := S_BW;
  9134. taicpu(p).oper[1]^.reg := ThisReg;
  9135. Result := True;
  9136. end
  9137. else
  9138. InternalError(2020112341);
  9139. S_W:
  9140. if TargetSize = S_L then
  9141. begin
  9142. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  9143. taicpu(p).opsize := S_BL;
  9144. taicpu(p).oper[1]^.reg := ThisReg;
  9145. Result := True;
  9146. end
  9147. else
  9148. InternalError(2020112342);
  9149. else
  9150. ;
  9151. end;
  9152. end
  9153. else if not hp1_removed and not RegInUse then
  9154. begin
  9155. { If we have something like:
  9156. movzbl (oper),%regd
  9157. add x, %regd
  9158. movzbl %regb, %regd
  9159. We can reduce the register size to the input of the final
  9160. movzbl instruction. Overflows won't have any effect.
  9161. }
  9162. if (taicpu(p).opsize in [S_BW, S_BL]) and
  9163. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9164. begin
  9165. TargetSize := S_B;
  9166. setsubreg(ThisReg, R_SUBL);
  9167. Result := True;
  9168. end
  9169. else if (taicpu(p).opsize = S_WL) and
  9170. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  9171. begin
  9172. TargetSize := S_W;
  9173. setsubreg(ThisReg, R_SUBW);
  9174. Result := True;
  9175. end;
  9176. if Result then
  9177. begin
  9178. { Convert the input MOVZX to a MOV }
  9179. if (taicpu(p).oper[0]^.typ = top_reg) and
  9180. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  9181. begin
  9182. { Or remove it completely! }
  9183. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9184. RemoveCurrentP(p);
  9185. p_removed := True;
  9186. end
  9187. else
  9188. begin
  9189. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9190. taicpu(p).opcode := A_MOV;
  9191. taicpu(p).oper[1]^.reg := ThisReg;
  9192. taicpu(p).opsize := TargetSize;
  9193. end;
  9194. end;
  9195. end;
  9196. end;
  9197. end;
  9198. procedure AdjustFinalLoad;
  9199. begin
  9200. if not LowerUnsignedOverflow then
  9201. begin
  9202. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9203. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9204. begin
  9205. { Convert the output MOVZX to a MOV }
  9206. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9207. begin
  9208. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9209. if (MinSize = S_B) or
  9210. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9211. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9212. begin
  9213. { Remove it completely! }
  9214. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9215. { Be careful; if p = hp1 and p was also removed, p
  9216. will become a dangling pointer }
  9217. if p = hp1 then
  9218. begin
  9219. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9220. p_removed := True;
  9221. end
  9222. else
  9223. RemoveInstruction(hp1);
  9224. hp1_removed := True;
  9225. end;
  9226. end
  9227. else
  9228. begin
  9229. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9230. taicpu(hp1).opcode := A_MOV;
  9231. taicpu(hp1).oper[0]^.reg := ThisReg;
  9232. taicpu(hp1).opsize := TargetSize;
  9233. end;
  9234. end
  9235. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9236. begin
  9237. { Need to change the size of the output }
  9238. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9239. taicpu(hp1).oper[0]^.reg := ThisReg;
  9240. taicpu(hp1).opsize := S_BL;
  9241. end;
  9242. end;
  9243. end;
  9244. function CompressInstructions: Boolean;
  9245. var
  9246. LocalIndex: Integer;
  9247. begin
  9248. Result := False;
  9249. { The objective here is to try to find a combination that
  9250. removes one of the MOV/Z instructions. }
  9251. if (
  9252. (taicpu(p).oper[0]^.typ <> top_reg) or
  9253. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9254. ) and
  9255. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9256. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9257. begin
  9258. { Make a preference to remove the second MOVZX instruction }
  9259. case taicpu(hp1).opsize of
  9260. S_BL, S_WL:
  9261. begin
  9262. TargetSize := S_L;
  9263. TargetSubReg := R_SUBD;
  9264. end;
  9265. S_BW:
  9266. begin
  9267. TargetSize := S_W;
  9268. TargetSubReg := R_SUBW;
  9269. end;
  9270. else
  9271. InternalError(2020112302);
  9272. end;
  9273. end
  9274. else
  9275. begin
  9276. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9277. begin
  9278. { Exceeded lower bound but not upper bound }
  9279. TargetSize := MaxSize;
  9280. end
  9281. else if not LowerUnsignedOverflow then
  9282. begin
  9283. { Size didn't exceed lower bound }
  9284. TargetSize := MinSize;
  9285. end
  9286. else
  9287. Exit;
  9288. end;
  9289. case TargetSize of
  9290. S_B:
  9291. TargetSubReg := R_SUBL;
  9292. S_W:
  9293. TargetSubReg := R_SUBW;
  9294. S_L:
  9295. TargetSubReg := R_SUBD;
  9296. else
  9297. InternalError(2020112350);
  9298. end;
  9299. { Update the register to its new size }
  9300. setsubreg(ThisReg, TargetSubReg);
  9301. RegInUse := False;
  9302. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9303. begin
  9304. { Check to see if the active register is used afterwards;
  9305. if not, we can change it and make a saving. }
  9306. TransferUsedRegs(TmpUsedRegs);
  9307. { The target register may be marked as in use to cross
  9308. a jump to a distant label, so exclude it }
  9309. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9310. hp2 := p;
  9311. repeat
  9312. { Explicitly check for the excluded register (don't include the first
  9313. instruction as it may be reading from here }
  9314. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9315. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9316. begin
  9317. RegInUse := True;
  9318. Break;
  9319. end;
  9320. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9321. if not GetNextInstruction(hp2, hp2) then
  9322. InternalError(2020112340);
  9323. until (hp2 = hp1);
  9324. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9325. { We might still be able to get away with this }
  9326. RegInUse := not
  9327. (
  9328. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9329. (hp2.typ = ait_instruction) and
  9330. (
  9331. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9332. instruction that doesn't actually contain ThisReg }
  9333. (cs_opt_level3 in current_settings.optimizerswitches) or
  9334. RegInInstruction(ThisReg, hp2)
  9335. ) and
  9336. RegLoadedWithNewValue(ThisReg, hp2)
  9337. );
  9338. if not RegInUse then
  9339. begin
  9340. { Force the register size to the same as this instruction so it can be removed}
  9341. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9342. begin
  9343. TargetSize := S_L;
  9344. TargetSubReg := R_SUBD;
  9345. end
  9346. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9347. begin
  9348. TargetSize := S_W;
  9349. TargetSubReg := R_SUBW;
  9350. end;
  9351. ThisReg := taicpu(hp1).oper[1]^.reg;
  9352. setsubreg(ThisReg, TargetSubReg);
  9353. RegChanged := True;
  9354. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9355. TransferUsedRegs(TmpUsedRegs);
  9356. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9357. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9358. if p = hp1 then
  9359. begin
  9360. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9361. p_removed := True;
  9362. end
  9363. else
  9364. RemoveInstruction(hp1);
  9365. hp1_removed := True;
  9366. { Instruction will become "mov %reg,%reg" }
  9367. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9368. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9369. begin
  9370. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9371. RemoveCurrentP(p);
  9372. p_removed := True;
  9373. end
  9374. else
  9375. taicpu(p).oper[1]^.reg := ThisReg;
  9376. Result := True;
  9377. end
  9378. else
  9379. begin
  9380. if TargetSize <> MaxSize then
  9381. begin
  9382. { Since the register is in use, we have to force it to
  9383. MaxSize otherwise part of it may become undefined later on }
  9384. TargetSize := MaxSize;
  9385. case TargetSize of
  9386. S_B:
  9387. TargetSubReg := R_SUBL;
  9388. S_W:
  9389. TargetSubReg := R_SUBW;
  9390. S_L:
  9391. TargetSubReg := R_SUBD;
  9392. else
  9393. InternalError(2020112351);
  9394. end;
  9395. setsubreg(ThisReg, TargetSubReg);
  9396. end;
  9397. AdjustFinalLoad;
  9398. end;
  9399. end
  9400. else
  9401. AdjustFinalLoad;
  9402. Result := AdjustInitialLoadAndSize or Result;
  9403. { Now go through every instruction we found and change the
  9404. size. If TargetSize = MaxSize, then almost no changes are
  9405. needed and Result can remain False if it hasn't been set
  9406. yet.
  9407. If RegChanged is True, then the register requires changing
  9408. and so the point about TargetSize = MaxSize doesn't apply. }
  9409. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9410. begin
  9411. for LocalIndex := 0 to InstrMax do
  9412. begin
  9413. { If p_removed is true, then the original MOV/Z was removed
  9414. and removing the AND instruction may not be safe if it
  9415. appears first }
  9416. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9417. InternalError(2020112310);
  9418. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9419. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9420. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9421. InstrList[LocalIndex].opsize := TargetSize;
  9422. end;
  9423. Result := True;
  9424. end;
  9425. end;
  9426. begin
  9427. Result := False;
  9428. p_removed := False;
  9429. hp1_removed := False;
  9430. ThisReg := taicpu(p).oper[1]^.reg;
  9431. { Check for:
  9432. movs/z ###,%ecx (or %cx or %rcx)
  9433. ...
  9434. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9435. (dealloc %ecx)
  9436. Change to:
  9437. mov ###,%cl (if ### = %cl, then remove completely)
  9438. ...
  9439. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9440. }
  9441. if (getsupreg(ThisReg) = RS_ECX) and
  9442. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9443. (hp1.typ = ait_instruction) and
  9444. (
  9445. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9446. instruction that doesn't actually contain ECX }
  9447. (cs_opt_level3 in current_settings.optimizerswitches) or
  9448. RegInInstruction(NR_ECX, hp1) or
  9449. (
  9450. { It's common for the shift/rotate's read/write register to be
  9451. initialised in between, so under -O2 and under, search ahead
  9452. one more instruction
  9453. }
  9454. GetNextInstruction(hp1, hp1) and
  9455. (hp1.typ = ait_instruction) and
  9456. RegInInstruction(NR_ECX, hp1)
  9457. )
  9458. ) and
  9459. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9460. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9461. begin
  9462. TransferUsedRegs(TmpUsedRegs);
  9463. hp2 := p;
  9464. repeat
  9465. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9466. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9467. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9468. begin
  9469. case taicpu(p).opsize of
  9470. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9471. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9472. begin
  9473. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9474. RemoveCurrentP(p);
  9475. end
  9476. else
  9477. begin
  9478. taicpu(p).opcode := A_MOV;
  9479. taicpu(p).opsize := S_B;
  9480. taicpu(p).oper[1]^.reg := NR_CL;
  9481. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9482. end;
  9483. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9484. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9485. begin
  9486. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9487. RemoveCurrentP(p);
  9488. end
  9489. else
  9490. begin
  9491. taicpu(p).opcode := A_MOV;
  9492. taicpu(p).opsize := S_W;
  9493. taicpu(p).oper[1]^.reg := NR_CX;
  9494. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9495. end;
  9496. {$ifdef x86_64}
  9497. S_LQ:
  9498. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9499. begin
  9500. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9501. RemoveCurrentP(p);
  9502. end
  9503. else
  9504. begin
  9505. taicpu(p).opcode := A_MOV;
  9506. taicpu(p).opsize := S_L;
  9507. taicpu(p).oper[1]^.reg := NR_ECX;
  9508. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9509. end;
  9510. {$endif x86_64}
  9511. else
  9512. InternalError(2021120401);
  9513. end;
  9514. Result := True;
  9515. Exit;
  9516. end;
  9517. end;
  9518. { This is anything but quick! }
  9519. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9520. Exit;
  9521. SetLength(InstrList, 0);
  9522. InstrMax := -1;
  9523. case taicpu(p).opsize of
  9524. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9525. begin
  9526. {$if defined(i386) or defined(i8086)}
  9527. { If the target size is 8-bit, make sure we can actually encode it }
  9528. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9529. Exit;
  9530. {$endif i386 or i8086}
  9531. LowerLimit := $FF;
  9532. SignedLowerLimit := $7F;
  9533. SignedLowerLimitBottom := -128;
  9534. MinSize := S_B;
  9535. if taicpu(p).opsize = S_BW then
  9536. begin
  9537. MaxSize := S_W;
  9538. UpperLimit := $FFFF;
  9539. SignedUpperLimit := $7FFF;
  9540. SignedUpperLimitBottom := -32768;
  9541. end
  9542. else
  9543. begin
  9544. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9545. MaxSize := S_L;
  9546. UpperLimit := $FFFFFFFF;
  9547. SignedUpperLimit := $7FFFFFFF;
  9548. SignedUpperLimitBottom := -2147483648;
  9549. end;
  9550. end;
  9551. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9552. begin
  9553. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9554. LowerLimit := $FFFF;
  9555. SignedLowerLimit := $7FFF;
  9556. SignedLowerLimitBottom := -32768;
  9557. UpperLimit := $FFFFFFFF;
  9558. SignedUpperLimit := $7FFFFFFF;
  9559. SignedUpperLimitBottom := -2147483648;
  9560. MinSize := S_W;
  9561. MaxSize := S_L;
  9562. end;
  9563. {$ifdef x86_64}
  9564. S_LQ:
  9565. begin
  9566. { Both the lower and upper limits are set to 32-bit. If a limit
  9567. is breached, then optimisation is impossible }
  9568. LowerLimit := $FFFFFFFF;
  9569. SignedLowerLimit := $7FFFFFFF;
  9570. SignedLowerLimitBottom := -2147483648;
  9571. UpperLimit := $FFFFFFFF;
  9572. SignedUpperLimit := $7FFFFFFF;
  9573. SignedUpperLimitBottom := -2147483648;
  9574. MinSize := S_L;
  9575. MaxSize := S_L;
  9576. end;
  9577. {$endif x86_64}
  9578. else
  9579. InternalError(2020112301);
  9580. end;
  9581. TestValMin := 0;
  9582. TestValMax := LowerLimit;
  9583. TestValSignedMax := SignedLowerLimit;
  9584. TryShiftDownLimit := LowerLimit;
  9585. TryShiftDown := S_NO;
  9586. ShiftDownOverflow := False;
  9587. RegChanged := False;
  9588. BitwiseOnly := True;
  9589. OrXorUsed := False;
  9590. UpperSignedOverflow := False;
  9591. LowerSignedOverflow := False;
  9592. UpperUnsignedOverflow := False;
  9593. LowerUnsignedOverflow := False;
  9594. hp1 := p;
  9595. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9596. (hp1.typ = ait_instruction) and
  9597. (
  9598. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9599. instruction that doesn't actually contain ThisReg }
  9600. (cs_opt_level3 in current_settings.optimizerswitches) or
  9601. { This allows this Movx optimisation to work through the SETcc instructions
  9602. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9603. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9604. skip over these SETcc instructions). }
  9605. (taicpu(hp1).opcode = A_SETcc) or
  9606. RegInInstruction(ThisReg, hp1)
  9607. ) do
  9608. begin
  9609. case taicpu(hp1).opcode of
  9610. A_INC,A_DEC:
  9611. begin
  9612. { Has to be an exact match on the register }
  9613. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9614. Break;
  9615. if taicpu(hp1).opcode = A_INC then
  9616. begin
  9617. Inc(TestValMin);
  9618. Inc(TestValMax);
  9619. Inc(TestValSignedMax);
  9620. end
  9621. else
  9622. begin
  9623. Dec(TestValMin);
  9624. Dec(TestValMax);
  9625. Dec(TestValSignedMax);
  9626. end;
  9627. end;
  9628. A_TEST, A_CMP:
  9629. begin
  9630. if (
  9631. { Too high a risk of non-linear behaviour that breaks DFA
  9632. here, unless it's cmp $0,%reg, which is equivalent to
  9633. test %reg,%reg }
  9634. OrXorUsed and
  9635. (taicpu(hp1).opcode = A_CMP) and
  9636. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9637. ) or
  9638. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9639. { Has to be an exact match on the register }
  9640. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9641. (
  9642. { Permit "test %reg,%reg" }
  9643. (taicpu(hp1).opcode = A_TEST) and
  9644. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9645. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9646. ) or
  9647. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9648. { Make sure the comparison value is not smaller than the
  9649. smallest allowed signed value for the minimum size (e.g.
  9650. -128 for 8-bit) }
  9651. not (
  9652. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9653. { Is it in the negative range? }
  9654. (
  9655. (taicpu(hp1).oper[0]^.val < 0) and
  9656. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9657. )
  9658. ) then
  9659. Break;
  9660. { Check to see if the active register is used afterwards }
  9661. TransferUsedRegs(TmpUsedRegs);
  9662. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9663. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9664. begin
  9665. { Make sure the comparison or any previous instructions
  9666. hasn't pushed the test values outside of the range of
  9667. MinSize }
  9668. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9669. begin
  9670. { Exceeded lower bound but not upper bound }
  9671. Exit;
  9672. end
  9673. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9674. begin
  9675. { Size didn't exceed lower bound }
  9676. TargetSize := MinSize;
  9677. end
  9678. else
  9679. Break;
  9680. case TargetSize of
  9681. S_B:
  9682. TargetSubReg := R_SUBL;
  9683. S_W:
  9684. TargetSubReg := R_SUBW;
  9685. S_L:
  9686. TargetSubReg := R_SUBD;
  9687. else
  9688. InternalError(2021051002);
  9689. end;
  9690. if TargetSize <> MaxSize then
  9691. begin
  9692. { Update the register to its new size }
  9693. setsubreg(ThisReg, TargetSubReg);
  9694. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9695. taicpu(hp1).oper[1]^.reg := ThisReg;
  9696. taicpu(hp1).opsize := TargetSize;
  9697. { Convert the input MOVZX to a MOV if necessary }
  9698. AdjustInitialLoadAndSize;
  9699. if (InstrMax >= 0) then
  9700. begin
  9701. for Index := 0 to InstrMax do
  9702. begin
  9703. { If p_removed is true, then the original MOV/Z was removed
  9704. and removing the AND instruction may not be safe if it
  9705. appears first }
  9706. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9707. InternalError(2020112311);
  9708. if InstrList[Index].oper[0]^.typ = top_reg then
  9709. InstrList[Index].oper[0]^.reg := ThisReg;
  9710. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9711. InstrList[Index].opsize := MinSize;
  9712. end;
  9713. end;
  9714. Result := True;
  9715. end;
  9716. Exit;
  9717. end;
  9718. end;
  9719. A_SETcc:
  9720. begin
  9721. { This allows this Movx optimisation to work through the SETcc instructions
  9722. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9723. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9724. skip over these SETcc instructions). }
  9725. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9726. { Of course, break out if the current register is used }
  9727. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9728. Break
  9729. else
  9730. { We must use Continue so the instruction doesn't get added
  9731. to InstrList }
  9732. Continue;
  9733. end;
  9734. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9735. begin
  9736. if
  9737. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9738. { Has to be an exact match on the register }
  9739. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9740. (
  9741. (
  9742. (taicpu(hp1).oper[0]^.typ = top_const) and
  9743. (
  9744. (
  9745. (taicpu(hp1).opcode = A_SHL) and
  9746. (
  9747. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9748. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9749. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9750. )
  9751. ) or (
  9752. (taicpu(hp1).opcode <> A_SHL) and
  9753. (
  9754. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9755. { Is it in the negative range? }
  9756. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9757. )
  9758. )
  9759. )
  9760. ) or (
  9761. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9762. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9763. )
  9764. ) then
  9765. Break;
  9766. { Only process OR and XOR if there are only bitwise operations,
  9767. since otherwise they can too easily fool the data flow
  9768. analysis (they can cause non-linear behaviour) }
  9769. case taicpu(hp1).opcode of
  9770. A_ADD:
  9771. begin
  9772. if OrXorUsed then
  9773. { Too high a risk of non-linear behaviour that breaks DFA here }
  9774. Break
  9775. else
  9776. BitwiseOnly := False;
  9777. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9778. begin
  9779. TestValMin := TestValMin * 2;
  9780. TestValMax := TestValMax * 2;
  9781. TestValSignedMax := TestValSignedMax * 2;
  9782. end
  9783. else
  9784. begin
  9785. WorkingValue := taicpu(hp1).oper[0]^.val;
  9786. TestValMin := TestValMin + WorkingValue;
  9787. TestValMax := TestValMax + WorkingValue;
  9788. TestValSignedMax := TestValSignedMax + WorkingValue;
  9789. end;
  9790. end;
  9791. A_SUB:
  9792. begin
  9793. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9794. begin
  9795. TestValMin := 0;
  9796. TestValMax := 0;
  9797. TestValSignedMax := 0;
  9798. end
  9799. else
  9800. begin
  9801. if OrXorUsed then
  9802. { Too high a risk of non-linear behaviour that breaks DFA here }
  9803. Break
  9804. else
  9805. BitwiseOnly := False;
  9806. WorkingValue := taicpu(hp1).oper[0]^.val;
  9807. TestValMin := TestValMin - WorkingValue;
  9808. TestValMax := TestValMax - WorkingValue;
  9809. TestValSignedMax := TestValSignedMax - WorkingValue;
  9810. end;
  9811. end;
  9812. A_AND:
  9813. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9814. begin
  9815. { we might be able to go smaller if AND appears first }
  9816. if InstrMax = -1 then
  9817. case MinSize of
  9818. S_B:
  9819. ;
  9820. S_W:
  9821. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9822. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9823. begin
  9824. TryShiftDown := S_B;
  9825. TryShiftDownLimit := $FF;
  9826. end;
  9827. S_L:
  9828. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9829. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9830. begin
  9831. TryShiftDown := S_B;
  9832. TryShiftDownLimit := $FF;
  9833. end
  9834. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9835. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9836. begin
  9837. TryShiftDown := S_W;
  9838. TryShiftDownLimit := $FFFF;
  9839. end;
  9840. else
  9841. InternalError(2020112320);
  9842. end;
  9843. WorkingValue := taicpu(hp1).oper[0]^.val;
  9844. TestValMin := TestValMin and WorkingValue;
  9845. TestValMax := TestValMax and WorkingValue;
  9846. TestValSignedMax := TestValSignedMax and WorkingValue;
  9847. end;
  9848. A_OR:
  9849. begin
  9850. if not BitwiseOnly then
  9851. Break;
  9852. OrXorUsed := True;
  9853. WorkingValue := taicpu(hp1).oper[0]^.val;
  9854. TestValMin := TestValMin or WorkingValue;
  9855. TestValMax := TestValMax or WorkingValue;
  9856. TestValSignedMax := TestValSignedMax or WorkingValue;
  9857. end;
  9858. A_XOR:
  9859. begin
  9860. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9861. begin
  9862. TestValMin := 0;
  9863. TestValMax := 0;
  9864. TestValSignedMax := 0;
  9865. end
  9866. else
  9867. begin
  9868. if not BitwiseOnly then
  9869. Break;
  9870. OrXorUsed := True;
  9871. WorkingValue := taicpu(hp1).oper[0]^.val;
  9872. TestValMin := TestValMin xor WorkingValue;
  9873. TestValMax := TestValMax xor WorkingValue;
  9874. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9875. end;
  9876. end;
  9877. A_SHL:
  9878. begin
  9879. BitwiseOnly := False;
  9880. WorkingValue := taicpu(hp1).oper[0]^.val;
  9881. TestValMin := TestValMin shl WorkingValue;
  9882. TestValMax := TestValMax shl WorkingValue;
  9883. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9884. end;
  9885. A_SHR,
  9886. { The first instruction was MOVZX, so the value won't be negative }
  9887. A_SAR:
  9888. begin
  9889. if InstrMax <> -1 then
  9890. BitwiseOnly := False
  9891. else
  9892. { we might be able to go smaller if SHR appears first }
  9893. case MinSize of
  9894. S_B:
  9895. ;
  9896. S_W:
  9897. if (taicpu(hp1).oper[0]^.val >= 8) then
  9898. begin
  9899. TryShiftDown := S_B;
  9900. TryShiftDownLimit := $FF;
  9901. TryShiftDownSignedLimit := $7F;
  9902. TryShiftDownSignedLimitLower := -128;
  9903. end;
  9904. S_L:
  9905. if (taicpu(hp1).oper[0]^.val >= 24) then
  9906. begin
  9907. TryShiftDown := S_B;
  9908. TryShiftDownLimit := $FF;
  9909. TryShiftDownSignedLimit := $7F;
  9910. TryShiftDownSignedLimitLower := -128;
  9911. end
  9912. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9913. begin
  9914. TryShiftDown := S_W;
  9915. TryShiftDownLimit := $FFFF;
  9916. TryShiftDownSignedLimit := $7FFF;
  9917. TryShiftDownSignedLimitLower := -32768;
  9918. end;
  9919. else
  9920. InternalError(2020112321);
  9921. end;
  9922. WorkingValue := taicpu(hp1).oper[0]^.val;
  9923. if taicpu(hp1).opcode = A_SAR then
  9924. begin
  9925. TestValMin := SarInt64(TestValMin, WorkingValue);
  9926. TestValMax := SarInt64(TestValMax, WorkingValue);
  9927. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9928. end
  9929. else
  9930. begin
  9931. TestValMin := TestValMin shr WorkingValue;
  9932. TestValMax := TestValMax shr WorkingValue;
  9933. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9934. end;
  9935. end;
  9936. else
  9937. InternalError(2020112303);
  9938. end;
  9939. end;
  9940. (*
  9941. A_IMUL:
  9942. case taicpu(hp1).ops of
  9943. 2:
  9944. begin
  9945. if not MatchOpType(hp1, top_reg, top_reg) or
  9946. { Has to be an exact match on the register }
  9947. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9948. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9949. Break;
  9950. TestValMin := TestValMin * TestValMin;
  9951. TestValMax := TestValMax * TestValMax;
  9952. TestValSignedMax := TestValSignedMax * TestValMax;
  9953. end;
  9954. 3:
  9955. begin
  9956. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9957. { Has to be an exact match on the register }
  9958. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9959. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9960. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9961. { Is it in the negative range? }
  9962. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9963. Break;
  9964. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9965. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9966. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9967. end;
  9968. else
  9969. Break;
  9970. end;
  9971. A_IDIV:
  9972. case taicpu(hp1).ops of
  9973. 3:
  9974. begin
  9975. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9976. { Has to be an exact match on the register }
  9977. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9978. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9979. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9980. { Is it in the negative range? }
  9981. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9982. Break;
  9983. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9984. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9985. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9986. end;
  9987. else
  9988. Break;
  9989. end;
  9990. *)
  9991. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9992. begin
  9993. { If there are no instructions in between, then we might be able to make a saving }
  9994. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9995. Break;
  9996. { We have something like:
  9997. movzbw %dl,%dx
  9998. ...
  9999. movswl %dx,%edx
  10000. Change the latter to a zero-extension then enter the
  10001. A_MOVZX case branch.
  10002. }
  10003. {$ifdef x86_64}
  10004. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10005. begin
  10006. { this becomes a zero extension from 32-bit to 64-bit, but
  10007. the upper 32 bits are already zero, so just delete the
  10008. instruction }
  10009. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  10010. RemoveInstruction(hp1);
  10011. Result := True;
  10012. Exit;
  10013. end
  10014. else
  10015. {$endif x86_64}
  10016. begin
  10017. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  10018. taicpu(hp1).opcode := A_MOVZX;
  10019. {$ifdef x86_64}
  10020. case taicpu(hp1).opsize of
  10021. S_BQ:
  10022. begin
  10023. taicpu(hp1).opsize := S_BL;
  10024. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10025. end;
  10026. S_WQ:
  10027. begin
  10028. taicpu(hp1).opsize := S_WL;
  10029. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10030. end;
  10031. S_LQ:
  10032. begin
  10033. taicpu(hp1).opcode := A_MOV;
  10034. taicpu(hp1).opsize := S_L;
  10035. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10036. { In this instance, we need to break out because the
  10037. instruction is no longer MOVZX or MOVSXD }
  10038. Result := True;
  10039. Exit;
  10040. end;
  10041. else
  10042. ;
  10043. end;
  10044. {$endif x86_64}
  10045. Result := CompressInstructions;
  10046. Exit;
  10047. end;
  10048. end;
  10049. A_MOVZX:
  10050. begin
  10051. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  10052. Break;
  10053. if (InstrMax = -1) then
  10054. begin
  10055. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  10056. begin
  10057. { Optimise around i40003 }
  10058. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  10059. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  10060. {$ifndef x86_64}
  10061. and (
  10062. (taicpu(p).oper[0]^.typ <> top_reg) or
  10063. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  10064. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  10065. )
  10066. {$endif not x86_64}
  10067. then
  10068. begin
  10069. if (taicpu(p).oper[0]^.typ = top_reg) then
  10070. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  10071. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  10072. taicpu(p).opsize := S_BL;
  10073. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  10074. RemoveInstruction(hp1);
  10075. Result := True;
  10076. Exit;
  10077. end;
  10078. end
  10079. else
  10080. begin
  10081. { Will return false if the second parameter isn't ThisReg
  10082. (can happen on -O2 and under) }
  10083. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10084. begin
  10085. { The two MOVZX instructions are adjacent, so remove the first one }
  10086. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  10087. RemoveCurrentP(p);
  10088. Result := True;
  10089. Exit;
  10090. end;
  10091. Break;
  10092. end;
  10093. end;
  10094. Result := CompressInstructions;
  10095. Exit;
  10096. end;
  10097. else
  10098. { This includes ADC, SBB and IDIV }
  10099. Break;
  10100. end;
  10101. if not CheckOverflowConditions then
  10102. Break;
  10103. { Contains highest index (so instruction count - 1) }
  10104. Inc(InstrMax);
  10105. if InstrMax > High(InstrList) then
  10106. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10107. InstrList[InstrMax] := taicpu(hp1);
  10108. end;
  10109. end;
  10110. {$pop}
  10111. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  10112. var
  10113. hp1 : tai;
  10114. begin
  10115. Result:=false;
  10116. if (taicpu(p).ops >= 2) and
  10117. ((taicpu(p).oper[0]^.typ = top_const) or
  10118. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  10119. (taicpu(p).oper[1]^.typ = top_reg) and
  10120. ((taicpu(p).ops = 2) or
  10121. ((taicpu(p).oper[2]^.typ = top_reg) and
  10122. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  10123. GetLastInstruction(p,hp1) and
  10124. MatchInstruction(hp1,A_MOV,[]) and
  10125. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10126. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10127. begin
  10128. TransferUsedRegs(TmpUsedRegs);
  10129. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  10130. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  10131. { change
  10132. mov reg1,reg2
  10133. imul y,reg2 to imul y,reg1,reg2 }
  10134. begin
  10135. taicpu(p).ops := 3;
  10136. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  10137. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  10138. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  10139. RemoveInstruction(hp1);
  10140. result:=true;
  10141. end;
  10142. end;
  10143. end;
  10144. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  10145. var
  10146. ThisLabel: TAsmLabel;
  10147. begin
  10148. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  10149. ThisLabel.decrefs;
  10150. taicpu(p).condition := C_None;
  10151. taicpu(p).opcode := A_RET;
  10152. taicpu(p).is_jmp := false;
  10153. taicpu(p).ops := taicpu(ret_p).ops;
  10154. case taicpu(ret_p).ops of
  10155. 0:
  10156. taicpu(p).clearop(0);
  10157. 1:
  10158. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  10159. else
  10160. internalerror(2016041301);
  10161. end;
  10162. { If the original label is now dead, it might turn out that the label
  10163. immediately follows p. As a result, everything beyond it, which will
  10164. be just some final register configuration and a RET instruction, is
  10165. now dead code. [Kit] }
  10166. { NOTE: This is much faster than introducing a OptPass2RET routine and
  10167. running RemoveDeadCodeAfterJump for each RET instruction, because
  10168. this optimisation rarely happens and most RETs appear at the end of
  10169. routines where there is nothing that can be stripped. [Kit] }
  10170. if not ThisLabel.is_used then
  10171. RemoveDeadCodeAfterJump(p);
  10172. end;
  10173. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  10174. var
  10175. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  10176. Unconditional, PotentialModified: Boolean;
  10177. OperPtr: POper;
  10178. NewRef: TReference;
  10179. InstrList: array of taicpu;
  10180. InstrMax, Index: Integer;
  10181. const
  10182. {$ifdef DEBUG_AOPTCPU}
  10183. SNoFlags: shortstring = ' so the flags aren''t modified';
  10184. {$else DEBUG_AOPTCPU}
  10185. SNoFlags = '';
  10186. {$endif DEBUG_AOPTCPU}
  10187. begin
  10188. Result:=false;
  10189. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10190. begin
  10191. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10192. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10193. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10194. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10195. GetNextInstruction(hp1, hp2) and
  10196. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10197. { Change from: To:
  10198. set(C) %reg j(~C) label
  10199. test %reg,%reg/cmp $0,%reg
  10200. je label
  10201. set(C) %reg j(C) label
  10202. test %reg,%reg/cmp $0,%reg
  10203. jne label
  10204. (Also do something similar with sete/setne instead of je/jne)
  10205. }
  10206. begin
  10207. { Before we do anything else, we need to check the instructions
  10208. in between SETcc and TEST to make sure they don't modify the
  10209. FLAGS register - if -O2 or under, there won't be any
  10210. instructions between SET and TEST }
  10211. TransferUsedRegs(TmpUsedRegs);
  10212. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10213. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10214. begin
  10215. next := p;
  10216. SetLength(InstrList, 0);
  10217. InstrMax := -1;
  10218. PotentialModified := False;
  10219. { Make a note of every instruction that modifies the FLAGS
  10220. register }
  10221. while GetNextInstruction(next, next) and (next <> hp1) do
  10222. begin
  10223. if next.typ <> ait_instruction then
  10224. { GetNextInstructionUsingReg should have returned False }
  10225. InternalError(2021051701);
  10226. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10227. begin
  10228. case taicpu(next).opcode of
  10229. A_SETcc,
  10230. A_CMOVcc,
  10231. A_Jcc:
  10232. begin
  10233. if PotentialModified then
  10234. { Not safe because the flags were modified earlier }
  10235. Exit
  10236. else
  10237. { Condition is the same as the initial SETcc, so this is safe
  10238. (don't add to instruction list though) }
  10239. Continue;
  10240. end;
  10241. A_ADD:
  10242. begin
  10243. if (taicpu(next).opsize = S_B) or
  10244. { LEA doesn't support 8-bit operands }
  10245. (taicpu(next).oper[1]^.typ <> top_reg) or
  10246. { Must write to a register }
  10247. (taicpu(next).oper[0]^.typ = top_ref) then
  10248. { Require a constant or a register }
  10249. Exit;
  10250. PotentialModified := True;
  10251. end;
  10252. A_SUB:
  10253. begin
  10254. if (taicpu(next).opsize = S_B) or
  10255. { LEA doesn't support 8-bit operands }
  10256. (taicpu(next).oper[1]^.typ <> top_reg) or
  10257. { Must write to a register }
  10258. (taicpu(next).oper[0]^.typ <> top_const) or
  10259. (taicpu(next).oper[0]^.val = $80000000) then
  10260. { Can't subtract a register with LEA - also
  10261. check that the value isn't -2^31, as this
  10262. can't be negated }
  10263. Exit;
  10264. PotentialModified := True;
  10265. end;
  10266. A_SAL,
  10267. A_SHL:
  10268. begin
  10269. if (taicpu(next).opsize = S_B) or
  10270. { LEA doesn't support 8-bit operands }
  10271. (taicpu(next).oper[1]^.typ <> top_reg) or
  10272. { Must write to a register }
  10273. (taicpu(next).oper[0]^.typ <> top_const) or
  10274. (taicpu(next).oper[0]^.val < 0) or
  10275. (taicpu(next).oper[0]^.val > 3) then
  10276. Exit;
  10277. PotentialModified := True;
  10278. end;
  10279. A_IMUL:
  10280. begin
  10281. if (taicpu(next).ops <> 3) or
  10282. (taicpu(next).oper[1]^.typ <> top_reg) or
  10283. { Must write to a register }
  10284. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10285. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10286. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10287. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10288. Exit
  10289. else
  10290. PotentialModified := True;
  10291. end;
  10292. else
  10293. { Don't know how to change this, so abort }
  10294. Exit;
  10295. end;
  10296. { Contains highest index (so instruction count - 1) }
  10297. Inc(InstrMax);
  10298. if InstrMax > High(InstrList) then
  10299. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10300. InstrList[InstrMax] := taicpu(next);
  10301. end;
  10302. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10303. end;
  10304. if not Assigned(next) or (next <> hp1) then
  10305. { It should be equal to hp1 }
  10306. InternalError(2021051702);
  10307. { Cycle through each instruction and check to see if we can
  10308. change them to versions that don't modify the flags }
  10309. if (InstrMax >= 0) then
  10310. begin
  10311. for Index := 0 to InstrMax do
  10312. case InstrList[Index].opcode of
  10313. A_ADD:
  10314. begin
  10315. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10316. InstrList[Index].opcode := A_LEA;
  10317. reference_reset(NewRef, 1, []);
  10318. NewRef.base := InstrList[Index].oper[1]^.reg;
  10319. if InstrList[Index].oper[0]^.typ = top_reg then
  10320. begin
  10321. NewRef.index := InstrList[Index].oper[0]^.reg;
  10322. NewRef.scalefactor := 1;
  10323. end
  10324. else
  10325. NewRef.offset := InstrList[Index].oper[0]^.val;
  10326. InstrList[Index].loadref(0, NewRef);
  10327. end;
  10328. A_SUB:
  10329. begin
  10330. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10331. InstrList[Index].opcode := A_LEA;
  10332. reference_reset(NewRef, 1, []);
  10333. NewRef.base := InstrList[Index].oper[1]^.reg;
  10334. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10335. InstrList[Index].loadref(0, NewRef);
  10336. end;
  10337. A_SHL,
  10338. A_SAL:
  10339. begin
  10340. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10341. InstrList[Index].opcode := A_LEA;
  10342. reference_reset(NewRef, 1, []);
  10343. NewRef.index := InstrList[Index].oper[1]^.reg;
  10344. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10345. InstrList[Index].loadref(0, NewRef);
  10346. end;
  10347. A_IMUL:
  10348. begin
  10349. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10350. InstrList[Index].opcode := A_LEA;
  10351. reference_reset(NewRef, 1, []);
  10352. NewRef.index := InstrList[Index].oper[1]^.reg;
  10353. case InstrList[Index].oper[0]^.val of
  10354. 2, 4, 8:
  10355. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10356. else {3, 5 and 9}
  10357. begin
  10358. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10359. NewRef.base := InstrList[Index].oper[1]^.reg;
  10360. end;
  10361. end;
  10362. InstrList[Index].loadref(0, NewRef);
  10363. end;
  10364. else
  10365. InternalError(2021051710);
  10366. end;
  10367. end;
  10368. { Mark the FLAGS register as used across this whole block }
  10369. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10370. end;
  10371. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10372. JumpC := taicpu(hp2).condition;
  10373. Unconditional := False;
  10374. if conditions_equal(JumpC, C_E) then
  10375. SetC := inverse_cond(taicpu(p).condition)
  10376. else if conditions_equal(JumpC, C_NE) then
  10377. SetC := taicpu(p).condition
  10378. else
  10379. { We've got something weird here (and inefficent) }
  10380. begin
  10381. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10382. SetC := C_NONE;
  10383. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10384. if condition_in(C_AE, JumpC) then
  10385. Unconditional := True
  10386. else
  10387. { Not sure what to do with this jump - drop out }
  10388. Exit;
  10389. end;
  10390. RemoveInstruction(hp1);
  10391. if Unconditional then
  10392. MakeUnconditional(taicpu(hp2))
  10393. else
  10394. begin
  10395. if SetC = C_NONE then
  10396. InternalError(2018061402);
  10397. taicpu(hp2).SetCondition(SetC);
  10398. end;
  10399. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10400. TmpUsedRegs }
  10401. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10402. begin
  10403. RemoveCurrentp(p, hp2);
  10404. if taicpu(hp2).opcode = A_SETcc then
  10405. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10406. else
  10407. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10408. end
  10409. else
  10410. if taicpu(hp2).opcode = A_SETcc then
  10411. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10412. else
  10413. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10414. Result := True;
  10415. end
  10416. else if
  10417. { Make sure the instructions are adjacent }
  10418. (
  10419. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10420. GetNextInstruction(p, hp1)
  10421. ) and
  10422. MatchInstruction(hp1, A_MOV, [S_B]) and
  10423. { Writing to memory is allowed }
  10424. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10425. begin
  10426. {
  10427. Watch out for sequences such as:
  10428. set(c)b %regb
  10429. movb %regb,(ref)
  10430. movb $0,1(ref)
  10431. movb $0,2(ref)
  10432. movb $0,3(ref)
  10433. Much more efficient to turn it into:
  10434. movl $0,%regl
  10435. set(c)b %regb
  10436. movl %regl,(ref)
  10437. Or:
  10438. set(c)b %regb
  10439. movzbl %regb,%regl
  10440. movl %regl,(ref)
  10441. }
  10442. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10443. GetNextInstruction(hp1, hp2) and
  10444. MatchInstruction(hp2, A_MOV, [S_B]) and
  10445. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10446. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10447. begin
  10448. { Don't do anything else except set Result to True }
  10449. end
  10450. else
  10451. begin
  10452. if taicpu(p).oper[0]^.typ = top_reg then
  10453. begin
  10454. TransferUsedRegs(TmpUsedRegs);
  10455. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10456. end;
  10457. { If it's not a register, it's a memory address }
  10458. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10459. begin
  10460. { Even if the register is still in use, we can minimise the
  10461. pipeline stall by changing the MOV into another SETcc. }
  10462. taicpu(hp1).opcode := A_SETcc;
  10463. taicpu(hp1).condition := taicpu(p).condition;
  10464. if taicpu(hp1).oper[1]^.typ = top_ref then
  10465. begin
  10466. { Swapping the operand pointers like this is probably a
  10467. bit naughty, but it is far faster than using loadoper
  10468. to transfer the reference from oper[1] to oper[0] if
  10469. you take into account the extra procedure calls and
  10470. the memory allocation and deallocation required }
  10471. OperPtr := taicpu(hp1).oper[1];
  10472. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10473. taicpu(hp1).oper[0] := OperPtr;
  10474. end
  10475. else
  10476. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10477. taicpu(hp1).clearop(1);
  10478. taicpu(hp1).ops := 1;
  10479. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10480. end
  10481. else
  10482. begin
  10483. if taicpu(hp1).oper[1]^.typ = top_reg then
  10484. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10485. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10486. RemoveInstruction(hp1);
  10487. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10488. end
  10489. end;
  10490. Result := True;
  10491. end;
  10492. end;
  10493. end;
  10494. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10495. var
  10496. hp1: tai;
  10497. Count: Integer;
  10498. OrigLabel: TAsmLabel;
  10499. begin
  10500. result := False;
  10501. { Sometimes, the optimisations below can permit this }
  10502. RemoveDeadCodeAfterJump(p);
  10503. 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
  10504. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10505. begin
  10506. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10507. { Also a side-effect of optimisations }
  10508. if CollapseZeroDistJump(p, OrigLabel) then
  10509. begin
  10510. Result := True;
  10511. Exit;
  10512. end;
  10513. hp1 := GetLabelWithSym(OrigLabel);
  10514. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10515. begin
  10516. if taicpu(hp1).opcode = A_RET then
  10517. begin
  10518. {
  10519. change
  10520. jmp .L1
  10521. ...
  10522. .L1:
  10523. ret
  10524. into
  10525. ret
  10526. }
  10527. begin
  10528. ConvertJumpToRET(p, hp1);
  10529. result:=true;
  10530. end;
  10531. end
  10532. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10533. not (cs_opt_size in current_settings.optimizerswitches) and
  10534. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10535. begin
  10536. Result := True;
  10537. Exit;
  10538. end;
  10539. end;
  10540. end;
  10541. end;
  10542. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  10543. begin
  10544. Result := assigned(p) and
  10545. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10546. (taicpu(p).oper[1]^.typ = top_reg) and
  10547. (
  10548. (taicpu(p).oper[0]^.typ = top_reg) or
  10549. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10550. it is not expected that this can cause a seg. violation }
  10551. (
  10552. (taicpu(p).oper[0]^.typ = top_ref) and
  10553. { TODO: Can we detect which references become constants at this
  10554. stage so we don't have to do a blanket ban? }
  10555. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10556. (
  10557. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10558. (
  10559. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  10560. not RefModified and
  10561. { If the reference also appears in the condition, then we know it's safe, otherwise
  10562. any kind of access violation would have occurred already }
  10563. Assigned(cond_p) and
  10564. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10565. (cond_p.typ = ait_instruction) and
  10566. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10567. { Just consider 2-operand comparison instructions for now to be safe }
  10568. (taicpu(cond_p).ops = 2) and
  10569. (
  10570. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10571. (
  10572. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10573. { Don't risk identical registers but different offsets, as we may have constructs
  10574. such as buffer streams with things like length fields that indicate whether
  10575. any more data follows. And there are probably some contrived examples where
  10576. writing to offsets behind the one being read also lead to access violations }
  10577. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10578. (
  10579. { Check that we're not modifying a register that appears in the reference }
  10580. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10581. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10582. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10583. )
  10584. )
  10585. )
  10586. )
  10587. )
  10588. )
  10589. );
  10590. end;
  10591. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10592. begin
  10593. { Update integer registers, ignoring deallocations }
  10594. repeat
  10595. while assigned(p) and
  10596. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10597. (p.typ = ait_label) or
  10598. ((p.typ = ait_marker) and
  10599. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10600. p := tai(p.next);
  10601. while assigned(p) and
  10602. (p.typ=ait_RegAlloc) Do
  10603. begin
  10604. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10605. begin
  10606. case tai_regalloc(p).ratype of
  10607. ra_alloc :
  10608. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10609. else
  10610. ;
  10611. end;
  10612. end;
  10613. p := tai(p.next);
  10614. end;
  10615. until not(assigned(p)) or
  10616. (not(p.typ in SkipInstr) and
  10617. not((p.typ = ait_label) and
  10618. labelCanBeSkipped(tai_label(p))));
  10619. end;
  10620. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10621. var
  10622. hp1,hp2: tai;
  10623. carryadd_opcode : TAsmOp;
  10624. symbol: TAsmSymbol;
  10625. increg, tmpreg: TRegister;
  10626. RefModified: Boolean;
  10627. {$ifndef i8086}
  10628. { Code and variables specific to CMOV optimisations }
  10629. hp3,hp4,hp5,
  10630. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10631. l, c, w, x : Longint;
  10632. condition, second_condition : TAsmCond;
  10633. FoundMatchingJump, RegMatch: Boolean;
  10634. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10635. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10636. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10637. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  10638. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  10639. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  10640. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10641. new register to store the constant }
  10642. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10643. var
  10644. RegSize: TSubRegister;
  10645. CurrentVal: TCGInt;
  10646. ANewReg: TRegister;
  10647. X: ShortInt;
  10648. begin
  10649. Result := False;
  10650. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10651. Exit;
  10652. if StoredCount >= MAX_CMOV_REGISTERS then
  10653. { Arrays are full }
  10654. Exit;
  10655. { Remember that CMOV can't encode 8-bit registers }
  10656. case taicpu(p).opsize of
  10657. S_W:
  10658. RegSize := R_SUBW;
  10659. S_L:
  10660. RegSize := R_SUBD;
  10661. {$ifdef x86_64}
  10662. S_Q:
  10663. RegSize := R_SUBQ;
  10664. {$endif x86_64}
  10665. else
  10666. InternalError(2021100401);
  10667. end;
  10668. { See if the value has already been reserved for another CMOV instruction }
  10669. CurrentVal := taicpu(p).oper[0]^.val;
  10670. for X := 0 to StoredCount - 1 do
  10671. if ConstVals[X] = CurrentVal then
  10672. begin
  10673. ConstRegs[StoredCount] := ConstRegs[X];
  10674. ConstSizes[StoredCount] := RegSize;
  10675. ConstVals[StoredCount] := CurrentVal;
  10676. Result := True;
  10677. Inc(StoredCount);
  10678. { Don't increase CMOVCount this time, since we're re-using a register }
  10679. Exit;
  10680. end;
  10681. ANewReg := GetIntRegisterBetween(R_SUBWHOLE, TmpUsedRegs, search_start_p, stop_search_p, True);
  10682. if ANewReg = NR_NO then
  10683. { No free registers }
  10684. Exit;
  10685. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10686. up vying for the same register }
  10687. IncludeRegInUsedRegs(ANewReg, TmpUsedRegs);
  10688. ConstRegs[StoredCount] := ANewReg;
  10689. ConstSizes[StoredCount] := RegSize;
  10690. ConstVals[StoredCount] := CurrentVal;
  10691. Inc(StoredCount);
  10692. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10693. MOV required adds complexity and will cause diminishing returns
  10694. sooner than normal. This is more of an approximate weighting than
  10695. anything else. }
  10696. Inc(CMOVCount);
  10697. Result := True;
  10698. end;
  10699. {$endif i8086}
  10700. begin
  10701. result:=false;
  10702. if GetNextInstruction(p,hp1) then
  10703. begin
  10704. if (hp1.typ=ait_label) then
  10705. begin
  10706. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10707. Exit;
  10708. end
  10709. else if (hp1.typ<>ait_instruction) then
  10710. Exit;
  10711. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10712. if (
  10713. (
  10714. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10715. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10716. (Taicpu(hp1).oper[0]^.val=1)
  10717. ) or
  10718. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10719. ) and
  10720. GetNextInstruction(hp1,hp2) and
  10721. SkipAligns(hp2, hp2) and
  10722. (hp2.typ = ait_label) and
  10723. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10724. { jb @@1 cmc
  10725. inc/dec operand --> adc/sbb operand,0
  10726. @@1:
  10727. ... and ...
  10728. jnb @@1
  10729. inc/dec operand --> adc/sbb operand,0
  10730. @@1: }
  10731. begin
  10732. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10733. begin
  10734. case taicpu(hp1).opcode of
  10735. A_INC,
  10736. A_ADD:
  10737. carryadd_opcode:=A_ADC;
  10738. A_DEC,
  10739. A_SUB:
  10740. carryadd_opcode:=A_SBB;
  10741. else
  10742. InternalError(2021011001);
  10743. end;
  10744. Taicpu(p).clearop(0);
  10745. Taicpu(p).ops:=0;
  10746. Taicpu(p).is_jmp:=false;
  10747. Taicpu(p).opcode:=A_CMC;
  10748. Taicpu(p).condition:=C_NONE;
  10749. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10750. Taicpu(hp1).ops:=2;
  10751. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10752. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10753. else
  10754. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10755. Taicpu(hp1).loadconst(0,0);
  10756. Taicpu(hp1).opcode:=carryadd_opcode;
  10757. result:=true;
  10758. exit;
  10759. end
  10760. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10761. begin
  10762. case taicpu(hp1).opcode of
  10763. A_INC,
  10764. A_ADD:
  10765. carryadd_opcode:=A_ADC;
  10766. A_DEC,
  10767. A_SUB:
  10768. carryadd_opcode:=A_SBB;
  10769. else
  10770. InternalError(2021011002);
  10771. end;
  10772. Taicpu(hp1).ops:=2;
  10773. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10774. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10775. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10776. else
  10777. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10778. Taicpu(hp1).loadconst(0,0);
  10779. Taicpu(hp1).opcode:=carryadd_opcode;
  10780. RemoveCurrentP(p, hp1);
  10781. result:=true;
  10782. exit;
  10783. end
  10784. {
  10785. jcc @@1 setcc tmpreg
  10786. inc/dec/add/sub operand -> (movzx tmpreg)
  10787. @@1: add/sub tmpreg,operand
  10788. While this increases code size slightly, it makes the code much faster if the
  10789. jump is unpredictable
  10790. }
  10791. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10792. begin
  10793. { search for an available register which is volatile }
  10794. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10795. if increg <> NR_NO then
  10796. begin
  10797. { We don't need to check if tmpreg is in hp1 or not, because
  10798. it will be marked as in use at p (if not, this is
  10799. indictive of a compiler bug). }
  10800. TAsmLabel(symbol).decrefs;
  10801. Taicpu(p).clearop(0);
  10802. Taicpu(p).ops:=1;
  10803. Taicpu(p).is_jmp:=false;
  10804. Taicpu(p).opcode:=A_SETcc;
  10805. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10806. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10807. Taicpu(p).loadreg(0,increg);
  10808. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10809. begin
  10810. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10811. R_SUBW:
  10812. begin
  10813. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10814. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10815. end;
  10816. R_SUBD:
  10817. begin
  10818. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10819. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10820. end;
  10821. {$ifdef x86_64}
  10822. R_SUBQ:
  10823. begin
  10824. { MOVZX doesn't have a 64-bit variant, because
  10825. the 32-bit version implicitly zeroes the
  10826. upper 32-bits of the destination register }
  10827. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10828. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10829. setsubreg(tmpreg, R_SUBQ);
  10830. end;
  10831. {$endif x86_64}
  10832. else
  10833. Internalerror(2020030601);
  10834. end;
  10835. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10836. asml.InsertAfter(hp2,p);
  10837. end
  10838. else
  10839. tmpreg := increg;
  10840. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10841. begin
  10842. Taicpu(hp1).ops:=2;
  10843. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10844. end;
  10845. Taicpu(hp1).loadreg(0,tmpreg);
  10846. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10847. Result := True;
  10848. { p is no longer a Jcc instruction, so exit }
  10849. Exit;
  10850. end;
  10851. end;
  10852. end;
  10853. { Detect the following:
  10854. jmp<cond> @Lbl1
  10855. jmp @Lbl2
  10856. ...
  10857. @Lbl1:
  10858. ret
  10859. Change to:
  10860. jmp<inv_cond> @Lbl2
  10861. ret
  10862. }
  10863. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10864. begin
  10865. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10866. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10867. MatchInstruction(hp2,A_RET,[S_NO]) then
  10868. begin
  10869. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10870. { Change label address to that of the unconditional jump }
  10871. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10872. TAsmLabel(symbol).DecRefs;
  10873. taicpu(hp1).opcode := A_RET;
  10874. taicpu(hp1).is_jmp := false;
  10875. taicpu(hp1).ops := taicpu(hp2).ops;
  10876. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10877. case taicpu(hp2).ops of
  10878. 0:
  10879. taicpu(hp1).clearop(0);
  10880. 1:
  10881. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10882. else
  10883. internalerror(2016041302);
  10884. end;
  10885. end;
  10886. {$ifndef i8086}
  10887. end
  10888. {
  10889. convert
  10890. j<c> .L1
  10891. mov 1,reg
  10892. jmp .L2
  10893. .L1
  10894. mov 0,reg
  10895. .L2
  10896. into
  10897. mov 0,reg
  10898. set<not(c)> reg
  10899. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10900. would destroy the flag contents
  10901. }
  10902. else if MatchInstruction(hp1,A_MOV,[]) and
  10903. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10904. {$ifdef i386}
  10905. (
  10906. { Under i386, ESI, EDI, EBP and ESP
  10907. don't have an 8-bit representation }
  10908. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10909. ) and
  10910. {$endif i386}
  10911. (taicpu(hp1).oper[0]^.val=1) and
  10912. GetNextInstruction(hp1,hp2) and
  10913. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10914. GetNextInstruction(hp2,hp3) and
  10915. { skip align }
  10916. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10917. (hp3.typ=ait_label) and
  10918. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10919. (tai_label(hp3).labsym.getrefs=1) and
  10920. GetNextInstruction(hp3,hp4) and
  10921. MatchInstruction(hp4,A_MOV,[]) and
  10922. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10923. (taicpu(hp4).oper[0]^.val=0) and
  10924. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10925. GetNextInstruction(hp4,hp5) and
  10926. (hp5.typ=ait_label) and
  10927. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10928. (tai_label(hp5).labsym.getrefs=1) then
  10929. begin
  10930. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10931. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10932. { remove last label }
  10933. RemoveInstruction(hp5);
  10934. { remove second label }
  10935. RemoveInstruction(hp3);
  10936. { if align is present remove it }
  10937. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10938. RemoveInstruction(hp3);
  10939. { remove jmp }
  10940. RemoveInstruction(hp2);
  10941. if taicpu(hp1).opsize=S_B then
  10942. RemoveInstruction(hp1)
  10943. else
  10944. taicpu(hp1).loadconst(0,0);
  10945. taicpu(hp4).opcode:=A_SETcc;
  10946. taicpu(hp4).opsize:=S_B;
  10947. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10948. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10949. taicpu(hp4).opercnt:=1;
  10950. taicpu(hp4).ops:=1;
  10951. taicpu(hp4).freeop(1);
  10952. RemoveCurrentP(p);
  10953. Result:=true;
  10954. exit;
  10955. end
  10956. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  10957. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10958. begin
  10959. { check for
  10960. jCC xxx
  10961. <several movs>
  10962. xxx:
  10963. Also spot:
  10964. Jcc xxx
  10965. <several movs>
  10966. jmp xxx
  10967. Change to:
  10968. <several cmovs with inverted condition>
  10969. jmp xxx (only for the 2nd case)
  10970. }
  10971. hp2 := p;
  10972. hp_lblxxx := hp1;
  10973. hp_flagalloc := nil;
  10974. hp_stop := nil;
  10975. FoundMatchingJump := False;
  10976. { Remember the first instruction in the first block of MOVs }
  10977. hpmov1 := hp1;
  10978. TransferUsedRegs(TmpUsedRegs);
  10979. while assigned(hp_lblxxx) and
  10980. { stop on labels }
  10981. (hp_lblxxx.typ <> ait_label) do
  10982. begin
  10983. { Keep track of all integer registers that are used }
  10984. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10985. if hp_lblxxx.typ = ait_instruction then
  10986. begin
  10987. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10988. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10989. begin
  10990. hp_stop := hp_lblxxx;
  10991. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10992. begin
  10993. { We found Jcc xxx; <several movs>; Jmp xxx }
  10994. FoundMatchingJump := True;
  10995. Break;
  10996. end;
  10997. { If it's not the jump we're looking for, it's
  10998. possibly the "if..else" variant }
  10999. end
  11000. { Check to see if we have a valid MOV instruction instead }
  11001. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  11002. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11003. Break
  11004. else
  11005. { This will be a valid MOV }
  11006. hp_stop := hp_lblxxx;
  11007. end;
  11008. hp2 := hp_lblxxx;
  11009. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  11010. end;
  11011. { Just make sure the last MOV is included if there's no jump }
  11012. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  11013. hp_stop := hp_lblxxx;
  11014. { Note, the logic behind using hp_stop over hp_lblxxx in the
  11015. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  11016. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  11017. jmp yyy; xxx:; movs; yyy:" variation }
  11018. if assigned(hp_lblxxx) and
  11019. (
  11020. { If we found JMP xxx, we don't actually need a label
  11021. (hp_lblxxx is the JMP instruction instead) }
  11022. FoundMatchingJump or
  11023. { Make sure we actually have the right label }
  11024. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  11025. ) then
  11026. begin
  11027. { Use TmpUsedRegs to track registers that we reserve }
  11028. { When allocating temporary registers, try to look one
  11029. instruction back, as defining them before a CMP or TEST
  11030. instruction will be faster, and also avoid picking a
  11031. register that was only just deallocated }
  11032. if GetLastInstruction(p, hp_prev) and
  11033. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  11034. begin
  11035. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  11036. for l := 0 to 1 do
  11037. with taicpu(hp_prev).oper[l]^ do
  11038. case typ of
  11039. top_reg:
  11040. if getregtype(reg) = R_INTREGISTER then
  11041. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11042. top_ref:
  11043. begin
  11044. if
  11045. {$ifdef x86_64}
  11046. (ref^.base <> NR_RIP) and
  11047. {$endif x86_64}
  11048. (ref^.base <> NR_NO) then
  11049. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11050. if (ref^.index <> NR_NO) then
  11051. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11052. end
  11053. else
  11054. ;
  11055. end;
  11056. { When inserting instructions before hp_prev, try to insert
  11057. them before the allocation of the FLAGS register }
  11058. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  11059. { If not found, set it equal to hp_prev so it's something sensible }
  11060. hp_flagalloc := hp_prev;
  11061. hp_prev2 := nil;
  11062. { When dealing with a comparison against zero, take
  11063. note of the instruction before it to see if we can
  11064. move instructions further back in order to benefit
  11065. PostPeepholeOptTestOr.
  11066. }
  11067. if (
  11068. (
  11069. (taicpu(hp_prev).opcode = A_CMP) and
  11070. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  11071. ) or
  11072. (
  11073. (taicpu(hp_prev).opcode = A_TEST) and
  11074. (
  11075. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  11076. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  11077. )
  11078. )
  11079. ) and
  11080. GetLastInstruction(hp_prev, hp_prev2) then
  11081. begin
  11082. if (hp_prev2.typ = ait_instruction) and
  11083. { These instructions set the zero flag if the result is zero }
  11084. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  11085. begin
  11086. { Also mark all the registers in this previous instruction
  11087. as 'in use', even if they've just been deallocated }
  11088. for l := 0 to 1 do
  11089. with taicpu(hp_prev2).oper[l]^ do
  11090. case typ of
  11091. top_reg:
  11092. if getregtype(reg) = R_INTREGISTER then
  11093. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  11094. top_ref:
  11095. begin
  11096. if
  11097. {$ifdef x86_64}
  11098. (ref^.base <> NR_RIP) and
  11099. {$endif x86_64}
  11100. (ref^.base <> NR_NO) then
  11101. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  11102. if (ref^.index <> NR_NO) then
  11103. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  11104. end
  11105. else
  11106. ;
  11107. end;
  11108. end
  11109. else
  11110. { Unsuitable instruction }
  11111. hp_prev2 := nil;
  11112. end;
  11113. end
  11114. else
  11115. begin
  11116. hp_prev := p;
  11117. { When inserting instructions before hp_prev, try to insert
  11118. them before the allocation of the FLAGS register }
  11119. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  11120. { If not found, set it equal to p so it's something sensible }
  11121. hp_flagalloc := p;
  11122. hp_prev2 := nil;
  11123. end;
  11124. l := 0;
  11125. c := 0;
  11126. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  11127. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  11128. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  11129. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  11130. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  11131. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  11132. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  11133. RefModified := False;
  11134. while assigned(hp1) and
  11135. { Stop on the label we found }
  11136. (hp1 <> hp_lblxxx) do
  11137. begin
  11138. case hp1.typ of
  11139. ait_instruction:
  11140. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11141. begin
  11142. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11143. begin
  11144. Inc(l);
  11145. { MOV instruction will be writing to a register }
  11146. if Assigned(hp_prev) and
  11147. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11148. (hp_prev.typ = ait_instruction) and
  11149. (taicpu(hp_prev).ops = 2) and
  11150. (
  11151. (
  11152. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11153. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11154. ) or
  11155. (
  11156. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11157. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11158. )
  11159. ) then
  11160. { It is no longer safe to use the reference in the condition.
  11161. this prevents problems such as:
  11162. mov (%reg),%reg
  11163. mov (%reg),...
  11164. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11165. (fixes #40165)
  11166. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11167. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11168. }
  11169. RefModified := True;
  11170. end
  11171. else if not (cs_opt_size in current_settings.optimizerswitches) and
  11172. { CMOV with constants grows the code size }
  11173. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  11174. begin
  11175. { Register was reserved by TryCMOVConst and
  11176. stored on ConstRegs[c] }
  11177. end
  11178. else
  11179. Break;
  11180. end
  11181. else
  11182. Break;
  11183. else
  11184. ;
  11185. end;
  11186. GetNextInstruction(hp1,hp1);
  11187. end;
  11188. if (hp1 = hp_lblxxx) then
  11189. begin
  11190. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  11191. begin
  11192. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11193. TmpUsedRegs[R_INTREGISTER].Clear;
  11194. x := 0;
  11195. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  11196. condition := inverse_cond(taicpu(p).condition);
  11197. UpdateUsedRegs(tai(p.next));
  11198. hp1 := hpmov1;
  11199. repeat
  11200. if not Assigned(hp1) then
  11201. InternalError(2018062900);
  11202. if (hp1.typ = ait_instruction) then
  11203. begin
  11204. { Extra safeguard }
  11205. if (taicpu(hp1).opcode <> A_MOV) then
  11206. InternalError(2018062901);
  11207. if taicpu(hp1).oper[0]^.typ = top_const then
  11208. begin
  11209. if x >= MAX_CMOV_REGISTERS then
  11210. InternalError(2021100410);
  11211. { If it's in TmpUsedRegs, then this register
  11212. is being used more than once and hence has
  11213. already had its value defined (it gets
  11214. added to UsedRegs through AllocRegBetween
  11215. below) }
  11216. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11217. begin
  11218. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11219. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  11220. asml.InsertBefore(hp_new, hp_flagalloc);
  11221. if Assigned(hp_prev2) then
  11222. TrySwapMovOp(hp_prev2, hp_new);
  11223. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11224. ConstMovs[X] := hp_new;
  11225. end
  11226. else
  11227. { We just need an instruction between hp_prev and hp1
  11228. where we know the register is marked as in use }
  11229. hp_new := hpmov1;
  11230. { Keep track of largest write for this register so it can be optimised later }
  11231. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11232. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11233. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11234. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11235. Inc(x);
  11236. end;
  11237. taicpu(hp1).opcode := A_CMOVcc;
  11238. taicpu(hp1).condition := condition;
  11239. end;
  11240. UpdateUsedRegs(tai(hp1.next));
  11241. GetNextInstruction(hp1, hp1);
  11242. until (hp1 = hp_lblxxx);
  11243. { Update initialisation MOVs to the smallest possible size }
  11244. for c := 0 to x - 1 do
  11245. if Assigned(ConstMovs[c]) then
  11246. begin
  11247. taicpu(ConstMovs[c]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[c])]);
  11248. setsubreg(taicpu(ConstMovs[c]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[c])]);
  11249. end;
  11250. hp2 := hp_lblxxx;
  11251. repeat
  11252. if not Assigned(hp2) then
  11253. InternalError(2018062910);
  11254. case hp2.typ of
  11255. ait_label:
  11256. { What we expected - break out of the loop (it won't be a dead label at the top of
  11257. a cluster because that was optimised at an earlier stage) }
  11258. Break;
  11259. ait_align:
  11260. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11261. begin
  11262. hp2 := tai(hp2.Next);
  11263. Continue;
  11264. end;
  11265. ait_instruction:
  11266. begin
  11267. if taicpu(hp2).opcode<>A_JMP then
  11268. InternalError(2018062912);
  11269. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11270. Break;
  11271. end
  11272. else
  11273. begin
  11274. { Might be a comment or temporary allocation entry }
  11275. if not (hp2.typ in SkipInstr) then
  11276. InternalError(2018062911);
  11277. hp2 := tai(hp2.Next);
  11278. Continue;
  11279. end;
  11280. end;
  11281. until False;
  11282. { Now we can safely decrement the reference count }
  11283. tasmlabel(symbol).decrefs;
  11284. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11285. { Remove the original jump }
  11286. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11287. if hp2.typ=ait_instruction then
  11288. begin
  11289. p := hp2;
  11290. Result := True;
  11291. end
  11292. else
  11293. begin
  11294. UpdateUsedRegs(tai(hp2.next));
  11295. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11296. { Remove the label if this is its final reference }
  11297. if (tasmlabel(symbol).getrefs=0) then
  11298. begin
  11299. { Make sure the aligns get stripped too }
  11300. hp1 := tai(hp_lblxxx.Previous);
  11301. while Assigned(hp1) and (hp1.typ = ait_align) do
  11302. begin
  11303. hp_lblxxx := hp1;
  11304. hp1 := tai(hp_lblxxx.Previous);
  11305. end;
  11306. StripLabelFast(hp_lblxxx);
  11307. end;
  11308. end;
  11309. Exit;
  11310. end;
  11311. end
  11312. else if assigned(hp_lblxxx) and
  11313. { check further for
  11314. jCC xxx
  11315. <several movs 1>
  11316. jmp yyy
  11317. xxx:
  11318. <several movs 2>
  11319. yyy:
  11320. }
  11321. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11322. { hp1 should be pointing to jmp yyy }
  11323. MatchInstruction(hp1, A_JMP, []) and
  11324. { real label and jump, no further references to the
  11325. label are allowed }
  11326. (TAsmLabel(symbol).getrefs=1) and
  11327. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11328. begin
  11329. hp_jump := hp1;
  11330. { Don't set c to zero }
  11331. l := 0;
  11332. w := 0;
  11333. GetNextInstruction(hp_lblxxx, hpmov2);
  11334. hp2 := hp_lblxxx;
  11335. hp_lblyyy := hpmov2;
  11336. while assigned(hp_lblyyy) and
  11337. { stop on labels }
  11338. (hp_lblyyy.typ <> ait_label) do
  11339. begin
  11340. { Keep track of all integer registers that are used }
  11341. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11342. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11343. Break;
  11344. hp2 := hp_lblyyy;
  11345. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11346. end;
  11347. { Analyse the second batch of MOVs to see if the setup is valid }
  11348. RefModified := False;
  11349. hp1 := hpmov2;
  11350. while assigned(hp1) and
  11351. (hp1 <> hp_lblyyy) do
  11352. begin
  11353. case hp1.typ of
  11354. ait_instruction:
  11355. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11356. begin
  11357. if CanBeCMOV(hp1, hp_prev, RefModified) then
  11358. begin
  11359. Inc(l);
  11360. { MOV instruction will be writing to a register }
  11361. if Assigned(hp_prev) and
  11362. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11363. (hp_prev.typ = ait_instruction) and
  11364. (taicpu(hp_prev).ops = 2) and
  11365. (
  11366. (
  11367. (taicpu(hp_prev).oper[0]^.typ = top_ref) and
  11368. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[0]^.ref^)
  11369. ) or
  11370. (
  11371. (taicpu(hp_prev).oper[1]^.typ = top_ref) and
  11372. RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(hp_prev).oper[1]^.ref^)
  11373. )
  11374. ) then
  11375. { It is no longer safe to use the reference in the condition.
  11376. this prevents problems such as:
  11377. mov (%reg),%reg
  11378. mov (%reg),...
  11379. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  11380. (fixes #40165)
  11381. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  11382. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  11383. }
  11384. RefModified := True;
  11385. end
  11386. else if not (cs_opt_size in current_settings.optimizerswitches)
  11387. { CMOV with constants grows the code size }
  11388. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11389. begin
  11390. { Register was reserved by TryCMOVConst and
  11391. stored on ConstRegs[c] }
  11392. end
  11393. else
  11394. Break;
  11395. end
  11396. else
  11397. Break;
  11398. else
  11399. ;
  11400. end;
  11401. GetNextInstruction(hp1,hp1);
  11402. end;
  11403. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11404. TmpUsedRegs[R_INTREGISTER].Clear;
  11405. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11406. (hp1 = hp_lblyyy) and
  11407. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11408. begin
  11409. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11410. second_condition := taicpu(p).condition;
  11411. condition := inverse_cond(taicpu(p).condition);
  11412. UpdateUsedRegs(tai(p.next));
  11413. { Scan through the first set of MOVs to update UsedRegs,
  11414. but don't process them yet }
  11415. hp1 := hpmov1;
  11416. repeat
  11417. if not Assigned(hp1) then
  11418. InternalError(2018062901);
  11419. UpdateUsedRegs(tai(hp1.next));
  11420. GetNextInstruction(hp1, hp1);
  11421. until (hp1 = hp_lblxxx);
  11422. UpdateUsedRegs(tai(hp_lblxxx.next));
  11423. { Process the second set of MOVs first,
  11424. because if a destination register is
  11425. shared between the first and second MOV
  11426. sets, it is more efficient to turn the
  11427. first one into a MOV instruction and place
  11428. it before the CMP if possible, but we
  11429. won't know which registers are shared
  11430. until we've processed at least one list,
  11431. so we might as well make it the second
  11432. one since that won't be modified again. }
  11433. hp1 := hpmov2;
  11434. repeat
  11435. if not Assigned(hp1) then
  11436. InternalError(2018062902);
  11437. if (hp1.typ = ait_instruction) then
  11438. begin
  11439. { Extra safeguard }
  11440. if (taicpu(hp1).opcode <> A_MOV) then
  11441. InternalError(2018062903);
  11442. if taicpu(hp1).oper[0]^.typ = top_const then
  11443. begin
  11444. RegMatch := False;
  11445. for x := 0 to c - 1 do
  11446. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11447. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11448. begin
  11449. RegMatch := True;
  11450. { If it's in TmpUsedRegs, then this register
  11451. is being used more than once and hence has
  11452. already had its value defined (it gets
  11453. added to UsedRegs through AllocRegBetween
  11454. below) }
  11455. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11456. begin
  11457. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11458. asml.InsertBefore(hp_new, hp_flagalloc);
  11459. if Assigned(hp_prev2) then
  11460. TrySwapMovOp(hp_prev2, hp_new);
  11461. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11462. ConstMovs[X] := hp_new;
  11463. end
  11464. else
  11465. { We just need an instruction between hp_prev and hp1
  11466. where we know the register is marked as in use }
  11467. hp_new := hpmov2;
  11468. { Keep track of largest write for this register so it can be optimised later }
  11469. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11470. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11471. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11472. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11473. Break;
  11474. end;
  11475. if not RegMatch then
  11476. InternalError(2021100411);
  11477. end;
  11478. taicpu(hp1).opcode := A_CMOVcc;
  11479. taicpu(hp1).condition := second_condition;
  11480. { Store these writes to search for
  11481. duplicates later on }
  11482. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11483. Inc(w);
  11484. end;
  11485. UpdateUsedRegs(tai(hp1.next));
  11486. GetNextInstruction(hp1, hp1);
  11487. until (hp1 = hp_lblyyy);
  11488. { Now do the first set of MOVs }
  11489. hp1 := hpmov1;
  11490. repeat
  11491. if not Assigned(hp1) then
  11492. InternalError(2018062904);
  11493. if (hp1.typ = ait_instruction) then
  11494. begin
  11495. RegMatch := False;
  11496. { Extra safeguard }
  11497. if (taicpu(hp1).opcode <> A_MOV) then
  11498. InternalError(2018062905);
  11499. { Search through the RegWrites list to see
  11500. if there are any opposing CMOV pairs that
  11501. write to the same register }
  11502. for x := 0 to w - 1 do
  11503. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11504. begin
  11505. { We have a match. Keep this as a MOV }
  11506. { Move ahead in preparation }
  11507. GetNextInstruction(hp1, hp1);
  11508. RegMatch := True;
  11509. Break;
  11510. end;
  11511. if RegMatch then
  11512. Continue;
  11513. if taicpu(hp1).oper[0]^.typ = top_const then
  11514. begin
  11515. RegMatch := False;
  11516. for x := 0 to c - 1 do
  11517. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) and
  11518. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[X]) then
  11519. begin
  11520. RegMatch := True;
  11521. { If it's in TmpUsedRegs, then this register
  11522. is being used more than once and hence has
  11523. already had its value defined (it gets
  11524. added to UsedRegs through AllocRegBetween
  11525. below) }
  11526. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11527. begin
  11528. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[X]);
  11529. asml.InsertBefore(hp_new, hp_flagalloc);
  11530. if Assigned(hp_prev2) then
  11531. TrySwapMovOp(hp_prev2, hp_new);
  11532. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11533. ConstMovs[X] := hp_new;
  11534. end
  11535. else
  11536. { We just need an instruction between hp_prev and hp1
  11537. where we know the register is marked as in use }
  11538. hp_new := hpmov1;
  11539. { Keep track of largest write for this register so it can be optimised later }
  11540. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[X])]) then
  11541. ConstWriteSizes[getsupreg(ConstRegs[X])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  11542. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11543. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[X]), ConstSizes[X]));
  11544. Break;
  11545. end;
  11546. if not RegMatch then
  11547. InternalError(2021100412);
  11548. end;
  11549. taicpu(hp1).opcode := A_CMOVcc;
  11550. taicpu(hp1).condition := condition;
  11551. end;
  11552. GetNextInstruction(hp1, hp1);
  11553. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11554. { Update initialisation MOVs to the smallest possible size }
  11555. for x := 0 to c - 1 do
  11556. if Assigned(ConstMovs[x]) then
  11557. begin
  11558. taicpu(ConstMovs[x]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[x])]);
  11559. setsubreg(taicpu(ConstMovs[x]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[x])]);
  11560. end;
  11561. UpdateUsedRegs(tai(hp_jump.next));
  11562. UpdateUsedRegs(tai(hp_lblyyy.next));
  11563. { Get first instruction after label }
  11564. hp1 := p;
  11565. GetNextInstruction(hp_lblyyy, p);
  11566. { Don't dereference yet, as doing so will cause
  11567. GetNextInstruction to skip the label and
  11568. optional align marker. [Kit] }
  11569. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11570. { remove Jcc }
  11571. RemoveInstruction(hp1);
  11572. { Now we can safely decrement it }
  11573. tasmlabel(symbol).decrefs;
  11574. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11575. { Make sure the aligns get stripped too }
  11576. hp1 := tai(hp_lblxxx.Previous);
  11577. while Assigned(hp1) and (hp1.typ = ait_align) do
  11578. begin
  11579. hp_lblxxx := hp1;
  11580. hp1 := tai(hp_lblxxx.Previous);
  11581. end;
  11582. StripLabelFast(hp_lblxxx);
  11583. { remove jmp }
  11584. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11585. RemoveInstruction(hp_jump);
  11586. { As before, now we can safely decrement it }
  11587. TAsmLabel(symbol).decrefs;
  11588. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11589. if TAsmLabel(symbol).getrefs = 0 then
  11590. begin
  11591. { Make sure the aligns get stripped too }
  11592. hp1 := tai(hp_lblyyy.Previous);
  11593. while Assigned(hp1) and (hp1.typ = ait_align) do
  11594. begin
  11595. hp_lblyyy := hp1;
  11596. hp1 := tai(hp_lblyyy.Previous);
  11597. end;
  11598. StripLabelFast(hp_lblyyy);
  11599. end;
  11600. if Assigned(p) then
  11601. result := True;
  11602. exit;
  11603. end;
  11604. end;
  11605. end;
  11606. {$endif i8086}
  11607. end;
  11608. end;
  11609. end;
  11610. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11611. var
  11612. hp1,hp2,hp3: tai;
  11613. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11614. NewSize: TOpSize;
  11615. NewRegSize: TSubRegister;
  11616. Limit: TCgInt;
  11617. SwapOper: POper;
  11618. begin
  11619. result:=false;
  11620. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11621. GetNextInstruction(p,hp1) and
  11622. (hp1.typ = ait_instruction);
  11623. if reg_and_hp1_is_instr and
  11624. (
  11625. (taicpu(hp1).opcode <> A_LEA) or
  11626. { If the LEA instruction can be converted into an arithmetic instruction,
  11627. it may be possible to then fold it. }
  11628. (
  11629. { If the flags register is in use, don't change the instruction
  11630. to an ADD otherwise this will scramble the flags. [Kit] }
  11631. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11632. ConvertLEA(taicpu(hp1))
  11633. )
  11634. ) and
  11635. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11636. GetNextInstruction(hp1,hp2) and
  11637. MatchInstruction(hp2,A_MOV,[]) and
  11638. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11639. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11640. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11641. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11642. {$ifdef i386}
  11643. { not all registers have byte size sub registers on i386 }
  11644. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11645. {$endif i386}
  11646. (((taicpu(hp1).ops=2) and
  11647. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11648. ((taicpu(hp1).ops=1) and
  11649. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11650. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11651. begin
  11652. { change movsX/movzX reg/ref, reg2
  11653. add/sub/or/... reg3/$const, reg2
  11654. mov reg2 reg/ref
  11655. to add/sub/or/... reg3/$const, reg/ref }
  11656. { by example:
  11657. movswl %si,%eax movswl %si,%eax p
  11658. decl %eax addl %edx,%eax hp1
  11659. movw %ax,%si movw %ax,%si hp2
  11660. ->
  11661. movswl %si,%eax movswl %si,%eax p
  11662. decw %eax addw %edx,%eax hp1
  11663. movw %ax,%si movw %ax,%si hp2
  11664. }
  11665. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11666. {
  11667. ->
  11668. movswl %si,%eax movswl %si,%eax p
  11669. decw %si addw %dx,%si hp1
  11670. movw %ax,%si movw %ax,%si hp2
  11671. }
  11672. case taicpu(hp1).ops of
  11673. 1:
  11674. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11675. 2:
  11676. begin
  11677. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11678. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11679. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11680. end;
  11681. else
  11682. internalerror(2008042702);
  11683. end;
  11684. {
  11685. ->
  11686. decw %si addw %dx,%si p
  11687. }
  11688. DebugMsg(SPeepholeOptimization + 'var3',p);
  11689. RemoveCurrentP(p, hp1);
  11690. RemoveInstruction(hp2);
  11691. Result := True;
  11692. Exit;
  11693. end;
  11694. if reg_and_hp1_is_instr and
  11695. (taicpu(hp1).opcode = A_MOV) and
  11696. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11697. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11698. {$ifdef x86_64}
  11699. { check for implicit extension to 64 bit }
  11700. or
  11701. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11702. (taicpu(hp1).opsize=S_Q) and
  11703. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11704. )
  11705. {$endif x86_64}
  11706. )
  11707. then
  11708. begin
  11709. { change
  11710. movx %reg1,%reg2
  11711. mov %reg2,%reg3
  11712. dealloc %reg2
  11713. into
  11714. movx %reg,%reg3
  11715. }
  11716. TransferUsedRegs(TmpUsedRegs);
  11717. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11718. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11719. begin
  11720. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11721. {$ifdef x86_64}
  11722. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11723. (taicpu(hp1).opsize=S_Q) then
  11724. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11725. else
  11726. {$endif x86_64}
  11727. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11728. RemoveInstruction(hp1);
  11729. Result := True;
  11730. Exit;
  11731. end;
  11732. end;
  11733. if reg_and_hp1_is_instr and
  11734. ((taicpu(hp1).opcode=A_MOV) or
  11735. (taicpu(hp1).opcode=A_ADD) or
  11736. (taicpu(hp1).opcode=A_SUB) or
  11737. (taicpu(hp1).opcode=A_CMP) or
  11738. (taicpu(hp1).opcode=A_OR) or
  11739. (taicpu(hp1).opcode=A_XOR) or
  11740. (taicpu(hp1).opcode=A_AND)
  11741. ) and
  11742. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11743. begin
  11744. AndTest := (taicpu(hp1).opcode=A_AND) and
  11745. GetNextInstruction(hp1, hp2) and
  11746. (hp2.typ = ait_instruction) and
  11747. (
  11748. (
  11749. (taicpu(hp2).opcode=A_TEST) and
  11750. (
  11751. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11752. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11753. (
  11754. { If the AND and TEST instructions share a constant, this is also valid }
  11755. (taicpu(hp1).oper[0]^.typ = top_const) and
  11756. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11757. )
  11758. ) and
  11759. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11760. ) or
  11761. (
  11762. (taicpu(hp2).opcode=A_CMP) and
  11763. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11764. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11765. )
  11766. );
  11767. { change
  11768. movx (oper),%reg2
  11769. and $x,%reg2
  11770. test %reg2,%reg2
  11771. dealloc %reg2
  11772. into
  11773. op %reg1,%reg3
  11774. if the second op accesses only the bits stored in reg1
  11775. }
  11776. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11777. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11778. (taicpu(hp1).oper[0]^.typ = top_const) and
  11779. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11780. AndTest then
  11781. begin
  11782. { Check if the AND constant is in range }
  11783. case taicpu(p).opsize of
  11784. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11785. begin
  11786. NewSize := S_B;
  11787. Limit := $FF;
  11788. end;
  11789. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11790. begin
  11791. NewSize := S_W;
  11792. Limit := $FFFF;
  11793. end;
  11794. {$ifdef x86_64}
  11795. S_LQ:
  11796. begin
  11797. NewSize := S_L;
  11798. Limit := $FFFFFFFF;
  11799. end;
  11800. {$endif x86_64}
  11801. else
  11802. InternalError(2021120303);
  11803. end;
  11804. if (
  11805. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11806. { Check for negative operands }
  11807. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11808. ) and
  11809. GetNextInstruction(hp2,hp3) and
  11810. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11811. (taicpu(hp3).condition in [C_E,C_NE]) then
  11812. begin
  11813. TransferUsedRegs(TmpUsedRegs);
  11814. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11815. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11816. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11817. begin
  11818. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11819. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11820. taicpu(hp1).opcode := A_TEST;
  11821. taicpu(hp1).opsize := NewSize;
  11822. RemoveInstruction(hp2);
  11823. RemoveCurrentP(p, hp1);
  11824. Result:=true;
  11825. exit;
  11826. end;
  11827. end;
  11828. end;
  11829. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11830. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11831. (taicpu(hp1).opsize=S_B)) or
  11832. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11833. (taicpu(hp1).opsize=S_W))
  11834. {$ifdef x86_64}
  11835. or ((taicpu(p).opsize=S_LQ) and
  11836. (taicpu(hp1).opsize=S_L))
  11837. {$endif x86_64}
  11838. ) and
  11839. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11840. begin
  11841. { change
  11842. movx %reg1,%reg2
  11843. op %reg2,%reg3
  11844. dealloc %reg2
  11845. into
  11846. op %reg1,%reg3
  11847. if the second op accesses only the bits stored in reg1
  11848. }
  11849. TransferUsedRegs(TmpUsedRegs);
  11850. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11851. if AndTest then
  11852. begin
  11853. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11854. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11855. end
  11856. else
  11857. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11858. if not RegUsed then
  11859. begin
  11860. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11861. if taicpu(p).oper[0]^.typ=top_reg then
  11862. begin
  11863. case taicpu(hp1).opsize of
  11864. S_B:
  11865. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11866. S_W:
  11867. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11868. S_L:
  11869. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11870. else
  11871. Internalerror(2020102301);
  11872. end;
  11873. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11874. end
  11875. else
  11876. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11877. RemoveCurrentP(p);
  11878. if AndTest then
  11879. RemoveInstruction(hp2);
  11880. result:=true;
  11881. exit;
  11882. end;
  11883. end
  11884. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11885. (
  11886. { Bitwise operations only }
  11887. (taicpu(hp1).opcode=A_AND) or
  11888. (taicpu(hp1).opcode=A_TEST) or
  11889. (
  11890. (taicpu(hp1).oper[0]^.typ = top_const) and
  11891. (
  11892. (taicpu(hp1).opcode=A_OR) or
  11893. (taicpu(hp1).opcode=A_XOR)
  11894. )
  11895. )
  11896. ) and
  11897. (
  11898. (taicpu(hp1).oper[0]^.typ = top_const) or
  11899. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11900. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11901. ) then
  11902. begin
  11903. { change
  11904. movx %reg2,%reg2
  11905. op const,%reg2
  11906. into
  11907. op const,%reg2 (smaller version)
  11908. movx %reg2,%reg2
  11909. also change
  11910. movx %reg1,%reg2
  11911. and/test (oper),%reg2
  11912. dealloc %reg2
  11913. into
  11914. and/test (oper),%reg1
  11915. }
  11916. case taicpu(p).opsize of
  11917. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11918. begin
  11919. NewSize := S_B;
  11920. NewRegSize := R_SUBL;
  11921. Limit := $FF;
  11922. end;
  11923. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11924. begin
  11925. NewSize := S_W;
  11926. NewRegSize := R_SUBW;
  11927. Limit := $FFFF;
  11928. end;
  11929. {$ifdef x86_64}
  11930. S_LQ:
  11931. begin
  11932. NewSize := S_L;
  11933. NewRegSize := R_SUBD;
  11934. Limit := $FFFFFFFF;
  11935. end;
  11936. {$endif x86_64}
  11937. else
  11938. Internalerror(2021120302);
  11939. end;
  11940. TransferUsedRegs(TmpUsedRegs);
  11941. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11942. if AndTest then
  11943. begin
  11944. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11945. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11946. end
  11947. else
  11948. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11949. if
  11950. (
  11951. (taicpu(p).opcode = A_MOVZX) and
  11952. (
  11953. (taicpu(hp1).opcode=A_AND) or
  11954. (taicpu(hp1).opcode=A_TEST)
  11955. ) and
  11956. not (
  11957. { If both are references, then the final instruction will have
  11958. both operands as references, which is not allowed }
  11959. (taicpu(p).oper[0]^.typ = top_ref) and
  11960. (taicpu(hp1).oper[0]^.typ = top_ref)
  11961. ) and
  11962. not RegUsed
  11963. ) or
  11964. (
  11965. (
  11966. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11967. not RegUsed
  11968. ) and
  11969. (taicpu(p).oper[0]^.typ = top_reg) and
  11970. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11971. (taicpu(hp1).oper[0]^.typ = top_const) and
  11972. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11973. ) then
  11974. begin
  11975. {$if defined(i386) or defined(i8086)}
  11976. { If the target size is 8-bit, make sure we can actually encode it }
  11977. 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
  11978. Exit;
  11979. {$endif i386 or i8086}
  11980. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11981. taicpu(hp1).opsize := NewSize;
  11982. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11983. if AndTest then
  11984. begin
  11985. RemoveInstruction(hp2);
  11986. if not RegUsed then
  11987. begin
  11988. taicpu(hp1).opcode := A_TEST;
  11989. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11990. begin
  11991. { Make sure the reference is the second operand }
  11992. SwapOper := taicpu(hp1).oper[0];
  11993. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11994. taicpu(hp1).oper[1] := SwapOper;
  11995. end;
  11996. end;
  11997. end;
  11998. case taicpu(hp1).oper[0]^.typ of
  11999. top_reg:
  12000. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  12001. top_const:
  12002. { For the AND/TEST case }
  12003. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  12004. else
  12005. ;
  12006. end;
  12007. if RegUsed then
  12008. begin
  12009. AsmL.Remove(p);
  12010. AsmL.InsertAfter(p, hp1);
  12011. p := hp1;
  12012. end
  12013. else
  12014. RemoveCurrentP(p, hp1);
  12015. result:=true;
  12016. exit;
  12017. end;
  12018. end;
  12019. end;
  12020. if reg_and_hp1_is_instr and
  12021. (taicpu(p).oper[0]^.typ = top_reg) and
  12022. (
  12023. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  12024. ) and
  12025. (taicpu(hp1).oper[0]^.typ = top_const) and
  12026. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12027. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12028. { Minimum shift value allowed is the bit difference between the sizes }
  12029. (taicpu(hp1).oper[0]^.val >=
  12030. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12031. 8 * (
  12032. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  12033. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12034. )
  12035. ) then
  12036. begin
  12037. { For:
  12038. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  12039. shl/sal ##, %reg1
  12040. Remove the movsx/movzx instruction if the shift overwrites the
  12041. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  12042. }
  12043. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  12044. RemoveCurrentP(p, hp1);
  12045. Result := True;
  12046. Exit;
  12047. end
  12048. else if reg_and_hp1_is_instr and
  12049. (taicpu(p).oper[0]^.typ = top_reg) and
  12050. (
  12051. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  12052. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  12053. ) and
  12054. (taicpu(hp1).oper[0]^.typ = top_const) and
  12055. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12056. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12057. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  12058. (taicpu(hp1).oper[0]^.val <
  12059. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  12060. 8 * (
  12061. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  12062. )
  12063. ) then
  12064. begin
  12065. { For:
  12066. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  12067. sar ##, %reg1 shr ##, %reg1
  12068. Move the shift to before the movx instruction if the shift value
  12069. is not too large.
  12070. }
  12071. asml.Remove(hp1);
  12072. asml.InsertBefore(hp1, p);
  12073. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12074. case taicpu(p).opsize of
  12075. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  12076. taicpu(hp1).opsize := S_B;
  12077. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  12078. taicpu(hp1).opsize := S_W;
  12079. {$ifdef x86_64}
  12080. S_LQ:
  12081. taicpu(hp1).opsize := S_L;
  12082. {$endif}
  12083. else
  12084. InternalError(2020112401);
  12085. end;
  12086. if (taicpu(hp1).opcode = A_SHR) then
  12087. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  12088. else
  12089. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  12090. Result := True;
  12091. end;
  12092. if reg_and_hp1_is_instr and
  12093. (taicpu(p).oper[0]^.typ = top_reg) and
  12094. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12095. (
  12096. (taicpu(hp1).opcode = taicpu(p).opcode)
  12097. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  12098. {$ifdef x86_64}
  12099. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  12100. {$endif x86_64}
  12101. ) then
  12102. begin
  12103. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12104. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  12105. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12106. begin
  12107. {
  12108. For example:
  12109. movzbw %al,%ax
  12110. movzwl %ax,%eax
  12111. Compress into:
  12112. movzbl %al,%eax
  12113. }
  12114. RegUsed := False;
  12115. case taicpu(p).opsize of
  12116. S_BW:
  12117. case taicpu(hp1).opsize of
  12118. S_WL:
  12119. begin
  12120. taicpu(p).opsize := S_BL;
  12121. RegUsed := True;
  12122. end;
  12123. {$ifdef x86_64}
  12124. S_WQ:
  12125. begin
  12126. if taicpu(p).opcode = A_MOVZX then
  12127. begin
  12128. taicpu(p).opsize := S_BL;
  12129. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12130. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12131. end
  12132. else
  12133. taicpu(p).opsize := S_BQ;
  12134. RegUsed := True;
  12135. end;
  12136. {$endif x86_64}
  12137. else
  12138. ;
  12139. end;
  12140. {$ifdef x86_64}
  12141. S_BL:
  12142. case taicpu(hp1).opsize of
  12143. S_LQ:
  12144. begin
  12145. if taicpu(p).opcode = A_MOVZX then
  12146. begin
  12147. taicpu(p).opsize := S_BL;
  12148. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12149. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12150. end
  12151. else
  12152. taicpu(p).opsize := S_BQ;
  12153. RegUsed := True;
  12154. end;
  12155. else
  12156. ;
  12157. end;
  12158. S_WL:
  12159. case taicpu(hp1).opsize of
  12160. S_LQ:
  12161. begin
  12162. if taicpu(p).opcode = A_MOVZX then
  12163. begin
  12164. taicpu(p).opsize := S_WL;
  12165. { 64-bit zero extension is implicit, so change to the 32-bit register }
  12166. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12167. end
  12168. else
  12169. taicpu(p).opsize := S_WQ;
  12170. RegUsed := True;
  12171. end;
  12172. else
  12173. ;
  12174. end;
  12175. {$endif x86_64}
  12176. else
  12177. ;
  12178. end;
  12179. if RegUsed then
  12180. begin
  12181. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  12182. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  12183. RemoveInstruction(hp1);
  12184. Result := True;
  12185. Exit;
  12186. end;
  12187. end;
  12188. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12189. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  12190. GetNextInstruction(hp1, hp2) and
  12191. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  12192. (
  12193. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  12194. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  12195. {$ifdef x86_64}
  12196. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  12197. {$endif x86_64}
  12198. ) and
  12199. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  12200. (
  12201. (
  12202. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  12203. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12204. ) or
  12205. (
  12206. { Only allow the operands in reverse order for TEST instructions }
  12207. (taicpu(hp2).opcode = A_TEST) and
  12208. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12209. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  12210. )
  12211. ) then
  12212. begin
  12213. {
  12214. For example:
  12215. movzbl %al,%eax
  12216. movzbl (ref),%edx
  12217. andl %edx,%eax
  12218. (%edx deallocated)
  12219. Change to:
  12220. andb (ref),%al
  12221. movzbl %al,%eax
  12222. Rules are:
  12223. - First two instructions have the same opcode and opsize
  12224. - First instruction's operands are the same super-register
  12225. - Second instruction operates on a different register
  12226. - Third instruction is AND, OR, XOR or TEST
  12227. - Third instruction's operands are the destination registers of the first two instructions
  12228. - Third instruction writes to the destination register of the first instruction (except with TEST)
  12229. - Second instruction's destination register is deallocated afterwards
  12230. }
  12231. TransferUsedRegs(TmpUsedRegs);
  12232. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12233. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  12234. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  12235. begin
  12236. case taicpu(p).opsize of
  12237. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12238. NewSize := S_B;
  12239. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12240. NewSize := S_W;
  12241. {$ifdef x86_64}
  12242. S_LQ:
  12243. NewSize := S_L;
  12244. {$endif x86_64}
  12245. else
  12246. InternalError(2021120301);
  12247. end;
  12248. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  12249. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  12250. taicpu(hp2).opsize := NewSize;
  12251. RemoveInstruction(hp1);
  12252. { With TEST, it's best to keep the MOVX instruction at the top }
  12253. if (taicpu(hp2).opcode <> A_TEST) then
  12254. begin
  12255. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  12256. asml.Remove(p);
  12257. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  12258. asml.InsertAfter(p, hp2);
  12259. p := hp2;
  12260. end
  12261. else
  12262. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  12263. Result := True;
  12264. Exit;
  12265. end;
  12266. end;
  12267. end;
  12268. if taicpu(p).opcode=A_MOVZX then
  12269. begin
  12270. { removes superfluous And's after movzx's }
  12271. if reg_and_hp1_is_instr and
  12272. (taicpu(hp1).opcode = A_AND) and
  12273. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12274. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  12275. {$ifdef x86_64}
  12276. { check for implicit extension to 64 bit }
  12277. or
  12278. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12279. (taicpu(hp1).opsize=S_Q) and
  12280. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12281. )
  12282. {$endif x86_64}
  12283. )
  12284. then
  12285. begin
  12286. case taicpu(p).opsize Of
  12287. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12288. if (taicpu(hp1).oper[0]^.val = $ff) then
  12289. begin
  12290. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12291. RemoveInstruction(hp1);
  12292. Result:=true;
  12293. exit;
  12294. end;
  12295. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12296. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12297. begin
  12298. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12299. RemoveInstruction(hp1);
  12300. Result:=true;
  12301. exit;
  12302. end;
  12303. {$ifdef x86_64}
  12304. S_LQ:
  12305. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12306. begin
  12307. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12308. RemoveInstruction(hp1);
  12309. Result:=true;
  12310. exit;
  12311. end;
  12312. {$endif x86_64}
  12313. else
  12314. ;
  12315. end;
  12316. { we cannot get rid of the and, but can we get rid of the movz ?}
  12317. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12318. begin
  12319. case taicpu(p).opsize Of
  12320. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12321. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12322. begin
  12323. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12324. RemoveCurrentP(p,hp1);
  12325. Result:=true;
  12326. exit;
  12327. end;
  12328. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12329. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12330. begin
  12331. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12332. RemoveCurrentP(p,hp1);
  12333. Result:=true;
  12334. exit;
  12335. end;
  12336. {$ifdef x86_64}
  12337. S_LQ:
  12338. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12339. begin
  12340. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12341. RemoveCurrentP(p,hp1);
  12342. Result:=true;
  12343. exit;
  12344. end;
  12345. {$endif x86_64}
  12346. else
  12347. ;
  12348. end;
  12349. end;
  12350. end;
  12351. { changes some movzx constructs to faster synonyms (all examples
  12352. are given with eax/ax, but are also valid for other registers)}
  12353. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12354. begin
  12355. case taicpu(p).opsize of
  12356. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12357. (the machine code is equivalent to movzbl %al,%eax), but the
  12358. code generator still generates that assembler instruction and
  12359. it is silently converted. This should probably be checked.
  12360. [Kit] }
  12361. S_BW:
  12362. begin
  12363. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12364. (
  12365. not IsMOVZXAcceptable
  12366. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12367. or (
  12368. (cs_opt_size in current_settings.optimizerswitches) and
  12369. (taicpu(p).oper[1]^.reg = NR_AX)
  12370. )
  12371. ) then
  12372. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12373. begin
  12374. DebugMsg(SPeepholeOptimization + 'var7',p);
  12375. taicpu(p).opcode := A_AND;
  12376. taicpu(p).changeopsize(S_W);
  12377. taicpu(p).loadConst(0,$ff);
  12378. Result := True;
  12379. end
  12380. else if not IsMOVZXAcceptable and
  12381. GetNextInstruction(p, hp1) and
  12382. (tai(hp1).typ = ait_instruction) and
  12383. (taicpu(hp1).opcode = A_AND) and
  12384. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12385. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12386. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12387. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12388. begin
  12389. DebugMsg(SPeepholeOptimization + 'var8',p);
  12390. taicpu(p).opcode := A_MOV;
  12391. taicpu(p).changeopsize(S_W);
  12392. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12393. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12394. Result := True;
  12395. end;
  12396. end;
  12397. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12398. S_BL:
  12399. if not IsMOVZXAcceptable then
  12400. begin
  12401. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12402. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12403. begin
  12404. DebugMsg(SPeepholeOptimization + 'var9',p);
  12405. taicpu(p).opcode := A_AND;
  12406. taicpu(p).changeopsize(S_L);
  12407. taicpu(p).loadConst(0,$ff);
  12408. Result := True;
  12409. end
  12410. else if GetNextInstruction(p, hp1) and
  12411. (tai(hp1).typ = ait_instruction) and
  12412. (taicpu(hp1).opcode = A_AND) and
  12413. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12414. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12415. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12416. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12417. begin
  12418. DebugMsg(SPeepholeOptimization + 'var10',p);
  12419. taicpu(p).opcode := A_MOV;
  12420. taicpu(p).changeopsize(S_L);
  12421. { do not use R_SUBWHOLE
  12422. as movl %rdx,%eax
  12423. is invalid in assembler PM }
  12424. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12425. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12426. Result := True;
  12427. end;
  12428. end;
  12429. {$endif i8086}
  12430. S_WL:
  12431. if not IsMOVZXAcceptable then
  12432. begin
  12433. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12434. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12435. begin
  12436. DebugMsg(SPeepholeOptimization + 'var11',p);
  12437. taicpu(p).opcode := A_AND;
  12438. taicpu(p).changeopsize(S_L);
  12439. taicpu(p).loadConst(0,$ffff);
  12440. Result := True;
  12441. end
  12442. else if GetNextInstruction(p, hp1) and
  12443. (tai(hp1).typ = ait_instruction) and
  12444. (taicpu(hp1).opcode = A_AND) and
  12445. (taicpu(hp1).oper[0]^.typ = top_const) and
  12446. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12447. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12448. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12449. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12450. begin
  12451. DebugMsg(SPeepholeOptimization + 'var12',p);
  12452. taicpu(p).opcode := A_MOV;
  12453. taicpu(p).changeopsize(S_L);
  12454. { do not use R_SUBWHOLE
  12455. as movl %rdx,%eax
  12456. is invalid in assembler PM }
  12457. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12458. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12459. Result := True;
  12460. end;
  12461. end;
  12462. else
  12463. InternalError(2017050705);
  12464. end;
  12465. end
  12466. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12467. begin
  12468. if GetNextInstruction(p, hp1) and
  12469. (tai(hp1).typ = ait_instruction) and
  12470. (taicpu(hp1).opcode = A_AND) and
  12471. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12472. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12473. begin
  12474. //taicpu(p).opcode := A_MOV;
  12475. case taicpu(p).opsize Of
  12476. S_BL:
  12477. begin
  12478. DebugMsg(SPeepholeOptimization + 'var13',p);
  12479. taicpu(hp1).changeopsize(S_L);
  12480. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12481. end;
  12482. S_WL:
  12483. begin
  12484. DebugMsg(SPeepholeOptimization + 'var14',p);
  12485. taicpu(hp1).changeopsize(S_L);
  12486. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12487. end;
  12488. S_BW:
  12489. begin
  12490. DebugMsg(SPeepholeOptimization + 'var15',p);
  12491. taicpu(hp1).changeopsize(S_W);
  12492. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12493. end;
  12494. else
  12495. Internalerror(2017050704)
  12496. end;
  12497. Result := True;
  12498. end;
  12499. end;
  12500. end;
  12501. end;
  12502. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12503. var
  12504. hp1, hp2 : tai;
  12505. MaskLength : Cardinal;
  12506. MaskedBits : TCgInt;
  12507. ActiveReg : TRegister;
  12508. begin
  12509. Result:=false;
  12510. { There are no optimisations for reference targets }
  12511. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12512. Exit;
  12513. while GetNextInstruction(p, hp1) and
  12514. (hp1.typ = ait_instruction) do
  12515. begin
  12516. if (taicpu(p).oper[0]^.typ = top_const) then
  12517. begin
  12518. case taicpu(hp1).opcode of
  12519. A_AND:
  12520. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12521. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12522. { the second register must contain the first one, so compare their subreg types }
  12523. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12524. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12525. { change
  12526. and const1, reg
  12527. and const2, reg
  12528. to
  12529. and (const1 and const2), reg
  12530. }
  12531. begin
  12532. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12533. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12534. RemoveCurrentP(p, hp1);
  12535. Result:=true;
  12536. exit;
  12537. end;
  12538. A_CMP:
  12539. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12540. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12541. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12542. { Just check that the condition on the next instruction is compatible }
  12543. GetNextInstruction(hp1, hp2) and
  12544. (hp2.typ = ait_instruction) and
  12545. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12546. then
  12547. { change
  12548. and 2^n, reg
  12549. cmp 2^n, reg
  12550. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12551. to
  12552. and 2^n, reg
  12553. test reg, reg
  12554. j(~c) / set(~c) / cmov(~c)
  12555. }
  12556. begin
  12557. { Keep TEST instruction in, rather than remove it, because
  12558. it may trigger other optimisations such as MovAndTest2Test }
  12559. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12560. taicpu(hp1).opcode := A_TEST;
  12561. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12562. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12563. Result := True;
  12564. Exit;
  12565. end
  12566. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  12567. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12568. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  12569. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  12570. { change
  12571. and $ff/$ff/$ffff, reg
  12572. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  12573. dealloc reg
  12574. to
  12575. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  12576. }
  12577. begin
  12578. TransferUsedRegs(TmpUsedRegs);
  12579. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12580. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  12581. begin
  12582. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  12583. case taicpu(p).oper[0]^.val of
  12584. $ff:
  12585. begin
  12586. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  12587. taicpu(hp1).opsize:=S_B;
  12588. end;
  12589. $ffff:
  12590. begin
  12591. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  12592. taicpu(hp1).opsize:=S_W;
  12593. end;
  12594. $ffffffff:
  12595. begin
  12596. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  12597. taicpu(hp1).opsize:=S_L;
  12598. end;
  12599. else
  12600. Internalerror(2023030401);
  12601. end;
  12602. RemoveCurrentP(p);
  12603. Result := True;
  12604. Exit;
  12605. end;
  12606. end;
  12607. A_MOVZX:
  12608. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12609. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12610. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12611. (
  12612. (
  12613. (taicpu(p).opsize=S_W) and
  12614. (taicpu(hp1).opsize=S_BW)
  12615. ) or
  12616. (
  12617. (taicpu(p).opsize=S_L) and
  12618. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12619. )
  12620. {$ifdef x86_64}
  12621. or
  12622. (
  12623. (taicpu(p).opsize=S_Q) and
  12624. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12625. )
  12626. {$endif x86_64}
  12627. ) then
  12628. begin
  12629. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12630. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12631. ) or
  12632. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12633. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12634. then
  12635. begin
  12636. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12637. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12638. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12639. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12640. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12641. }
  12642. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12643. RemoveInstruction(hp1);
  12644. { See if there are other optimisations possible }
  12645. Continue;
  12646. end;
  12647. end;
  12648. A_SHL:
  12649. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12650. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12651. begin
  12652. {$ifopt R+}
  12653. {$define RANGE_WAS_ON}
  12654. {$R-}
  12655. {$endif}
  12656. { get length of potential and mask }
  12657. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12658. { really a mask? }
  12659. {$ifdef RANGE_WAS_ON}
  12660. {$R+}
  12661. {$endif}
  12662. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12663. { unmasked part shifted out? }
  12664. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12665. begin
  12666. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12667. RemoveCurrentP(p, hp1);
  12668. Result:=true;
  12669. exit;
  12670. end;
  12671. end;
  12672. A_SHR:
  12673. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12674. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12675. (taicpu(hp1).oper[0]^.val <= 63) then
  12676. begin
  12677. { Does SHR combined with the AND cover all the bits?
  12678. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12679. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12680. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12681. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12682. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12683. begin
  12684. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12685. RemoveCurrentP(p, hp1);
  12686. Result := True;
  12687. Exit;
  12688. end;
  12689. end;
  12690. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12691. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12692. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12693. begin
  12694. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12695. (
  12696. (
  12697. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12698. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12699. ) or (
  12700. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12701. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12702. {$ifdef x86_64}
  12703. ) or (
  12704. (taicpu(hp1).opsize = S_LQ) and
  12705. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12706. {$endif x86_64}
  12707. )
  12708. ) then
  12709. begin
  12710. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12711. begin
  12712. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12713. RemoveInstruction(hp1);
  12714. { See if there are other optimisations possible }
  12715. Continue;
  12716. end;
  12717. { The super-registers are the same though.
  12718. Note that this change by itself doesn't improve
  12719. code speed, but it opens up other optimisations. }
  12720. {$ifdef x86_64}
  12721. { Convert 64-bit register to 32-bit }
  12722. case taicpu(hp1).opsize of
  12723. S_BQ:
  12724. begin
  12725. taicpu(hp1).opsize := S_BL;
  12726. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12727. end;
  12728. S_WQ:
  12729. begin
  12730. taicpu(hp1).opsize := S_WL;
  12731. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12732. end
  12733. else
  12734. ;
  12735. end;
  12736. {$endif x86_64}
  12737. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12738. taicpu(hp1).opcode := A_MOVZX;
  12739. { See if there are other optimisations possible }
  12740. Continue;
  12741. end;
  12742. end;
  12743. else
  12744. ;
  12745. end;
  12746. end
  12747. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12748. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12749. begin
  12750. {$ifdef x86_64}
  12751. if (taicpu(p).opsize = S_Q) then
  12752. begin
  12753. { Never necessary }
  12754. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12755. RemoveCurrentP(p, hp1);
  12756. Result := True;
  12757. Exit;
  12758. end;
  12759. {$endif x86_64}
  12760. { Forward check to determine necessity of and %reg,%reg }
  12761. TransferUsedRegs(TmpUsedRegs);
  12762. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12763. { Saves on a bunch of dereferences }
  12764. ActiveReg := taicpu(p).oper[1]^.reg;
  12765. case taicpu(hp1).opcode of
  12766. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12767. if (
  12768. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12769. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12770. ) and
  12771. (
  12772. (taicpu(hp1).opcode <> A_MOV) or
  12773. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12774. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12775. ) and
  12776. not (
  12777. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12778. (taicpu(hp1).opcode = A_MOV) and
  12779. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12780. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12781. ) and
  12782. (
  12783. (
  12784. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12785. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12786. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12787. ) or
  12788. (
  12789. {$ifdef x86_64}
  12790. (
  12791. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12792. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12793. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12794. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12795. ) and
  12796. {$endif x86_64}
  12797. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12798. )
  12799. ) then
  12800. begin
  12801. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12802. RemoveCurrentP(p, hp1);
  12803. Result := True;
  12804. Exit;
  12805. end;
  12806. A_ADD,
  12807. A_AND,
  12808. A_BSF,
  12809. A_BSR,
  12810. A_BTC,
  12811. A_BTR,
  12812. A_BTS,
  12813. A_OR,
  12814. A_SUB,
  12815. A_XOR:
  12816. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12817. if (
  12818. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12819. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12820. ) and
  12821. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12822. begin
  12823. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12824. RemoveCurrentP(p, hp1);
  12825. Result := True;
  12826. Exit;
  12827. end;
  12828. A_CMP,
  12829. A_TEST:
  12830. if (
  12831. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12832. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12833. ) and
  12834. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12835. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12836. begin
  12837. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12838. RemoveCurrentP(p, hp1);
  12839. Result := True;
  12840. Exit;
  12841. end;
  12842. A_BSWAP,
  12843. A_NEG,
  12844. A_NOT:
  12845. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12846. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12847. begin
  12848. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12849. RemoveCurrentP(p, hp1);
  12850. Result := True;
  12851. Exit;
  12852. end;
  12853. else
  12854. ;
  12855. end;
  12856. end;
  12857. if (taicpu(hp1).is_jmp) and
  12858. (taicpu(hp1).opcode<>A_JMP) and
  12859. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12860. begin
  12861. { change
  12862. and x, reg
  12863. jxx
  12864. to
  12865. test x, reg
  12866. jxx
  12867. if reg is deallocated before the
  12868. jump, but only if it's a conditional jump (PFV)
  12869. }
  12870. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12871. taicpu(p).opcode := A_TEST;
  12872. Exit;
  12873. end;
  12874. Break;
  12875. end;
  12876. { Lone AND tests }
  12877. if (taicpu(p).oper[0]^.typ = top_const) then
  12878. begin
  12879. {
  12880. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12881. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12882. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12883. }
  12884. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12885. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12886. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12887. begin
  12888. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12889. if taicpu(p).opsize = S_L then
  12890. begin
  12891. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12892. Result := True;
  12893. end;
  12894. end;
  12895. end;
  12896. { Backward check to determine necessity of and %reg,%reg }
  12897. if (taicpu(p).oper[0]^.typ = top_reg) and
  12898. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12899. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12900. GetLastInstruction(p, hp2) and
  12901. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12902. { Check size of adjacent instruction to determine if the AND is
  12903. effectively a null operation }
  12904. (
  12905. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12906. { Note: Don't include S_Q }
  12907. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12908. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12909. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12910. ) then
  12911. begin
  12912. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12913. { If GetNextInstruction returned False, hp1 will be nil }
  12914. RemoveCurrentP(p, hp1);
  12915. Result := True;
  12916. Exit;
  12917. end;
  12918. end;
  12919. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12920. var
  12921. hp1, hp2: tai;
  12922. NewRef: TReference;
  12923. Distance: Cardinal;
  12924. TempTracking: TAllUsedRegs;
  12925. { This entire nested function is used in an if-statement below, but we
  12926. want to avoid all the used reg transfers and GetNextInstruction calls
  12927. until we really have to check }
  12928. function MemRegisterNotUsedLater: Boolean; inline;
  12929. var
  12930. hp2: tai;
  12931. begin
  12932. TransferUsedRegs(TmpUsedRegs);
  12933. hp2 := p;
  12934. repeat
  12935. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12936. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12937. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12938. end;
  12939. begin
  12940. Result := False;
  12941. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12942. (taicpu(p).oper[1]^.typ = top_reg) then
  12943. begin
  12944. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12945. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12946. (hp1.typ <> ait_instruction) or
  12947. not
  12948. (
  12949. (cs_opt_level3 in current_settings.optimizerswitches) or
  12950. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12951. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12952. ) then
  12953. Exit;
  12954. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12955. addq $x, %rax
  12956. movq %rax, %rdx
  12957. sarq $63, %rdx
  12958. (%rax still in use)
  12959. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12960. leaq $x(%rax),%rdx
  12961. addq $x, %rax
  12962. sarq $63, %rdx
  12963. ...which is okay since it breaks the dependency chain between
  12964. addq and movq, but if OptPass2MOV is called first:
  12965. addq $x, %rax
  12966. cqto
  12967. ...which is better in all ways, taking only 2 cycles to execute
  12968. and much smaller in code size.
  12969. }
  12970. { The extra register tracking is quite strenuous }
  12971. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12972. MatchInstruction(hp1, A_MOV, []) then
  12973. begin
  12974. { Update the register tracking to the MOV instruction }
  12975. CopyUsedRegs(TempTracking);
  12976. hp2 := p;
  12977. repeat
  12978. UpdateUsedRegs(tai(hp2.Next));
  12979. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12980. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12981. OptPass2ADD get called again }
  12982. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12983. begin
  12984. { Reset the tracking to the current instruction }
  12985. RestoreUsedRegs(TempTracking);
  12986. ReleaseUsedRegs(TempTracking);
  12987. Result := True;
  12988. Exit;
  12989. end;
  12990. { Reset the tracking to the current instruction }
  12991. RestoreUsedRegs(TempTracking);
  12992. ReleaseUsedRegs(TempTracking);
  12993. { If OptPass2MOV returned True, we don't need to set Result to
  12994. True if hp1 didn't change because the ADD instruction didn't
  12995. get modified and we'll be evaluating hp1 again when the
  12996. peephole optimizer reaches it }
  12997. end;
  12998. { Change:
  12999. add %reg2,%reg1
  13000. (%reg2 not modified in between)
  13001. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  13002. To:
  13003. mov/s/z #(%reg1,%reg2),%reg1
  13004. }
  13005. if (taicpu(p).oper[0]^.typ = top_reg) and
  13006. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  13007. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  13008. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  13009. (
  13010. (
  13011. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  13012. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  13013. { r/esp cannot be an index }
  13014. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  13015. ) or (
  13016. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  13017. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  13018. )
  13019. ) and (
  13020. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  13021. (
  13022. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  13023. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  13024. MemRegisterNotUsedLater
  13025. )
  13026. ) then
  13027. begin
  13028. if (
  13029. { Instructions are guaranteed to be adjacent on -O2 and under }
  13030. (cs_opt_level3 in current_settings.optimizerswitches) and
  13031. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  13032. ) then
  13033. begin
  13034. { If the other register is used in between, move the MOV
  13035. instruction to right after the ADD instruction so a
  13036. saving can still be made }
  13037. Asml.Remove(hp1);
  13038. Asml.InsertAfter(hp1, p);
  13039. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13040. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13041. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  13042. RemoveCurrentp(p, hp1);
  13043. end
  13044. else
  13045. begin
  13046. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  13047. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  13048. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  13049. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  13050. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13051. { hp1 may not be the immediate next instruction under -O3 }
  13052. RemoveCurrentp(p)
  13053. else
  13054. RemoveCurrentp(p, hp1);
  13055. end;
  13056. Result := True;
  13057. Exit;
  13058. end;
  13059. { Change:
  13060. addl/q $x,%reg1
  13061. movl/q %reg1,%reg2
  13062. To:
  13063. leal/q $x(%reg1),%reg2
  13064. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13065. Breaks the dependency chain.
  13066. }
  13067. if (taicpu(p).oper[0]^.typ = top_const) and
  13068. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13069. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13070. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13071. (
  13072. { Instructions are guaranteed to be adjacent on -O2 and under }
  13073. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13074. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13075. ) then
  13076. begin
  13077. TransferUsedRegs(TmpUsedRegs);
  13078. hp2 := p;
  13079. repeat
  13080. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13081. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13082. if (
  13083. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  13084. not (cs_opt_size in current_settings.optimizerswitches) or
  13085. (
  13086. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13087. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13088. )
  13089. ) then
  13090. begin
  13091. { Change the MOV instruction to a LEA instruction, and update the
  13092. first operand }
  13093. reference_reset(NewRef, 1, []);
  13094. NewRef.base := taicpu(p).oper[1]^.reg;
  13095. NewRef.scalefactor := 1;
  13096. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  13097. taicpu(hp1).opcode := A_LEA;
  13098. taicpu(hp1).loadref(0, NewRef);
  13099. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13100. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13101. begin
  13102. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13103. { Move what is now the LEA instruction to before the ADD instruction }
  13104. Asml.Remove(hp1);
  13105. Asml.InsertBefore(hp1, p);
  13106. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13107. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  13108. p := hp1;
  13109. end
  13110. else
  13111. begin
  13112. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13113. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  13114. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13115. { hp1 may not be the immediate next instruction under -O3 }
  13116. RemoveCurrentp(p)
  13117. else
  13118. RemoveCurrentp(p, hp1);
  13119. end;
  13120. Result := True;
  13121. end;
  13122. end;
  13123. end;
  13124. end;
  13125. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  13126. var
  13127. SubReg: TSubRegister;
  13128. begin
  13129. Result:=false;
  13130. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  13131. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13132. with taicpu(p).oper[0]^.ref^ do
  13133. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  13134. begin
  13135. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  13136. begin
  13137. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  13138. taicpu(p).opcode := A_ADD;
  13139. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  13140. Result := True;
  13141. end
  13142. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  13143. begin
  13144. if (base <> NR_NO) then
  13145. begin
  13146. if (scalefactor <= 1) then
  13147. begin
  13148. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  13149. taicpu(p).opcode := A_ADD;
  13150. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  13151. Result := True;
  13152. end;
  13153. end
  13154. else
  13155. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  13156. if (scalefactor in [2, 4, 8]) then
  13157. begin
  13158. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  13159. taicpu(p).loadconst(0, BsrByte(scalefactor));
  13160. taicpu(p).opcode := A_SHL;
  13161. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  13162. Result := True;
  13163. end;
  13164. end;
  13165. end;
  13166. end;
  13167. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  13168. var
  13169. hp1, hp2: tai;
  13170. NewRef: TReference;
  13171. Distance: Cardinal;
  13172. TempTracking: TAllUsedRegs;
  13173. begin
  13174. Result := False;
  13175. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  13176. MatchOpType(taicpu(p),top_const,top_reg) then
  13177. begin
  13178. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  13179. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  13180. (hp1.typ <> ait_instruction) or
  13181. not
  13182. (
  13183. (cs_opt_level3 in current_settings.optimizerswitches) or
  13184. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  13185. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  13186. ) then
  13187. Exit;
  13188. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  13189. subq $x, %rax
  13190. movq %rax, %rdx
  13191. sarq $63, %rdx
  13192. (%rax still in use)
  13193. ...letting OptPass2SUB run its course (and without -Os) will produce:
  13194. leaq $-x(%rax),%rdx
  13195. movq $x, %rax
  13196. sarq $63, %rdx
  13197. ...which is okay since it breaks the dependency chain between
  13198. subq and movq, but if OptPass2MOV is called first:
  13199. subq $x, %rax
  13200. cqto
  13201. ...which is better in all ways, taking only 2 cycles to execute
  13202. and much smaller in code size.
  13203. }
  13204. { The extra register tracking is quite strenuous }
  13205. if (cs_opt_level2 in current_settings.optimizerswitches) and
  13206. MatchInstruction(hp1, A_MOV, []) then
  13207. begin
  13208. { Update the register tracking to the MOV instruction }
  13209. CopyUsedRegs(TempTracking);
  13210. hp2 := p;
  13211. repeat
  13212. UpdateUsedRegs(tai(hp2.Next));
  13213. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13214. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  13215. OptPass2SUB get called again }
  13216. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  13217. begin
  13218. { Reset the tracking to the current instruction }
  13219. RestoreUsedRegs(TempTracking);
  13220. ReleaseUsedRegs(TempTracking);
  13221. Result := True;
  13222. Exit;
  13223. end;
  13224. { Reset the tracking to the current instruction }
  13225. RestoreUsedRegs(TempTracking);
  13226. ReleaseUsedRegs(TempTracking);
  13227. { If OptPass2MOV returned True, we don't need to set Result to
  13228. True if hp1 didn't change because the SUB instruction didn't
  13229. get modified and we'll be evaluating hp1 again when the
  13230. peephole optimizer reaches it }
  13231. end;
  13232. { Change:
  13233. subl/q $x,%reg1
  13234. movl/q %reg1,%reg2
  13235. To:
  13236. leal/q $-x(%reg1),%reg2
  13237. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  13238. Breaks the dependency chain and potentially permits the removal of
  13239. a CMP instruction if one follows.
  13240. }
  13241. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  13242. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13243. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  13244. (
  13245. { Instructions are guaranteed to be adjacent on -O2 and under }
  13246. not (cs_opt_level3 in current_settings.optimizerswitches) or
  13247. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  13248. ) then
  13249. begin
  13250. TransferUsedRegs(TmpUsedRegs);
  13251. hp2 := p;
  13252. repeat
  13253. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13254. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13255. if (
  13256. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  13257. not (cs_opt_size in current_settings.optimizerswitches) or
  13258. (
  13259. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  13260. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  13261. )
  13262. ) then
  13263. begin
  13264. { Change the MOV instruction to a LEA instruction, and update the
  13265. first operand }
  13266. reference_reset(NewRef, 1, []);
  13267. NewRef.base := taicpu(p).oper[1]^.reg;
  13268. NewRef.scalefactor := 1;
  13269. NewRef.offset := -taicpu(p).oper[0]^.val;
  13270. taicpu(hp1).opcode := A_LEA;
  13271. taicpu(hp1).loadref(0, NewRef);
  13272. TransferUsedRegs(TmpUsedRegs);
  13273. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13274. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  13275. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13276. begin
  13277. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  13278. { Move what is now the LEA instruction to before the SUB instruction }
  13279. Asml.Remove(hp1);
  13280. Asml.InsertBefore(hp1, p);
  13281. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13282. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  13283. p := hp1;
  13284. end
  13285. else
  13286. begin
  13287. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  13288. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  13289. if (cs_opt_level3 in current_settings.optimizerswitches) then
  13290. { hp1 may not be the immediate next instruction under -O3 }
  13291. RemoveCurrentp(p)
  13292. else
  13293. RemoveCurrentp(p, hp1);
  13294. end;
  13295. Result := True;
  13296. end;
  13297. end;
  13298. end;
  13299. end;
  13300. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  13301. begin
  13302. { we can skip all instructions not messing with the stack pointer }
  13303. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  13304. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  13305. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  13306. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  13307. ({(taicpu(hp1).ops=0) or }
  13308. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  13309. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  13310. ) and }
  13311. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  13312. )
  13313. ) do
  13314. GetNextInstruction(hp1,hp1);
  13315. Result:=assigned(hp1);
  13316. end;
  13317. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  13318. var
  13319. hp1, hp2, hp3, hp4, hp5: tai;
  13320. begin
  13321. Result:=false;
  13322. hp5:=nil;
  13323. { replace
  13324. leal(q) x(<stackpointer>),<stackpointer>
  13325. call procname
  13326. leal(q) -x(<stackpointer>),<stackpointer>
  13327. ret
  13328. by
  13329. jmp procname
  13330. but do it only on level 4 because it destroys stack back traces
  13331. }
  13332. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13333. MatchOpType(taicpu(p),top_ref,top_reg) and
  13334. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13335. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13336. { the -8 or -24 are not required, but bail out early if possible,
  13337. higher values are unlikely }
  13338. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13339. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13340. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13341. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13342. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13343. GetNextInstruction(p, hp1) and
  13344. { Take a copy of hp1 }
  13345. SetAndTest(hp1, hp4) and
  13346. { trick to skip label }
  13347. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13348. SkipSimpleInstructions(hp1) and
  13349. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13350. GetNextInstruction(hp1, hp2) and
  13351. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13352. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13353. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13354. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13355. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13356. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13357. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13358. { Segment register will be NR_NO }
  13359. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13360. GetNextInstruction(hp2, hp3) and
  13361. { trick to skip label }
  13362. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13363. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13364. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13365. SetAndTest(hp3,hp5) and
  13366. GetNextInstruction(hp3,hp3) and
  13367. MatchInstruction(hp3,A_RET,[S_NO])
  13368. )
  13369. ) and
  13370. (taicpu(hp3).ops=0) then
  13371. begin
  13372. taicpu(hp1).opcode := A_JMP;
  13373. taicpu(hp1).is_jmp := true;
  13374. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13375. RemoveCurrentP(p, hp4);
  13376. RemoveInstruction(hp2);
  13377. RemoveInstruction(hp3);
  13378. if Assigned(hp5) then
  13379. begin
  13380. AsmL.Remove(hp5);
  13381. ASmL.InsertBefore(hp5,hp1)
  13382. end;
  13383. Result:=true;
  13384. end;
  13385. end;
  13386. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13387. {$ifdef x86_64}
  13388. var
  13389. hp1, hp2, hp3, hp4, hp5: tai;
  13390. {$endif x86_64}
  13391. begin
  13392. Result:=false;
  13393. {$ifdef x86_64}
  13394. hp5:=nil;
  13395. { replace
  13396. push %rax
  13397. call procname
  13398. pop %rcx
  13399. ret
  13400. by
  13401. jmp procname
  13402. but do it only on level 4 because it destroys stack back traces
  13403. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13404. for all supported calling conventions
  13405. }
  13406. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13407. MatchOpType(taicpu(p),top_reg) and
  13408. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13409. GetNextInstruction(p, hp1) and
  13410. { Take a copy of hp1 }
  13411. SetAndTest(hp1, hp4) and
  13412. { trick to skip label }
  13413. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13414. SkipSimpleInstructions(hp1) and
  13415. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13416. GetNextInstruction(hp1, hp2) and
  13417. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13418. MatchOpType(taicpu(hp2),top_reg) and
  13419. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13420. GetNextInstruction(hp2, hp3) and
  13421. { trick to skip label }
  13422. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13423. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13424. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13425. SetAndTest(hp3,hp5) and
  13426. GetNextInstruction(hp3,hp3) and
  13427. MatchInstruction(hp3,A_RET,[S_NO])
  13428. )
  13429. ) and
  13430. (taicpu(hp3).ops=0) then
  13431. begin
  13432. taicpu(hp1).opcode := A_JMP;
  13433. taicpu(hp1).is_jmp := true;
  13434. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13435. RemoveCurrentP(p, hp4);
  13436. RemoveInstruction(hp2);
  13437. RemoveInstruction(hp3);
  13438. if Assigned(hp5) then
  13439. begin
  13440. AsmL.Remove(hp5);
  13441. ASmL.InsertBefore(hp5,hp1)
  13442. end;
  13443. Result:=true;
  13444. end;
  13445. {$endif x86_64}
  13446. end;
  13447. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13448. var
  13449. Value, RegName: string;
  13450. begin
  13451. Result:=false;
  13452. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13453. begin
  13454. case taicpu(p).oper[0]^.val of
  13455. 0:
  13456. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13457. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13458. begin
  13459. { change "mov $0,%reg" into "xor %reg,%reg" }
  13460. taicpu(p).opcode := A_XOR;
  13461. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13462. Result := True;
  13463. {$ifdef x86_64}
  13464. end
  13465. else if (taicpu(p).opsize = S_Q) then
  13466. begin
  13467. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13468. { The actual optimization }
  13469. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13470. taicpu(p).changeopsize(S_L);
  13471. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13472. Result := True;
  13473. end;
  13474. $1..$FFFFFFFF:
  13475. begin
  13476. { Code size reduction by J. Gareth "Kit" Moreton }
  13477. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13478. case taicpu(p).opsize of
  13479. S_Q:
  13480. begin
  13481. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13482. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13483. { The actual optimization }
  13484. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13485. taicpu(p).changeopsize(S_L);
  13486. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13487. Result := True;
  13488. end;
  13489. else
  13490. { Do nothing };
  13491. end;
  13492. {$endif x86_64}
  13493. end;
  13494. -1:
  13495. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13496. if (cs_opt_size in current_settings.optimizerswitches) and
  13497. (taicpu(p).opsize <> S_B) and
  13498. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13499. begin
  13500. { change "mov $-1,%reg" into "or $-1,%reg" }
  13501. { NOTES:
  13502. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13503. - This operation creates a false dependency on the register, so only do it when optimising for size
  13504. - 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
  13505. }
  13506. taicpu(p).opcode := A_OR;
  13507. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13508. Result := True;
  13509. end;
  13510. else
  13511. { Do nothing };
  13512. end;
  13513. end;
  13514. end;
  13515. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13516. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13517. begin
  13518. Result := False;
  13519. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13520. Exit;
  13521. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13522. so don't bother optimising }
  13523. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13524. Exit;
  13525. if (taicpu(p).oper[0]^.typ <> top_const) or
  13526. { If the value can fit into an 8-bit signed integer, a smaller
  13527. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13528. falls within this range }
  13529. (
  13530. (taicpu(p).oper[0]^.val > -128) and
  13531. (taicpu(p).oper[0]^.val <= 127)
  13532. ) then
  13533. Exit;
  13534. { If we're optimising for size, this is acceptable }
  13535. if (cs_opt_size in current_settings.optimizerswitches) then
  13536. Exit(True);
  13537. if (taicpu(p).oper[1]^.typ = top_reg) and
  13538. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13539. Exit(True);
  13540. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13541. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13542. Exit(True);
  13543. end;
  13544. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13545. var
  13546. hp1: tai;
  13547. Value: TCGInt;
  13548. begin
  13549. Result := False;
  13550. if MatchOpType(taicpu(p), top_const, top_reg) then
  13551. begin
  13552. { Detect:
  13553. andw x, %ax (0 <= x < $8000)
  13554. ...
  13555. movzwl %ax,%eax
  13556. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13557. }
  13558. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13559. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13560. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13561. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13562. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13563. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13564. begin
  13565. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13566. taicpu(hp1).opcode := A_CWDE;
  13567. taicpu(hp1).clearop(0);
  13568. taicpu(hp1).clearop(1);
  13569. taicpu(hp1).ops := 0;
  13570. { A change was made, but not with p, so don't set Result, but
  13571. notify the compiler that a change was made }
  13572. Include(OptsToCheck, aoc_ForceNewIteration);
  13573. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13574. end;
  13575. end;
  13576. { If "not x" is a power of 2 (popcnt = 1), change:
  13577. and $x, %reg/ref
  13578. To:
  13579. btr lb(x), %reg/ref
  13580. }
  13581. if IsBTXAcceptable(p) and
  13582. (
  13583. { Make sure a TEST doesn't follow that plays with the register }
  13584. not GetNextInstruction(p, hp1) or
  13585. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13586. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13587. ) then
  13588. begin
  13589. {$push}{$R-}{$Q-}
  13590. { Value is a sign-extended 32-bit integer - just correct it
  13591. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13592. checks to see if this operand is an immediate. }
  13593. Value := not taicpu(p).oper[0]^.val;
  13594. {$pop}
  13595. {$ifdef x86_64}
  13596. if taicpu(p).opsize = S_L then
  13597. {$endif x86_64}
  13598. Value := Value and $FFFFFFFF;
  13599. if (PopCnt(QWord(Value)) = 1) then
  13600. begin
  13601. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13602. taicpu(p).opcode := A_BTR;
  13603. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13604. Result := True;
  13605. Exit;
  13606. end;
  13607. end;
  13608. end;
  13609. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13610. begin
  13611. Result := False;
  13612. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13613. Exit;
  13614. { Convert:
  13615. movswl %ax,%eax -> cwtl
  13616. movslq %eax,%rax -> cdqe
  13617. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13618. refer to the same opcode and depends only on the assembler's
  13619. current operand-size attribute. [Kit]
  13620. }
  13621. with taicpu(p) do
  13622. case opsize of
  13623. S_WL:
  13624. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13625. begin
  13626. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13627. opcode := A_CWDE;
  13628. clearop(0);
  13629. clearop(1);
  13630. ops := 0;
  13631. Result := True;
  13632. end;
  13633. {$ifdef x86_64}
  13634. S_LQ:
  13635. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13636. begin
  13637. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13638. opcode := A_CDQE;
  13639. clearop(0);
  13640. clearop(1);
  13641. ops := 0;
  13642. Result := True;
  13643. end;
  13644. {$endif x86_64}
  13645. else
  13646. ;
  13647. end;
  13648. end;
  13649. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13650. var
  13651. hp1, hp2: tai;
  13652. IdentityMask, Shift: TCGInt;
  13653. LimitSize: Topsize;
  13654. DoNotMerge: Boolean;
  13655. begin
  13656. Result := False;
  13657. { All these optimisations work on "shr const,%reg" }
  13658. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13659. Exit;
  13660. DoNotMerge := False;
  13661. Shift := taicpu(p).oper[0]^.val;
  13662. LimitSize := taicpu(p).opsize;
  13663. hp1 := p;
  13664. repeat
  13665. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13666. Break;
  13667. { Detect:
  13668. shr x, %reg
  13669. and y, %reg
  13670. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13671. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13672. }
  13673. case taicpu(hp1).opcode of
  13674. A_AND:
  13675. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13676. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13677. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13678. begin
  13679. { Make sure the FLAGS register isn't in use }
  13680. TransferUsedRegs(TmpUsedRegs);
  13681. hp2 := p;
  13682. repeat
  13683. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13684. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13685. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13686. begin
  13687. { Generate the identity mask }
  13688. case taicpu(p).opsize of
  13689. S_B:
  13690. IdentityMask := $FF shr Shift;
  13691. S_W:
  13692. IdentityMask := $FFFF shr Shift;
  13693. S_L:
  13694. IdentityMask := $FFFFFFFF shr Shift;
  13695. {$ifdef x86_64}
  13696. S_Q:
  13697. { We need to force the operands to be unsigned 64-bit
  13698. integers otherwise the wrong value is generated }
  13699. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13700. {$endif x86_64}
  13701. else
  13702. InternalError(2022081501);
  13703. end;
  13704. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13705. begin
  13706. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13707. { All the possible 1 bits are covered, so we can remove the AND }
  13708. hp2 := tai(hp1.Previous);
  13709. RemoveInstruction(hp1);
  13710. { p wasn't actually changed, so don't set Result to True,
  13711. but a change was nonetheless made elsewhere }
  13712. Include(OptsToCheck, aoc_ForceNewIteration);
  13713. { Do another pass in case other AND or MOVZX instructions
  13714. follow }
  13715. hp1 := hp2;
  13716. Continue;
  13717. end;
  13718. end;
  13719. end;
  13720. A_TEST, A_CMP, A_Jcc:
  13721. { Skip over conditional jumps and relevant comparisons }
  13722. Continue;
  13723. A_MOVZX:
  13724. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13725. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13726. begin
  13727. { Since the original register is being read as is, subsequent
  13728. SHRs must not be merged at this point }
  13729. DoNotMerge := True;
  13730. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13731. begin
  13732. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13733. begin
  13734. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13735. { All the possible 1 bits are covered, so we can remove the AND }
  13736. hp2 := tai(hp1.Previous);
  13737. RemoveInstruction(hp1);
  13738. hp1 := hp2;
  13739. end
  13740. else { Different register target }
  13741. begin
  13742. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13743. taicpu(hp1).opcode := A_MOV;
  13744. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13745. case taicpu(hp1).opsize of
  13746. S_BW:
  13747. taicpu(hp1).opsize := S_W;
  13748. S_BL, S_WL:
  13749. taicpu(hp1).opsize := S_L;
  13750. else
  13751. InternalError(2022081503);
  13752. end;
  13753. end;
  13754. end
  13755. else if (Shift > 0) and
  13756. (taicpu(p).opsize = S_W) and
  13757. (taicpu(hp1).opsize = S_WL) and
  13758. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13759. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13760. begin
  13761. { Detect:
  13762. shr x, %ax (x > 0)
  13763. ...
  13764. movzwl %ax,%eax
  13765. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13766. }
  13767. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13768. taicpu(hp1).opcode := A_CWDE;
  13769. taicpu(hp1).clearop(0);
  13770. taicpu(hp1).clearop(1);
  13771. taicpu(hp1).ops := 0;
  13772. end;
  13773. { Move onto the next instruction }
  13774. Continue;
  13775. end;
  13776. A_SHL, A_SAL, A_SHR:
  13777. if (taicpu(hp1).opsize <= LimitSize) and
  13778. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13779. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13780. begin
  13781. { Make sure the sizes don't exceed the register size limit
  13782. (measured by the shift value falling below the limit) }
  13783. if taicpu(hp1).opsize < LimitSize then
  13784. LimitSize := taicpu(hp1).opsize;
  13785. if taicpu(hp1).opcode = A_SHR then
  13786. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13787. else
  13788. begin
  13789. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13790. DoNotMerge := True;
  13791. end;
  13792. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13793. Break;
  13794. { Since we've established that the combined shift is within
  13795. limits, we can actually combine the adjacent SHR
  13796. instructions even if they're different sizes }
  13797. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13798. begin
  13799. hp2 := tai(hp1.Previous);
  13800. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13801. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13802. RemoveInstruction(hp1);
  13803. hp1 := hp2;
  13804. end;
  13805. { Move onto the next instruction }
  13806. Continue;
  13807. end;
  13808. else
  13809. ;
  13810. end;
  13811. Break;
  13812. until False;
  13813. { Detect the following (looking backwards):
  13814. shr %cl,%reg
  13815. shr x, %reg
  13816. Swap the two SHR instructions to minimise a pipeline stall.
  13817. }
  13818. if GetLastInstruction(p, hp1) and
  13819. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13820. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13821. { First operand will be %cl }
  13822. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13823. { Just to be sure }
  13824. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13825. begin
  13826. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13827. { Moving the entries this way ensures the register tracking remains correct }
  13828. Asml.Remove(p);
  13829. Asml.InsertBefore(p, hp1);
  13830. p := hp1;
  13831. { Don't set Result to True because the current instruction is now
  13832. "shr %cl,%reg" and there's nothing more we can do with it }
  13833. end;
  13834. end;
  13835. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13836. var
  13837. hp1, hp2: tai;
  13838. Opposite, SecondOpposite: TAsmOp;
  13839. NewCond: TAsmCond;
  13840. begin
  13841. Result := False;
  13842. { Change:
  13843. add/sub 128,(dest)
  13844. To:
  13845. sub/add -128,(dest)
  13846. This generaally takes fewer bytes to encode because -128 can be stored
  13847. in a signed byte, whereas +128 cannot.
  13848. }
  13849. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13850. begin
  13851. if taicpu(p).opcode = A_ADD then
  13852. Opposite := A_SUB
  13853. else
  13854. Opposite := A_ADD;
  13855. { Be careful if the flags are in use, because the CF flag inverts
  13856. when changing from ADD to SUB and vice versa }
  13857. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13858. GetNextInstruction(p, hp1) then
  13859. begin
  13860. TransferUsedRegs(TmpUsedRegs);
  13861. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13862. hp2 := hp1;
  13863. { Scan ahead to check if everything's safe }
  13864. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13865. begin
  13866. if (hp1.typ <> ait_instruction) then
  13867. { Probably unsafe since the flags are still in use }
  13868. Exit;
  13869. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13870. { Stop searching at an unconditional jump }
  13871. Break;
  13872. if not
  13873. (
  13874. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13875. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13876. ) and
  13877. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13878. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13879. Exit;
  13880. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13881. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13882. { Move to the next instruction }
  13883. GetNextInstruction(hp1, hp1);
  13884. end;
  13885. while Assigned(hp2) and (hp2 <> hp1) do
  13886. begin
  13887. NewCond := C_None;
  13888. case taicpu(hp2).condition of
  13889. C_A, C_NBE:
  13890. NewCond := C_BE;
  13891. C_B, C_C, C_NAE:
  13892. NewCond := C_AE;
  13893. C_AE, C_NB, C_NC:
  13894. NewCond := C_B;
  13895. C_BE, C_NA:
  13896. NewCond := C_A;
  13897. else
  13898. { No change needed };
  13899. end;
  13900. if NewCond <> C_None then
  13901. begin
  13902. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13903. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13904. taicpu(hp2).condition := NewCond;
  13905. end
  13906. else
  13907. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13908. begin
  13909. { Because of the flipping of the carry bit, to ensure
  13910. the operation remains equivalent, ADC becomes SBB
  13911. and vice versa, and the constant is not-inverted.
  13912. If multiple ADCs or SBBs appear in a row, each one
  13913. changed causes the carry bit to invert, so they all
  13914. need to be flipped }
  13915. if taicpu(hp2).opcode = A_ADC then
  13916. SecondOpposite := A_SBB
  13917. else
  13918. SecondOpposite := A_ADC;
  13919. if taicpu(hp2).oper[0]^.typ <> top_const then
  13920. { Should have broken out of this optimisation already }
  13921. InternalError(2021112901);
  13922. 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]^) + ' -> ' +
  13923. 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);
  13924. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13925. taicpu(hp2).opcode := SecondOpposite;
  13926. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13927. end;
  13928. { Move to the next instruction }
  13929. GetNextInstruction(hp2, hp2);
  13930. end;
  13931. if (hp2 <> hp1) then
  13932. InternalError(2021111501);
  13933. end;
  13934. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13935. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13936. taicpu(p).opcode := Opposite;
  13937. taicpu(p).oper[0]^.val := -128;
  13938. { No further optimisations can be made on this instruction, so move
  13939. onto the next one to save time }
  13940. p := tai(p.Next);
  13941. UpdateUsedRegs(p);
  13942. Result := True;
  13943. Exit;
  13944. end;
  13945. { Detect:
  13946. add/sub %reg2,(dest)
  13947. add/sub x, (dest)
  13948. (dest can be a register or a reference)
  13949. Swap the instructions to minimise a pipeline stall. This reverses the
  13950. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13951. optimisations could be made.
  13952. }
  13953. if (taicpu(p).oper[0]^.typ = top_reg) and
  13954. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13955. (
  13956. (
  13957. (taicpu(p).oper[1]^.typ = top_reg) and
  13958. { We can try searching further ahead if we're writing to a register }
  13959. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13960. ) or
  13961. (
  13962. (taicpu(p).oper[1]^.typ = top_ref) and
  13963. GetNextInstruction(p, hp1)
  13964. )
  13965. ) and
  13966. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13967. (taicpu(hp1).oper[0]^.typ = top_const) and
  13968. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13969. begin
  13970. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13971. TransferUsedRegs(TmpUsedRegs);
  13972. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13973. hp2 := p;
  13974. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13975. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13976. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13977. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13978. begin
  13979. asml.remove(hp1);
  13980. asml.InsertBefore(hp1, p);
  13981. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13982. Result := True;
  13983. end;
  13984. end;
  13985. end;
  13986. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13987. var
  13988. hp1: tai;
  13989. begin
  13990. Result:=false;
  13991. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13992. while GetNextInstruction(p, hp1) and
  13993. TrySwapMovCmp(p, hp1) do
  13994. begin
  13995. if MatchInstruction(hp1, A_MOV, []) then
  13996. begin
  13997. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13998. begin
  13999. { A little hacky, but since CMP doesn't read the flags, only
  14000. modify them, it's safe if they get scrambled by MOV -> XOR }
  14001. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14002. Result := PostPeepholeOptMov(hp1);
  14003. {$ifdef x86_64}
  14004. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14005. { Used to shrink instruction size }
  14006. PostPeepholeOptXor(hp1);
  14007. {$endif x86_64}
  14008. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14009. end
  14010. else
  14011. begin
  14012. Result := PostPeepholeOptMov(hp1);
  14013. {$ifdef x86_64}
  14014. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14015. { Used to shrink instruction size }
  14016. PostPeepholeOptXor(hp1);
  14017. {$endif x86_64}
  14018. end;
  14019. end;
  14020. { Enabling this flag is actually a null operation, but it marks
  14021. the code as 'modified' during this pass }
  14022. Include(OptsToCheck, aoc_ForceNewIteration);
  14023. end;
  14024. { change "cmp $0, %reg" to "test %reg, %reg" }
  14025. if MatchOpType(taicpu(p),top_const,top_reg) and
  14026. (taicpu(p).oper[0]^.val = 0) then
  14027. begin
  14028. taicpu(p).opcode := A_TEST;
  14029. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  14030. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  14031. Result:=true;
  14032. end;
  14033. end;
  14034. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  14035. var
  14036. IsTestConstX, IsValid : Boolean;
  14037. hp1,hp2 : tai;
  14038. begin
  14039. Result:=false;
  14040. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  14041. if (taicpu(p).opcode = A_TEST) then
  14042. while GetNextInstruction(p, hp1) and
  14043. TrySwapMovCmp(p, hp1) do
  14044. begin
  14045. if MatchInstruction(hp1, A_MOV, []) then
  14046. begin
  14047. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14048. begin
  14049. { A little hacky, but since TEST doesn't read the flags, only
  14050. modify them, it's safe if they get scrambled by MOV -> XOR }
  14051. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14052. Result := PostPeepholeOptMov(hp1);
  14053. {$ifdef x86_64}
  14054. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14055. { Used to shrink instruction size }
  14056. PostPeepholeOptXor(hp1);
  14057. {$endif x86_64}
  14058. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  14059. end
  14060. else
  14061. begin
  14062. Result := PostPeepholeOptMov(hp1);
  14063. {$ifdef x86_64}
  14064. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  14065. { Used to shrink instruction size }
  14066. PostPeepholeOptXor(hp1);
  14067. {$endif x86_64}
  14068. end;
  14069. end;
  14070. { Enabling this flag is actually a null operation, but it marks
  14071. the code as 'modified' during this pass }
  14072. Include(OptsToCheck, aoc_ForceNewIteration);
  14073. end;
  14074. { If x is a power of 2 (popcnt = 1), change:
  14075. or $x, %reg/ref
  14076. To:
  14077. bts lb(x), %reg/ref
  14078. }
  14079. if (taicpu(p).opcode = A_OR) and
  14080. IsBTXAcceptable(p) and
  14081. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14082. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14083. (
  14084. { Don't optimise if a test instruction follows }
  14085. not GetNextInstruction(p, hp1) or
  14086. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14087. ) then
  14088. begin
  14089. 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);
  14090. taicpu(p).opcode := A_BTS;
  14091. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14092. Result := True;
  14093. Exit;
  14094. end;
  14095. { If x is a power of 2 (popcnt = 1), change:
  14096. test $x, %reg/ref
  14097. je / sete / cmove (or jne / setne)
  14098. To:
  14099. bt lb(x), %reg/ref
  14100. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  14101. }
  14102. if (taicpu(p).opcode = A_TEST) and
  14103. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  14104. (taicpu(p).oper[0]^.typ = top_const) and
  14105. (
  14106. (cs_opt_size in current_settings.optimizerswitches) or
  14107. (
  14108. (taicpu(p).oper[1]^.typ = top_reg) and
  14109. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14110. ) or
  14111. (
  14112. (taicpu(p).oper[1]^.typ <> top_reg) and
  14113. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  14114. )
  14115. ) and
  14116. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14117. { For sizes less than S_L, the byte size is equal or larger with BT,
  14118. so don't bother optimising }
  14119. (taicpu(p).opsize >= S_L) then
  14120. begin
  14121. IsValid := True;
  14122. { Check the next set of instructions, watching the FLAGS register
  14123. and the conditions used }
  14124. TransferUsedRegs(TmpUsedRegs);
  14125. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14126. hp1 := p;
  14127. hp2 := nil;
  14128. while GetNextInstruction(hp1, hp1) do
  14129. begin
  14130. if not Assigned(hp2) then
  14131. { The first instruction after TEST }
  14132. hp2 := hp1;
  14133. if (hp1.typ <> ait_instruction) then
  14134. begin
  14135. { If the flags are no longer in use, everything is fine }
  14136. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14137. IsValid := False;
  14138. Break;
  14139. end;
  14140. case taicpu(hp1).condition of
  14141. C_None:
  14142. begin
  14143. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  14144. { Something is not quite normal, so play safe and don't change }
  14145. IsValid := False;
  14146. Break;
  14147. end;
  14148. C_E, C_Z, C_NE, C_NZ:
  14149. { This is fine };
  14150. else
  14151. begin
  14152. { Unsupported condition }
  14153. IsValid := False;
  14154. Break;
  14155. end;
  14156. end;
  14157. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  14158. end;
  14159. if IsValid then
  14160. begin
  14161. while hp2 <> hp1 do
  14162. begin
  14163. case taicpu(hp2).condition of
  14164. C_Z, C_E:
  14165. taicpu(hp2).condition := C_NC;
  14166. C_NZ, C_NE:
  14167. taicpu(hp2).condition := C_C;
  14168. else
  14169. { Should not get this by this point }
  14170. InternalError(2022110701);
  14171. end;
  14172. GetNextInstruction(hp2, hp2);
  14173. end;
  14174. 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);
  14175. taicpu(p).opcode := A_BT;
  14176. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14177. Result := True;
  14178. Exit;
  14179. end;
  14180. end;
  14181. { removes the line marked with (x) from the sequence
  14182. and/or/xor/add/sub/... $x, %y
  14183. test/or %y, %y | test $-1, %y (x)
  14184. j(n)z _Label
  14185. as the first instruction already adjusts the ZF
  14186. %y operand may also be a reference }
  14187. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  14188. MatchOperand(taicpu(p).oper[0]^,-1);
  14189. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  14190. GetLastInstruction(p, hp1) and
  14191. (tai(hp1).typ = ait_instruction) and
  14192. GetNextInstruction(p,hp2) and
  14193. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  14194. case taicpu(hp1).opcode Of
  14195. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  14196. { These two instructions set the zero flag if the result is zero }
  14197. A_POPCNT, A_LZCNT:
  14198. begin
  14199. if (
  14200. { With POPCNT, an input of zero will set the zero flag
  14201. because the population count of zero is zero }
  14202. (taicpu(hp1).opcode = A_POPCNT) and
  14203. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  14204. (
  14205. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  14206. { Faster than going through the second half of the 'or'
  14207. condition below }
  14208. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  14209. )
  14210. ) or (
  14211. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  14212. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14213. { and in case of carry for A(E)/B(E)/C/NC }
  14214. (
  14215. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  14216. (
  14217. (taicpu(hp1).opcode <> A_ADD) and
  14218. (taicpu(hp1).opcode <> A_SUB) and
  14219. (taicpu(hp1).opcode <> A_LZCNT)
  14220. )
  14221. )
  14222. ) then
  14223. begin
  14224. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  14225. RemoveCurrentP(p, hp2);
  14226. Result:=true;
  14227. Exit;
  14228. end;
  14229. end;
  14230. A_SHL, A_SAL, A_SHR, A_SAR:
  14231. begin
  14232. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  14233. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  14234. { therefore, it's only safe to do this optimization for }
  14235. { shifts by a (nonzero) constant }
  14236. (taicpu(hp1).oper[0]^.typ = top_const) and
  14237. (taicpu(hp1).oper[0]^.val <> 0) and
  14238. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14239. { and in case of carry for A(E)/B(E)/C/NC }
  14240. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14241. begin
  14242. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  14243. RemoveCurrentP(p, hp2);
  14244. Result:=true;
  14245. Exit;
  14246. end;
  14247. end;
  14248. A_DEC, A_INC, A_NEG:
  14249. begin
  14250. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  14251. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  14252. { and in case of carry for A(E)/B(E)/C/NC }
  14253. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14254. begin
  14255. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  14256. RemoveCurrentP(p, hp2);
  14257. Result:=true;
  14258. Exit;
  14259. end;
  14260. end;
  14261. A_ANDN, A_BZHI:
  14262. begin
  14263. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14264. { Only the zero and sign flags are consistent with what the result is }
  14265. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  14266. begin
  14267. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  14268. RemoveCurrentP(p, hp2);
  14269. Result:=true;
  14270. Exit;
  14271. end;
  14272. end;
  14273. A_BEXTR:
  14274. begin
  14275. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  14276. { Only the zero flag is set }
  14277. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  14278. begin
  14279. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  14280. RemoveCurrentP(p, hp2);
  14281. Result:=true;
  14282. Exit;
  14283. end;
  14284. end;
  14285. else
  14286. ;
  14287. end; { case }
  14288. { change "test $-1,%reg" into "test %reg,%reg" }
  14289. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  14290. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  14291. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  14292. if MatchInstruction(p, A_OR, []) and
  14293. { Can only match if they're both registers }
  14294. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  14295. begin
  14296. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  14297. taicpu(p).opcode := A_TEST;
  14298. { No need to set Result to True, as we've done all the optimisations we can }
  14299. end;
  14300. end;
  14301. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  14302. var
  14303. hp1,hp3 : tai;
  14304. {$ifndef x86_64}
  14305. hp2 : taicpu;
  14306. {$endif x86_64}
  14307. begin
  14308. Result:=false;
  14309. hp3:=nil;
  14310. {$ifndef x86_64}
  14311. { don't do this on modern CPUs, this really hurts them due to
  14312. broken call/ret pairing }
  14313. if (current_settings.optimizecputype < cpu_Pentium2) and
  14314. not(cs_create_pic in current_settings.moduleswitches) and
  14315. GetNextInstruction(p, hp1) and
  14316. MatchInstruction(hp1,A_JMP,[S_NO]) and
  14317. MatchOpType(taicpu(hp1),top_ref) and
  14318. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  14319. begin
  14320. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14321. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14322. InsertLLItem(p.previous, p, hp2);
  14323. taicpu(p).opcode := A_JMP;
  14324. taicpu(p).is_jmp := true;
  14325. RemoveInstruction(hp1);
  14326. Result:=true;
  14327. end
  14328. else
  14329. {$endif x86_64}
  14330. { replace
  14331. call procname
  14332. ret
  14333. by
  14334. jmp procname
  14335. but do it only on level 4 because it destroys stack back traces
  14336. else if the subroutine is marked as no return, remove the ret
  14337. }
  14338. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14339. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14340. GetNextInstruction(p, hp1) and
  14341. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14342. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14343. SetAndTest(hp1,hp3) and
  14344. GetNextInstruction(hp1,hp1) and
  14345. MatchInstruction(hp1,A_RET,[S_NO])
  14346. )
  14347. ) and
  14348. (taicpu(hp1).ops=0) then
  14349. begin
  14350. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14351. { we might destroy stack alignment here if we do not do a call }
  14352. (target_info.stackalign<=sizeof(SizeUInt)) then
  14353. begin
  14354. taicpu(p).opcode := A_JMP;
  14355. taicpu(p).is_jmp := true;
  14356. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14357. end
  14358. else
  14359. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14360. RemoveInstruction(hp1);
  14361. if Assigned(hp3) then
  14362. begin
  14363. AsmL.Remove(hp3);
  14364. AsmL.InsertBefore(hp3,p)
  14365. end;
  14366. Result:=true;
  14367. end;
  14368. end;
  14369. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14370. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14371. begin
  14372. case OpSize of
  14373. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14374. Result := (Val <= $FF) and (Val >= -128);
  14375. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14376. Result := (Val <= $FFFF) and (Val >= -32768);
  14377. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14378. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14379. else
  14380. Result := True;
  14381. end;
  14382. end;
  14383. var
  14384. hp1, hp2 : tai;
  14385. SizeChange: Boolean;
  14386. PreMessage: string;
  14387. begin
  14388. Result := False;
  14389. if (taicpu(p).oper[0]^.typ = top_reg) and
  14390. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14391. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14392. begin
  14393. { Change (using movzbl %al,%eax as an example):
  14394. movzbl %al, %eax movzbl %al, %eax
  14395. cmpl x, %eax testl %eax,%eax
  14396. To:
  14397. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14398. movzbl %al, %eax movzbl %al, %eax
  14399. Smaller instruction and minimises pipeline stall as the CPU
  14400. doesn't have to wait for the register to get zero-extended. [Kit]
  14401. Also allow if the smaller of the two registers is being checked,
  14402. as this still removes the false dependency.
  14403. }
  14404. if
  14405. (
  14406. (
  14407. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14408. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14409. ) or (
  14410. { If MatchOperand returns True, they must both be registers }
  14411. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14412. )
  14413. ) and
  14414. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14415. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14416. begin
  14417. 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);
  14418. asml.Remove(hp1);
  14419. asml.InsertBefore(hp1, p);
  14420. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14421. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14422. begin
  14423. taicpu(hp1).opcode := A_TEST;
  14424. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14425. end;
  14426. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14427. case taicpu(p).opsize of
  14428. S_BW, S_BL:
  14429. begin
  14430. SizeChange := taicpu(hp1).opsize <> S_B;
  14431. taicpu(hp1).changeopsize(S_B);
  14432. end;
  14433. S_WL:
  14434. begin
  14435. SizeChange := taicpu(hp1).opsize <> S_W;
  14436. taicpu(hp1).changeopsize(S_W);
  14437. end
  14438. else
  14439. InternalError(2020112701);
  14440. end;
  14441. UpdateUsedRegs(tai(p.Next));
  14442. { Check if the register is used aferwards - if not, we can
  14443. remove the movzx instruction completely }
  14444. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14445. begin
  14446. { Hp1 is a better position than p for debugging purposes }
  14447. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14448. RemoveCurrentp(p, hp1);
  14449. Result := True;
  14450. end;
  14451. if SizeChange then
  14452. DebugMsg(SPeepholeOptimization + PreMessage +
  14453. 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)
  14454. else
  14455. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14456. Exit;
  14457. end;
  14458. { Change (using movzwl %ax,%eax as an example):
  14459. movzwl %ax, %eax
  14460. movb %al, (dest) (Register is smaller than read register in movz)
  14461. To:
  14462. movb %al, (dest) (Move one back to avoid a false dependency)
  14463. movzwl %ax, %eax
  14464. }
  14465. if (taicpu(hp1).opcode = A_MOV) and
  14466. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14467. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14468. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14469. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14470. begin
  14471. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14472. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14473. asml.Remove(hp1);
  14474. asml.InsertBefore(hp1, p);
  14475. if taicpu(hp1).oper[1]^.typ = top_reg then
  14476. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14477. { Check if the register is used aferwards - if not, we can
  14478. remove the movzx instruction completely }
  14479. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14480. begin
  14481. { Hp1 is a better position than p for debugging purposes }
  14482. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14483. RemoveCurrentp(p, hp1);
  14484. Result := True;
  14485. end;
  14486. Exit;
  14487. end;
  14488. end;
  14489. end;
  14490. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14491. var
  14492. hp1: tai;
  14493. {$ifdef x86_64}
  14494. PreMessage, RegName: string;
  14495. {$endif x86_64}
  14496. begin
  14497. Result := False;
  14498. { If x is a power of 2 (popcnt = 1), change:
  14499. xor $x, %reg/ref
  14500. To:
  14501. btc lb(x), %reg/ref
  14502. }
  14503. if IsBTXAcceptable(p) and
  14504. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14505. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14506. (
  14507. { Don't optimise if a test instruction follows }
  14508. not GetNextInstruction(p, hp1) or
  14509. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14510. ) then
  14511. begin
  14512. 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);
  14513. taicpu(p).opcode := A_BTC;
  14514. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14515. Result := True;
  14516. Exit;
  14517. end;
  14518. {$ifdef x86_64}
  14519. { Code size reduction by J. Gareth "Kit" Moreton }
  14520. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14521. as this removes the REX prefix }
  14522. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14523. Exit;
  14524. if taicpu(p).oper[0]^.typ <> top_reg then
  14525. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14526. InternalError(2018011500);
  14527. case taicpu(p).opsize of
  14528. S_Q:
  14529. begin
  14530. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14531. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14532. { The actual optimization }
  14533. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14534. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14535. taicpu(p).changeopsize(S_L);
  14536. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14537. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14538. end;
  14539. else
  14540. ;
  14541. end;
  14542. {$endif x86_64}
  14543. end;
  14544. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14545. var
  14546. XReg: TRegister;
  14547. begin
  14548. Result := False;
  14549. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14550. Smaller encoding and slightly faster on some platforms (also works for
  14551. ZMM-sized registers) }
  14552. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14553. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14554. begin
  14555. XReg := taicpu(p).oper[0]^.reg;
  14556. if (taicpu(p).oper[1]^.reg = XReg) then
  14557. begin
  14558. taicpu(p).changeopsize(S_XMM);
  14559. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14560. if (cs_opt_size in current_settings.optimizerswitches) then
  14561. begin
  14562. { Change input registers to %xmm0 to reduce size. Note that
  14563. there's a risk of a false dependency doing this, so only
  14564. optimise for size here }
  14565. XReg := NR_XMM0;
  14566. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14567. end
  14568. else
  14569. begin
  14570. setsubreg(XReg, R_SUBMMX);
  14571. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14572. end;
  14573. taicpu(p).oper[0]^.reg := XReg;
  14574. taicpu(p).oper[1]^.reg := XReg;
  14575. Result := True;
  14576. end;
  14577. end;
  14578. end;
  14579. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14580. var
  14581. OperIdx: Integer;
  14582. begin
  14583. for OperIdx := 0 to p.ops - 1 do
  14584. if p.oper[OperIdx]^.typ = top_ref then
  14585. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14586. end;
  14587. end.