aoptx86.pas 758 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration,
  34. aoc_DoPass2JccOpts
  35. );
  36. TX86AsmOptimizer = class(TAsmOptimizer)
  37. { some optimizations are very expensive to check, so the
  38. pre opt pass can be used to set some flags, depending on the found
  39. instructions if it is worth to check a certain optimization }
  40. OptsToCheck : set of TOptsToCheck;
  41. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  42. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  43. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  44. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  45. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  46. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  47. how many instructions away that Next is from Current is.
  48. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  49. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  50. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  51. potentially allowing further optimisation (although it might need to know if
  52. it crossed a conditional jump. }
  53. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  54. {
  55. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  56. the use of a register by allocs/dealloc, so it can ignore calls.
  57. In the following example, GetNextInstructionUsingReg will return the second movq,
  58. GetNextInstructionUsingRegTrackingUse won't.
  59. movq %rdi,%rax
  60. # Register rdi released
  61. # Register rdi allocated
  62. movq %rax,%rdi
  63. While in this example:
  64. movq %rdi,%rax
  65. call proc
  66. movq %rdi,%rax
  67. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  68. won't.
  69. }
  70. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  71. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  72. { returns true if any of the registers in ref are modified by any
  73. instruction between p1 and p2, or if those instructions write to the
  74. reference }
  75. function RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  76. private
  77. function SkipSimpleInstructions(var hp1: tai): Boolean;
  78. protected
  79. class function IsMOVZXAcceptable: Boolean; static; inline;
  80. function CheckMovMov2MovMov2(const p, hp1: tai): Boolean;
  81. { Attempts to allocate a volatile integer register for use between p and hp,
  82. using AUsedRegs for the current register usage information. Returns NR_NO
  83. if no free register could be found }
  84. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  85. { Attempts to allocate a volatile MM register for use between p and hp,
  86. using AUsedRegs for the current register usage information. Returns NR_NO
  87. if no free register could be found }
  88. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  89. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  90. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  91. { checks whether reading the value in reg1 depends on the value of reg2. This
  92. is very similar to SuperRegisterEquals, except it takes into account that
  93. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  94. depend on the value in AH). }
  95. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  96. { Replaces all references to AOldReg in a memory reference to ANewReg }
  97. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  98. { Replaces all references to AOldReg in an operand to ANewReg }
  99. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  100. { Replaces all references to AOldReg in an instruction to ANewReg,
  101. except where the register is being written }
  102. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  103. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  104. or writes to a global symbol }
  105. class function IsRefSafe(const ref: PReference): Boolean; static;
  106. { Returns true if the given MOV instruction can be safely converted to CMOV }
  107. class function CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean; static;
  108. { Like UpdateUsedRegs, but ignores deallocations }
  109. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  110. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  111. class function IsBTXAcceptable(p : tai) : boolean; static;
  112. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  113. conversion was successful }
  114. function ConvertLEA(const p : taicpu): Boolean;
  115. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  116. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  117. procedure DebugMsg(const s : string; p : tai);inline;
  118. class function IsExitCode(p : tai) : boolean; static;
  119. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  120. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  121. procedure RemoveLastDeallocForFuncRes(p : tai);
  122. function DoArithCombineOpt(var p : tai) : Boolean;
  123. function DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  124. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  125. function HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  126. function PrePeepholeOptSxx(var p : tai) : boolean;
  127. function PrePeepholeOptIMUL(var p : tai) : boolean;
  128. function PrePeepholeOptAND(var p : tai) : boolean;
  129. function OptPass1Test(var p: tai): boolean;
  130. function OptPass1Add(var p: tai): boolean;
  131. function OptPass1AND(var p : tai) : boolean;
  132. function OptPass1CMOVcc(var p: tai): Boolean;
  133. function OptPass1_V_MOVAP(var p : tai) : boolean;
  134. function OptPass1VOP(var p : tai) : boolean;
  135. function OptPass1MOV(var p : tai) : boolean;
  136. function OptPass1Movx(var p : tai) : boolean;
  137. function OptPass1MOVXX(var p : tai) : boolean;
  138. function OptPass1OP(var p : tai) : boolean;
  139. function OptPass1LEA(var p : tai) : boolean;
  140. function OptPass1Sub(var p : tai) : boolean;
  141. function OptPass1SHLSAL(var p : tai) : boolean;
  142. function OptPass1SHR(var p : tai) : boolean;
  143. function OptPass1FSTP(var p : tai) : boolean;
  144. function OptPass1FLD(var p : tai) : boolean;
  145. function OptPass1Cmp(var p : tai) : boolean;
  146. function OptPass1PXor(var p : tai) : boolean;
  147. function OptPass1VPXor(var p: tai): boolean;
  148. function OptPass1Imul(var p : tai) : boolean;
  149. function OptPass1Jcc(var p : tai) : boolean;
  150. function OptPass1SHXX(var p: tai): boolean;
  151. function OptPass1VMOVDQ(var p: tai): Boolean;
  152. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  153. function OptPass1STCCLC(var p: tai): Boolean;
  154. function OptPass2STCCLC(var p: tai): Boolean;
  155. function OptPass2CMOVcc(var p: tai): Boolean;
  156. function OptPass2Movx(var p : tai): Boolean;
  157. function OptPass2MOV(var p : tai) : boolean;
  158. function OptPass2Imul(var p : tai) : boolean;
  159. function OptPass2Jmp(var p : tai) : boolean;
  160. function OptPass2Jcc(var p : tai) : boolean;
  161. function OptPass2Lea(var p: tai): Boolean;
  162. function OptPass2SUB(var p: tai): Boolean;
  163. function OptPass2ADD(var p : tai): Boolean;
  164. function OptPass2SETcc(var p : tai) : boolean;
  165. function OptPass2Cmp(var p: tai): Boolean;
  166. function OptPass2Test(var p: tai): Boolean;
  167. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  168. function PostPeepholeOptMov(var p : tai) : Boolean;
  169. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  170. function PostPeepholeOptXor(var p : tai) : Boolean;
  171. function PostPeepholeOptAnd(var p : tai) : boolean;
  172. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  173. function PostPeepholeOptCmp(var p : tai) : Boolean;
  174. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  175. function PostPeepholeOptCall(var p : tai) : Boolean;
  176. function PostPeepholeOptLea(var p : tai) : Boolean;
  177. function PostPeepholeOptPush(var p: tai): Boolean;
  178. function PostPeepholeOptShr(var p : tai) : boolean;
  179. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  180. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  181. function PostPeepholeOptRET(var p: tai): Boolean;
  182. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  183. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  184. function TrySwapMovOp(var p, hp1: tai): Boolean;
  185. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  186. function TryCmpCMovOpts(var p, hp1: tai) : Boolean;
  187. function TryJccStcClcOpt(var p, hp1: tai): Boolean;
  188. { Processor-dependent reference optimisation }
  189. class procedure OptimizeRefs(var p: taicpu); static;
  190. end;
  191. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  194. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  195. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  196. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  197. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  198. {$if max_operands>2}
  199. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  200. {$endif max_operands>2}
  201. function RefsEqual(const r1, r2: treference): boolean;
  202. { Like RefsEqual, but doesn't compare the offsets }
  203. function RefsAlmostEqual(const r1, r2: treference): boolean;
  204. { Note that Result is set to True if the references COULD overlap but the
  205. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  206. might still overlap because %reg2 could be equal to %reg1-4 }
  207. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  208. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  209. { returns true, if ref is a reference using only the registers passed as base and index
  210. and having an offset }
  211. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  212. implementation
  213. uses
  214. cutils,verbose,
  215. systems,
  216. globals,
  217. cpuinfo,
  218. procinfo,
  219. paramgr,
  220. aasmbase,
  221. aoptbase,aoptutils,
  222. symconst,symsym,
  223. cgx86,
  224. itcpugas;
  225. {$ifndef 8086}
  226. const
  227. MAX_CMOV_INSTRUCTIONS = 4;
  228. MAX_CMOV_REGISTERS = 8;
  229. type
  230. TCMovTrackingState = (tsInvalid, tsSimple, tsDetour, tsBranching,
  231. tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching,
  232. tsProcessed);
  233. { For OptPass2Jcc }
  234. TCMOVTracking = object
  235. private
  236. CMOVScore, ConstCount: LongInt;
  237. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  238. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  239. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  240. ConstSizes: array[0..MAX_CMOV_REGISTERS - 1] of TSubRegister; { May not match ConstRegs if one is shared over multiple CMOVs. }
  241. ConstMovs: array[0..MAX_CMOV_REGISTERS - 1] of tai; { Location of initialisation instruction }
  242. ConstWriteSizes: array[0..first_int_imreg - 1] of TSubRegister; { Largest size of register written. }
  243. fOptimizer: TX86AsmOptimizer;
  244. fLabel: TAsmSymbol;
  245. fInsertionPoint,
  246. fCondition,
  247. fInitialJump,
  248. fFirstMovBlock,
  249. fFirstMovBlockStop,
  250. fSecondJump,
  251. fThirdJump,
  252. fSecondMovBlock,
  253. fSecondMovBlockStop,
  254. fMidLabel,
  255. fEndLabel,
  256. fAllocationRange: tai;
  257. fState: TCMovTrackingState;
  258. function TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  259. function InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  260. function AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  261. public
  262. RegisterTracking: TAllUsedRegs;
  263. constructor Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  264. destructor Done;
  265. procedure Process(out new_p: tai);
  266. property State: TCMovTrackingState read fState;
  267. end;
  268. PCMOVTracking = ^TCMOVTracking;
  269. {$endif 8086}
  270. {$ifdef DEBUG_AOPTCPU}
  271. const
  272. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  273. {$else DEBUG_AOPTCPU}
  274. { Empty strings help the optimizer to remove string concatenations that won't
  275. ever appear to the user on release builds. [Kit] }
  276. const
  277. SPeepholeOptimization = '';
  278. {$endif DEBUG_AOPTCPU}
  279. LIST_STEP_SIZE = 4;
  280. type
  281. TJumpTrackingItem = class(TLinkedListItem)
  282. private
  283. FSymbol: TAsmSymbol;
  284. FRefs: LongInt;
  285. public
  286. constructor Create(ASymbol: TAsmSymbol);
  287. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  288. property Symbol: TAsmSymbol read FSymbol;
  289. property Refs: LongInt read FRefs;
  290. end;
  291. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  292. begin
  293. inherited Create;
  294. FSymbol := ASymbol;
  295. FRefs := 0;
  296. end;
  297. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  298. begin
  299. Inc(FRefs);
  300. end;
  301. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  302. begin
  303. result :=
  304. (instr.typ = ait_instruction) and
  305. (taicpu(instr).opcode = op) and
  306. ((opsize = []) or (taicpu(instr).opsize in opsize));
  307. end;
  308. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  309. begin
  310. result :=
  311. (instr.typ = ait_instruction) and
  312. ((taicpu(instr).opcode = op1) or
  313. (taicpu(instr).opcode = op2)
  314. ) and
  315. ((opsize = []) or (taicpu(instr).opsize in opsize));
  316. end;
  317. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  318. begin
  319. result :=
  320. (instr.typ = ait_instruction) and
  321. ((taicpu(instr).opcode = op1) or
  322. (taicpu(instr).opcode = op2) or
  323. (taicpu(instr).opcode = op3)
  324. ) and
  325. ((opsize = []) or (taicpu(instr).opsize in opsize));
  326. end;
  327. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  328. const opsize : topsizes) : boolean;
  329. var
  330. op : TAsmOp;
  331. begin
  332. result:=false;
  333. if (instr.typ <> ait_instruction) or
  334. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  335. exit;
  336. for op in ops do
  337. begin
  338. if taicpu(instr).opcode = op then
  339. begin
  340. result:=true;
  341. exit;
  342. end;
  343. end;
  344. end;
  345. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  346. begin
  347. result := (oper.typ = top_reg) and (oper.reg = reg);
  348. end;
  349. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  350. begin
  351. result := (oper.typ = top_const) and (oper.val = a);
  352. end;
  353. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  354. begin
  355. result := oper1.typ = oper2.typ;
  356. if result then
  357. case oper1.typ of
  358. top_const:
  359. Result:=oper1.val = oper2.val;
  360. top_reg:
  361. Result:=oper1.reg = oper2.reg;
  362. top_ref:
  363. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  364. else
  365. internalerror(2013102801);
  366. end
  367. end;
  368. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  369. begin
  370. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  371. if result then
  372. case oper1.typ of
  373. top_const:
  374. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  375. top_reg:
  376. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  377. top_ref:
  378. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  379. else
  380. internalerror(2020052401);
  381. end
  382. end;
  383. function RefsEqual(const r1, r2: treference): boolean;
  384. begin
  385. RefsEqual :=
  386. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  387. (r1.relsymbol = r2.relsymbol) and
  388. (r1.segment = r2.segment) and (r1.base = r2.base) and
  389. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  390. (r1.offset = r2.offset) and
  391. (r1.volatility + r2.volatility = []);
  392. end;
  393. function RefsAlmostEqual(const r1, r2: treference): boolean;
  394. begin
  395. RefsAlmostEqual :=
  396. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  397. (r1.relsymbol = r2.relsymbol) and
  398. (r1.segment = r2.segment) and (r1.base = r2.base) and
  399. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  400. { Don't compare the offsets }
  401. (r1.volatility + r2.volatility = []);
  402. end;
  403. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  404. begin
  405. if (r1.symbol<>r2.symbol) then
  406. { If the index registers are different, there's a chance one could
  407. be set so it equals the other symbol }
  408. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  409. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  410. (r1.relsymbol = r2.relsymbol) and
  411. (r1.segment = r2.segment) and (r1.base = r2.base) and
  412. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  413. (r1.volatility + r2.volatility = []) then
  414. { In this case, it all depends on the offsets }
  415. Exit(abs(r1.offset - r2.offset) < Range);
  416. { There's a chance things MIGHT overlap, so take no chances }
  417. Result := True;
  418. end;
  419. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  420. begin
  421. Result:=(ref.offset=0) and
  422. (ref.scalefactor in [0,1]) and
  423. (ref.segment=NR_NO) and
  424. (ref.symbol=nil) and
  425. (ref.relsymbol=nil) and
  426. ((base=NR_INVALID) or
  427. (ref.base=base)) and
  428. ((index=NR_INVALID) or
  429. (ref.index=index)) and
  430. (ref.volatility=[]);
  431. end;
  432. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  433. begin
  434. Result:=(ref.scalefactor in [0,1]) and
  435. (ref.segment=NR_NO) and
  436. (ref.symbol=nil) and
  437. (ref.relsymbol=nil) and
  438. ((base=NR_INVALID) or
  439. (ref.base=base)) and
  440. ((index=NR_INVALID) or
  441. (ref.index=index)) and
  442. (ref.volatility=[]);
  443. end;
  444. function InstrReadsFlags(p: tai): boolean;
  445. begin
  446. InstrReadsFlags := true;
  447. case p.typ of
  448. ait_instruction:
  449. if InsProp[taicpu(p).opcode].Ch*
  450. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  451. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  452. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  453. exit;
  454. ait_label:
  455. exit;
  456. else
  457. ;
  458. end;
  459. InstrReadsFlags := false;
  460. end;
  461. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  462. begin
  463. Next:=Current;
  464. repeat
  465. Result:=GetNextInstruction(Next,Next);
  466. until not (Result) or
  467. not(cs_opt_level3 in current_settings.optimizerswitches) or
  468. (Next.typ<>ait_instruction) or
  469. RegInInstruction(reg,Next) or
  470. is_calljmp(taicpu(Next).opcode);
  471. end;
  472. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  473. var
  474. GetNextResult: Boolean;
  475. begin
  476. Result:=0;
  477. Next:=Current;
  478. repeat
  479. GetNextResult := GetNextInstruction(Next,Next);
  480. if GetNextResult then
  481. Inc(Result)
  482. else
  483. { Must return zero upon hitting the end of the linked list without a match }
  484. Result := 0;
  485. until not (GetNextResult) or
  486. not(cs_opt_level3 in current_settings.optimizerswitches) or
  487. (Next.typ<>ait_instruction) or
  488. RegInInstruction(reg,Next) or
  489. is_calljmp(taicpu(Next).opcode);
  490. end;
  491. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  492. procedure TrackJump(Symbol: TAsmSymbol);
  493. var
  494. Search: TJumpTrackingItem;
  495. begin
  496. { See if an entry already exists in our jump tracking list
  497. (faster to search backwards due to the higher chance of
  498. matching destinations) }
  499. Search := TJumpTrackingItem(JumpTracking.Last);
  500. while Assigned(Search) do
  501. begin
  502. if Search.Symbol = Symbol then
  503. begin
  504. { Found it - remove it so it can be pushed to the front }
  505. JumpTracking.Remove(Search);
  506. Break;
  507. end;
  508. Search := TJumpTrackingItem(Search.Previous);
  509. end;
  510. if not Assigned(Search) then
  511. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  512. JumpTracking.Concat(Search);
  513. Search.IncRefs;
  514. end;
  515. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  516. var
  517. Search: TJumpTrackingItem;
  518. begin
  519. Result := False;
  520. { See if this label appears in the tracking list }
  521. Search := TJumpTrackingItem(JumpTracking.Last);
  522. while Assigned(Search) do
  523. begin
  524. if Search.Symbol = Symbol then
  525. begin
  526. { Found it - let's see what we can discover }
  527. if Search.Symbol.getrefs = Search.Refs then
  528. begin
  529. { Success - all the references are accounted for }
  530. JumpTracking.Remove(Search);
  531. Search.Free;
  532. { It is logically impossible for CrossJump to be false here
  533. because we must have run into a conditional jump for
  534. this label at some point }
  535. if not CrossJump then
  536. InternalError(2022041710);
  537. if JumpTracking.First = nil then
  538. { Tracking list is now empty - no more cross jumps }
  539. CrossJump := False;
  540. Result := True;
  541. Exit;
  542. end;
  543. { If the references don't match, it's possible to enter
  544. this label through other means, so drop out }
  545. Exit;
  546. end;
  547. Search := TJumpTrackingItem(Search.Previous);
  548. end;
  549. end;
  550. var
  551. Next_Label: tai;
  552. begin
  553. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  554. Next := Current;
  555. repeat
  556. Result := GetNextInstruction(Next,Next);
  557. if not Result then
  558. Break;
  559. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  560. if is_calljmpuncondret(taicpu(Next).opcode) then
  561. begin
  562. if (taicpu(Next).opcode = A_JMP) and
  563. { Remove dead code now to save time }
  564. RemoveDeadCodeAfterJump(taicpu(Next)) then
  565. { A jump was removed, but not the current instruction, and
  566. Result doesn't necessarily translate into an optimisation
  567. routine's Result, so use the "Force New Iteration" flag so
  568. mark a new pass }
  569. Include(OptsToCheck, aoc_ForceNewIteration);
  570. if not Assigned(JumpTracking) then
  571. begin
  572. { Cross-label optimisations often causes other optimisations
  573. to perform worse because they're not given the chance to
  574. optimise locally. In this case, don't do the cross-label
  575. optimisations yet, but flag them as a potential possibility
  576. for the next iteration of Pass 1 }
  577. if not NotFirstIteration then
  578. Include(OptsToCheck, aoc_ForceNewIteration);
  579. end
  580. else if IsJumpToLabel(taicpu(Next)) and
  581. GetNextInstruction(Next, Next_Label) then
  582. begin
  583. { If we have JMP .lbl, and the label after it has all of its
  584. references tracked, then this is probably an if-else style of
  585. block and we can keep tracking. If the label for this jump
  586. then appears later and is fully tracked, then it's the end
  587. of the if-else blocks and the code paths converge (thus
  588. marking the end of the cross-jump) }
  589. if (Next_Label.typ = ait_label) then
  590. begin
  591. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  592. begin
  593. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  594. Next := Next_Label;
  595. { CrossJump gets set to false by LabelAccountedFor if the
  596. list is completely emptied (as it indicates that all
  597. code paths have converged). We could avoid this nuance
  598. by moving the TrackJump call to before the
  599. LabelAccountedFor call, but this is slower in situations
  600. where LabelAccountedFor would return False due to the
  601. creation of a new object that is not used and destroyed
  602. soon after. }
  603. CrossJump := True;
  604. Continue;
  605. end;
  606. end
  607. else if (Next_Label.typ <> ait_marker) then
  608. { We just did a RemoveDeadCodeAfterJump, so either we find
  609. a label, the end of the procedure or some kind of marker}
  610. InternalError(2022041720);
  611. end;
  612. Result := False;
  613. Exit;
  614. end
  615. else
  616. begin
  617. if not Assigned(JumpTracking) then
  618. begin
  619. { Cross-label optimisations often causes other optimisations
  620. to perform worse because they're not given the chance to
  621. optimise locally. In this case, don't do the cross-label
  622. optimisations yet, but flag them as a potential possibility
  623. for the next iteration of Pass 1 }
  624. if not NotFirstIteration then
  625. Include(OptsToCheck, aoc_ForceNewIteration);
  626. end
  627. else if IsJumpToLabel(taicpu(Next)) then
  628. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  629. else
  630. { Conditional jumps should always be a jump to label }
  631. InternalError(2022041701);
  632. CrossJump := True;
  633. Continue;
  634. end;
  635. if Next.typ = ait_label then
  636. begin
  637. if not Assigned(JumpTracking) then
  638. begin
  639. { Cross-label optimisations often causes other optimisations
  640. to perform worse because they're not given the chance to
  641. optimise locally. In this case, don't do the cross-label
  642. optimisations yet, but flag them as a potential possibility
  643. for the next iteration of Pass 1 }
  644. if not NotFirstIteration then
  645. Include(OptsToCheck, aoc_ForceNewIteration);
  646. end
  647. else if LabelAccountedFor(tai_label(Next).labsym) then
  648. Continue;
  649. { If we reach here, we're at a label that hasn't been seen before
  650. (or JumpTracking was nil) }
  651. Break;
  652. end;
  653. until not Result or
  654. not (cs_opt_level3 in current_settings.optimizerswitches) or
  655. not (Next.typ in [ait_label, ait_instruction]) or
  656. RegInInstruction(reg,Next);
  657. end;
  658. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  659. begin
  660. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  661. begin
  662. Result:=GetNextInstruction(Current,Next);
  663. exit;
  664. end;
  665. Next:=tai(Current.Next);
  666. Result:=false;
  667. while assigned(Next) do
  668. begin
  669. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  670. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  671. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  672. exit
  673. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  674. begin
  675. Result:=true;
  676. exit;
  677. end;
  678. Next:=tai(Next.Next);
  679. end;
  680. end;
  681. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  682. begin
  683. Result:=RegReadByInstruction(reg,hp);
  684. end;
  685. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  686. var
  687. p: taicpu;
  688. opcount: longint;
  689. begin
  690. RegReadByInstruction := false;
  691. if hp.typ <> ait_instruction then
  692. exit;
  693. p := taicpu(hp);
  694. case p.opcode of
  695. A_CALL:
  696. regreadbyinstruction := true;
  697. A_IMUL:
  698. case p.ops of
  699. 1:
  700. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  701. (
  702. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  703. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  704. );
  705. 2,3:
  706. regReadByInstruction :=
  707. reginop(reg,p.oper[0]^) or
  708. reginop(reg,p.oper[1]^);
  709. else
  710. InternalError(2019112801);
  711. end;
  712. A_MUL:
  713. begin
  714. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  715. (
  716. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  717. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  718. );
  719. end;
  720. A_IDIV,A_DIV:
  721. begin
  722. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  723. (
  724. (getregtype(reg)=R_INTREGISTER) and
  725. (
  726. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  727. )
  728. );
  729. end;
  730. else
  731. begin
  732. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  733. begin
  734. RegReadByInstruction := false;
  735. exit;
  736. end;
  737. for opcount := 0 to p.ops-1 do
  738. if (p.oper[opCount]^.typ = top_ref) and
  739. RegInRef(reg,p.oper[opcount]^.ref^) then
  740. begin
  741. RegReadByInstruction := true;
  742. exit
  743. end;
  744. { special handling for SSE MOVSD }
  745. if (p.opcode=A_MOVSD) and (p.ops>0) then
  746. begin
  747. if p.ops<>2 then
  748. internalerror(2017042702);
  749. regReadByInstruction := reginop(reg,p.oper[0]^) or
  750. (
  751. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  752. );
  753. exit;
  754. end;
  755. with insprop[p.opcode] do
  756. begin
  757. case getregtype(reg) of
  758. R_INTREGISTER:
  759. begin
  760. case getsupreg(reg) of
  761. RS_EAX:
  762. if [Ch_REAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  763. begin
  764. RegReadByInstruction := true;
  765. exit
  766. end;
  767. RS_ECX:
  768. if [Ch_RECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  769. begin
  770. RegReadByInstruction := true;
  771. exit
  772. end;
  773. RS_EDX:
  774. if [Ch_REDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  775. begin
  776. RegReadByInstruction := true;
  777. exit
  778. end;
  779. RS_EBX:
  780. if [Ch_REBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  781. begin
  782. RegReadByInstruction := true;
  783. exit
  784. end;
  785. RS_ESP:
  786. if [Ch_RESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  787. begin
  788. RegReadByInstruction := true;
  789. exit
  790. end;
  791. RS_EBP:
  792. if [Ch_REBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  793. begin
  794. RegReadByInstruction := true;
  795. exit
  796. end;
  797. RS_ESI:
  798. if [Ch_RESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  799. begin
  800. RegReadByInstruction := true;
  801. exit
  802. end;
  803. RS_EDI:
  804. if [Ch_REDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  805. begin
  806. RegReadByInstruction := true;
  807. exit
  808. end;
  809. end;
  810. end;
  811. R_MMREGISTER:
  812. begin
  813. case getsupreg(reg) of
  814. RS_XMM0:
  815. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  816. begin
  817. RegReadByInstruction := true;
  818. exit
  819. end;
  820. end;
  821. end;
  822. else
  823. ;
  824. end;
  825. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  826. begin
  827. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  828. begin
  829. case p.condition of
  830. C_A,C_NBE, { CF=0 and ZF=0 }
  831. C_BE,C_NA: { CF=1 or ZF=1 }
  832. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  833. C_AE,C_NB,C_NC, { CF=0 }
  834. C_B,C_NAE,C_C: { CF=1 }
  835. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  836. C_NE,C_NZ, { ZF=0 }
  837. C_E,C_Z: { ZF=1 }
  838. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  839. C_G,C_NLE, { ZF=0 and SF=OF }
  840. C_LE,C_NG: { ZF=1 or SF<>OF }
  841. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  842. C_GE,C_NL, { SF=OF }
  843. C_L,C_NGE: { SF<>OF }
  844. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  845. C_NO, { OF=0 }
  846. C_O: { OF=1 }
  847. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  848. C_NP,C_PO, { PF=0 }
  849. C_P,C_PE: { PF=1 }
  850. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  851. C_NS, { SF=0 }
  852. C_S: { SF=1 }
  853. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  854. else
  855. internalerror(2017042701);
  856. end;
  857. if RegReadByInstruction then
  858. exit;
  859. end;
  860. case getsubreg(reg) of
  861. R_SUBW,R_SUBD,R_SUBQ:
  862. RegReadByInstruction :=
  863. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  864. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  865. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  866. R_SUBFLAGCARRY:
  867. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  868. R_SUBFLAGPARITY:
  869. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  870. R_SUBFLAGAUXILIARY:
  871. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  872. R_SUBFLAGZERO:
  873. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  874. R_SUBFLAGSIGN:
  875. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  876. R_SUBFLAGOVERFLOW:
  877. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  878. R_SUBFLAGINTERRUPT:
  879. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  880. R_SUBFLAGDIRECTION:
  881. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  882. else
  883. internalerror(2017042601);
  884. end;
  885. exit;
  886. end;
  887. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  888. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  889. (p.oper[0]^.reg=p.oper[1]^.reg) then
  890. exit;
  891. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  892. begin
  893. RegReadByInstruction := true;
  894. exit
  895. end;
  896. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  897. begin
  898. RegReadByInstruction := true;
  899. exit
  900. end;
  901. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  902. begin
  903. RegReadByInstruction := true;
  904. exit
  905. end;
  906. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  907. begin
  908. RegReadByInstruction := true;
  909. exit
  910. end;
  911. end;
  912. end;
  913. end;
  914. end;
  915. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  916. begin
  917. result:=false;
  918. if p1.typ<>ait_instruction then
  919. exit;
  920. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  921. exit(true);
  922. if (getregtype(reg)=R_INTREGISTER) and
  923. { change information for xmm movsd are not correct }
  924. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  925. begin
  926. { Handle instructions that behave differently depending on the size and operand count }
  927. case taicpu(p1).opcode of
  928. A_MUL, A_DIV, A_IDIV:
  929. if taicpu(p1).opsize = S_B then
  930. Result := (getsupreg(Reg) = RS_EAX)
  931. else
  932. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  933. A_IMUL:
  934. if taicpu(p1).ops = 1 then
  935. begin
  936. if taicpu(p1).opsize = S_B then
  937. Result := (getsupreg(Reg) = RS_EAX)
  938. else
  939. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  940. end;
  941. { If ops are greater than 1, call inherited method }
  942. else
  943. case getsupreg(reg) of
  944. { RS_EAX = RS_RAX on x86-64 }
  945. RS_EAX:
  946. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  947. RS_ECX:
  948. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  949. RS_EDX:
  950. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  951. RS_EBX:
  952. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  953. RS_ESP:
  954. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  955. RS_EBP:
  956. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  957. RS_ESI:
  958. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  959. RS_EDI:
  960. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  961. else
  962. ;
  963. end;
  964. end;
  965. if result then
  966. exit;
  967. end
  968. else if getregtype(reg)=R_MMREGISTER then
  969. begin
  970. case getsupreg(reg) of
  971. RS_XMM0:
  972. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  973. else
  974. ;
  975. end;
  976. if result then
  977. exit;
  978. end
  979. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  980. begin
  981. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  982. exit(true);
  983. case getsubreg(reg) of
  984. R_SUBFLAGCARRY:
  985. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  986. R_SUBFLAGPARITY:
  987. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  988. R_SUBFLAGAUXILIARY:
  989. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  990. R_SUBFLAGZERO:
  991. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  992. R_SUBFLAGSIGN:
  993. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  994. R_SUBFLAGOVERFLOW:
  995. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  996. R_SUBFLAGINTERRUPT:
  997. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  998. R_SUBFLAGDIRECTION:
  999. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  1000. R_SUBW,R_SUBD,R_SUBQ:
  1001. { Everything except the direction bits }
  1002. Result:=
  1003. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  1004. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1005. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1006. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1007. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1008. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  1009. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  1010. else
  1011. ;
  1012. end;
  1013. if result then
  1014. exit;
  1015. end
  1016. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  1017. exit(true);
  1018. Result:=inherited RegInInstruction(Reg, p1);
  1019. end;
  1020. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  1021. const
  1022. WriteOps: array[0..3] of set of TInsChange =
  1023. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1024. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1025. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1026. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1027. var
  1028. OperIdx: Integer;
  1029. begin
  1030. Result := False;
  1031. if p1.typ <> ait_instruction then
  1032. exit;
  1033. with insprop[taicpu(p1).opcode] do
  1034. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1035. begin
  1036. case getsubreg(reg) of
  1037. R_SUBW,R_SUBD,R_SUBQ:
  1038. Result :=
  1039. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  1040. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  1041. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  1042. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  1043. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  1044. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1045. R_SUBFLAGCARRY:
  1046. Result:=[Ch_WCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WUCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1047. R_SUBFLAGPARITY:
  1048. Result:=[Ch_WParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WUParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1049. R_SUBFLAGAUXILIARY:
  1050. Result:=[Ch_WAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1051. R_SUBFLAGZERO:
  1052. Result:=[Ch_WZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WUZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1053. R_SUBFLAGSIGN:
  1054. Result:=[Ch_WSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WUSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1055. R_SUBFLAGOVERFLOW:
  1056. Result:=[Ch_WOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WUOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1057. R_SUBFLAGINTERRUPT:
  1058. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1059. R_SUBFLAGDIRECTION:
  1060. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  1061. else
  1062. internalerror(2017042602);
  1063. end;
  1064. exit;
  1065. end;
  1066. case taicpu(p1).opcode of
  1067. A_CALL:
  1068. { We could potentially set Result to False if the register in
  1069. question is non-volatile for the subroutine's calling convention,
  1070. but this would require detecting the calling convention in use and
  1071. also assuming that the routine doesn't contain malformed assembly
  1072. language, for example... so it could only be done under -O4 as it
  1073. would be considered a side-effect. [Kit] }
  1074. Result := True;
  1075. A_MOVSD:
  1076. { special handling for SSE MOVSD }
  1077. if (taicpu(p1).ops>0) then
  1078. begin
  1079. if taicpu(p1).ops<>2 then
  1080. internalerror(2017042703);
  1081. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  1082. end;
  1083. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  1084. so fix it here (FK)
  1085. }
  1086. A_VMOVSS,
  1087. A_VMOVSD:
  1088. begin
  1089. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1090. exit;
  1091. end;
  1092. A_MUL, A_DIV, A_IDIV:
  1093. begin
  1094. if taicpu(p1).opsize = S_B then
  1095. Result := (getsupreg(Reg) = RS_EAX)
  1096. else
  1097. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1098. end;
  1099. A_IMUL:
  1100. begin
  1101. if taicpu(p1).ops = 1 then
  1102. begin
  1103. Result := (getsupreg(Reg) in [RS_EAX, RS_EDX]);
  1104. end
  1105. else
  1106. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1107. Exit;
  1108. end;
  1109. else
  1110. ;
  1111. end;
  1112. if Result then
  1113. exit;
  1114. with insprop[taicpu(p1).opcode] do
  1115. begin
  1116. if getregtype(reg)=R_INTREGISTER then
  1117. begin
  1118. case getsupreg(reg) of
  1119. RS_EAX:
  1120. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1121. begin
  1122. Result := True;
  1123. exit
  1124. end;
  1125. RS_ECX:
  1126. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1127. begin
  1128. Result := True;
  1129. exit
  1130. end;
  1131. RS_EDX:
  1132. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1133. begin
  1134. Result := True;
  1135. exit
  1136. end;
  1137. RS_EBX:
  1138. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1139. begin
  1140. Result := True;
  1141. exit
  1142. end;
  1143. RS_ESP:
  1144. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1145. begin
  1146. Result := True;
  1147. exit
  1148. end;
  1149. RS_EBP:
  1150. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1151. begin
  1152. Result := True;
  1153. exit
  1154. end;
  1155. RS_ESI:
  1156. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1157. begin
  1158. Result := True;
  1159. exit
  1160. end;
  1161. RS_EDI:
  1162. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1163. begin
  1164. Result := True;
  1165. exit
  1166. end;
  1167. end;
  1168. end;
  1169. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1170. if (WriteOps[OperIdx]*Ch<>[]) and
  1171. { The register doesn't get modified inside a reference }
  1172. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1173. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1174. begin
  1175. Result := true;
  1176. exit
  1177. end;
  1178. end;
  1179. end;
  1180. function TX86AsmOptimizer.RefModifiedBetween(Ref: TReference; RefSize: ASizeInt; p1, p2: tai): Boolean;
  1181. const
  1182. WriteOps: array[0..3] of set of TInsChange =
  1183. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  1184. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  1185. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  1186. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  1187. var
  1188. X: Integer;
  1189. CurrentP1Size: asizeint;
  1190. begin
  1191. Result := (
  1192. (Ref.base <> NR_NO) and
  1193. {$ifdef x86_64}
  1194. (Ref.base <> NR_RIP) and
  1195. {$endif x86_64}
  1196. RegModifiedBetween(Ref.base, p1, p2)
  1197. ) or
  1198. (
  1199. (Ref.index <> NR_NO) and
  1200. (Ref.index <> Ref.base) and
  1201. RegModifiedBetween(Ref.index, p1, p2)
  1202. );
  1203. { Now check to see if the memory itself is written to }
  1204. if not Result then
  1205. begin
  1206. while assigned(p1) and assigned(p2) and GetNextInstruction(p1,p1) and (p1<>p2) do
  1207. if p1.typ = ait_instruction then
  1208. begin
  1209. CurrentP1Size := topsize2memsize[taicpu(p1).opsize] shr 3; { Convert to bytes }
  1210. with insprop[taicpu(p1).opcode] do
  1211. for X := 0 to taicpu(p1).ops - 1 do
  1212. if (taicpu(p1).oper[X]^.typ = top_ref) and
  1213. RefsAlmostEqual(Ref, taicpu(p1).oper[X]^.ref^) and
  1214. { Catch any potential overlaps }
  1215. (
  1216. (RefSize = 0) or
  1217. ((taicpu(p1).oper[X]^.ref^.offset - Ref.offset) < RefSize)
  1218. ) and
  1219. (
  1220. (CurrentP1Size = 0) or
  1221. ((Ref.offset - taicpu(p1).oper[X]^.ref^.offset) < CurrentP1Size)
  1222. ) and
  1223. { Reference is used, but does the instruction write to it? }
  1224. (
  1225. (Ch_All in Ch) or
  1226. ((WriteOps[X] * Ch) <> [])
  1227. ) then
  1228. begin
  1229. Result := True;
  1230. Break;
  1231. end;
  1232. end;
  1233. end;
  1234. end;
  1235. {$ifdef DEBUG_AOPTCPU}
  1236. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1237. begin
  1238. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1239. end;
  1240. function debug_tostr(i: tcgint): string; inline;
  1241. begin
  1242. Result := tostr(i);
  1243. end;
  1244. function debug_hexstr(i: tcgint): string;
  1245. begin
  1246. Result := '0x';
  1247. case i of
  1248. 0..$FF:
  1249. Result := Result + hexstr(i, 2);
  1250. $100..$FFFF:
  1251. Result := Result + hexstr(i, 4);
  1252. $10000..$FFFFFF:
  1253. Result := Result + hexstr(i, 6);
  1254. $1000000..$FFFFFFFF:
  1255. Result := Result + hexstr(i, 8);
  1256. else
  1257. Result := Result + hexstr(i, 16);
  1258. end;
  1259. end;
  1260. function debug_regname(r: TRegister): string; inline;
  1261. begin
  1262. Result := '%' + std_regname(r);
  1263. end;
  1264. { Debug output function - creates a string representation of an operator }
  1265. function debug_operstr(oper: TOper): string;
  1266. begin
  1267. case oper.typ of
  1268. top_const:
  1269. Result := '$' + debug_tostr(oper.val);
  1270. top_reg:
  1271. Result := debug_regname(oper.reg);
  1272. top_ref:
  1273. begin
  1274. if oper.ref^.offset <> 0 then
  1275. Result := debug_tostr(oper.ref^.offset) + '('
  1276. else
  1277. Result := '(';
  1278. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1279. begin
  1280. Result := Result + debug_regname(oper.ref^.base);
  1281. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1282. Result := Result + ',' + debug_regname(oper.ref^.index);
  1283. end
  1284. else
  1285. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1286. Result := Result + debug_regname(oper.ref^.index);
  1287. if (oper.ref^.scalefactor > 1) then
  1288. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1289. else
  1290. Result := Result + ')';
  1291. end;
  1292. else
  1293. Result := '[UNKNOWN]';
  1294. end;
  1295. end;
  1296. function debug_op2str(opcode: tasmop): string; inline;
  1297. begin
  1298. Result := std_op2str[opcode];
  1299. end;
  1300. function debug_opsize2str(opsize: topsize): string; inline;
  1301. begin
  1302. Result := gas_opsize2str[opsize];
  1303. end;
  1304. {$else DEBUG_AOPTCPU}
  1305. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1306. begin
  1307. end;
  1308. function debug_tostr(i: tcgint): string; inline;
  1309. begin
  1310. Result := '';
  1311. end;
  1312. function debug_hexstr(i: tcgint): string; inline;
  1313. begin
  1314. Result := '';
  1315. end;
  1316. function debug_regname(r: TRegister): string; inline;
  1317. begin
  1318. Result := '';
  1319. end;
  1320. function debug_operstr(oper: TOper): string; inline;
  1321. begin
  1322. Result := '';
  1323. end;
  1324. function debug_op2str(opcode: tasmop): string; inline;
  1325. begin
  1326. Result := '';
  1327. end;
  1328. function debug_opsize2str(opsize: topsize): string; inline;
  1329. begin
  1330. Result := '';
  1331. end;
  1332. {$endif DEBUG_AOPTCPU}
  1333. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1334. begin
  1335. {$ifdef x86_64}
  1336. { Always fine on x86-64 }
  1337. Result := True;
  1338. {$else x86_64}
  1339. Result :=
  1340. {$ifdef i8086}
  1341. (current_settings.cputype >= cpu_386) and
  1342. {$endif i8086}
  1343. (
  1344. { Always accept if optimising for size }
  1345. (cs_opt_size in current_settings.optimizerswitches) or
  1346. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1347. (current_settings.optimizecputype >= cpu_Pentium2)
  1348. );
  1349. {$endif x86_64}
  1350. end;
  1351. { Attempts to allocate a volatile integer register for use between p and hp,
  1352. using AUsedRegs for the current register usage information. Returns NR_NO
  1353. if no free register could be found }
  1354. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1355. var
  1356. RegSet: TCPURegisterSet;
  1357. CurrentSuperReg: Integer;
  1358. CurrentReg: TRegister;
  1359. Currentp: tai;
  1360. Breakout: Boolean;
  1361. begin
  1362. Result := NR_NO;
  1363. RegSet :=
  1364. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1365. current_procinfo.saved_regs_int;
  1366. (*
  1367. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1368. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1369. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1370. *)
  1371. for CurrentSuperReg in RegSet do
  1372. begin
  1373. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1374. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1375. {$if defined(i386) or defined(i8086)}
  1376. { If the target size is 8-bit, make sure we can actually encode it }
  1377. and (
  1378. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1379. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1380. )
  1381. {$endif i386 or i8086}
  1382. then
  1383. begin
  1384. Currentp := p;
  1385. Breakout := False;
  1386. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1387. begin
  1388. case Currentp.typ of
  1389. ait_instruction:
  1390. begin
  1391. if RegInInstruction(CurrentReg, Currentp) then
  1392. begin
  1393. Breakout := True;
  1394. Break;
  1395. end;
  1396. { Cannot allocate across an unconditional jump }
  1397. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1398. Exit;
  1399. end;
  1400. ait_marker:
  1401. { Don't try anything more if a marker is hit }
  1402. Exit;
  1403. ait_regalloc:
  1404. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1405. begin
  1406. Breakout := True;
  1407. Break;
  1408. end;
  1409. else
  1410. ;
  1411. end;
  1412. end;
  1413. if Breakout then
  1414. { Try the next register }
  1415. Continue;
  1416. { We have a free register available }
  1417. Result := CurrentReg;
  1418. if not DontAlloc then
  1419. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1420. Exit;
  1421. end;
  1422. end;
  1423. end;
  1424. { Attempts to allocate a volatile MM register for use between p and hp,
  1425. using AUsedRegs for the current register usage information. Returns NR_NO
  1426. if no free register could be found }
  1427. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1428. var
  1429. RegSet: TCPURegisterSet;
  1430. CurrentSuperReg: Integer;
  1431. CurrentReg: TRegister;
  1432. Currentp: tai;
  1433. Breakout: Boolean;
  1434. begin
  1435. Result := NR_NO;
  1436. RegSet :=
  1437. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1438. current_procinfo.saved_regs_mm;
  1439. for CurrentSuperReg in RegSet do
  1440. begin
  1441. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1442. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1443. begin
  1444. Currentp := p;
  1445. Breakout := False;
  1446. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1447. begin
  1448. case Currentp.typ of
  1449. ait_instruction:
  1450. begin
  1451. if RegInInstruction(CurrentReg, Currentp) then
  1452. begin
  1453. Breakout := True;
  1454. Break;
  1455. end;
  1456. { Cannot allocate across an unconditional jump }
  1457. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1458. Exit;
  1459. end;
  1460. ait_marker:
  1461. { Don't try anything more if a marker is hit }
  1462. Exit;
  1463. ait_regalloc:
  1464. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1465. begin
  1466. Breakout := True;
  1467. Break;
  1468. end;
  1469. else
  1470. ;
  1471. end;
  1472. end;
  1473. if Breakout then
  1474. { Try the next register }
  1475. Continue;
  1476. { We have a free register available }
  1477. Result := CurrentReg;
  1478. if not DontAlloc then
  1479. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1480. Exit;
  1481. end;
  1482. end;
  1483. end;
  1484. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1485. begin
  1486. if not SuperRegistersEqual(reg1,reg2) then
  1487. exit(false);
  1488. if getregtype(reg1)<>R_INTREGISTER then
  1489. exit(true); {because SuperRegisterEqual is true}
  1490. case getsubreg(reg1) of
  1491. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1492. higher, it preserves the high bits, so the new value depends on
  1493. reg2's previous value. In other words, it is equivalent to doing:
  1494. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1495. R_SUBL:
  1496. exit(getsubreg(reg2)=R_SUBL);
  1497. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1498. higher, it actually does a:
  1499. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1500. R_SUBH:
  1501. exit(getsubreg(reg2)=R_SUBH);
  1502. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1503. bits of reg2:
  1504. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1505. R_SUBW:
  1506. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1507. { a write to R_SUBD always overwrites every other subregister,
  1508. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1509. R_SUBD,
  1510. R_SUBQ:
  1511. exit(true);
  1512. else
  1513. internalerror(2017042801);
  1514. end;
  1515. end;
  1516. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1517. begin
  1518. if not SuperRegistersEqual(reg1,reg2) then
  1519. exit(false);
  1520. if getregtype(reg1)<>R_INTREGISTER then
  1521. exit(true); {because SuperRegisterEqual is true}
  1522. case getsubreg(reg1) of
  1523. R_SUBL:
  1524. exit(getsubreg(reg2)<>R_SUBH);
  1525. R_SUBH:
  1526. exit(getsubreg(reg2)<>R_SUBL);
  1527. R_SUBW,
  1528. R_SUBD,
  1529. R_SUBQ:
  1530. exit(true);
  1531. else
  1532. internalerror(2017042802);
  1533. end;
  1534. end;
  1535. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1536. var
  1537. hp1 : tai;
  1538. l : TCGInt;
  1539. begin
  1540. result:=false;
  1541. if not(GetNextInstruction(p, hp1)) then
  1542. exit;
  1543. { changes the code sequence
  1544. shr/sar const1, x
  1545. shl const2, x
  1546. to
  1547. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1548. if (taicpu(p).oper[0]^.typ = top_const) and
  1549. MatchInstruction(hp1,A_SHL,[]) and
  1550. (taicpu(hp1).oper[0]^.typ = top_const) and
  1551. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1552. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1553. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1554. begin
  1555. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1556. not(cs_opt_size in current_settings.optimizerswitches)
  1557. {$ifdef x86_64}
  1558. and (
  1559. (taicpu(p).opsize <> S_Q) or
  1560. { 64-bit AND can only store signed 32-bit immediates }
  1561. (taicpu(p).oper[0]^.val < 32)
  1562. )
  1563. {$endif x86_64}
  1564. then
  1565. begin
  1566. { shr/sar const1, %reg
  1567. shl const2, %reg
  1568. with const1 > const2 }
  1569. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 1 done',p);
  1570. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1571. taicpu(hp1).opcode := A_AND;
  1572. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1573. case taicpu(p).opsize Of
  1574. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1575. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1576. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1577. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1578. else
  1579. Internalerror(2017050703)
  1580. end;
  1581. end
  1582. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1583. not(cs_opt_size in current_settings.optimizerswitches)
  1584. {$ifdef x86_64}
  1585. and (
  1586. (taicpu(p).opsize <> S_Q) or
  1587. { 64-bit AND can only store signed 32-bit immediates }
  1588. (taicpu(p).oper[0]^.val < 32)
  1589. )
  1590. {$endif x86_64}
  1591. then
  1592. begin
  1593. { shr/sar const1, %reg
  1594. shl const2, %reg
  1595. with const1 < const2 }
  1596. DebugMsg(SPeepholeOptimization + 'SxrShl2SxrAnd 2 done',p);
  1597. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1598. taicpu(p).opcode := A_AND;
  1599. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1600. case taicpu(p).opsize Of
  1601. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1602. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1603. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1604. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1605. else
  1606. Internalerror(2017050702)
  1607. end;
  1608. end
  1609. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val)
  1610. {$ifdef x86_64}
  1611. and (
  1612. (taicpu(p).opsize <> S_Q) or
  1613. { 64-bit AND can only store signed 32-bit immediates }
  1614. (taicpu(p).oper[0]^.val < 32)
  1615. )
  1616. {$endif x86_64}
  1617. then
  1618. begin
  1619. { shr/sar const1, %reg
  1620. shl const2, %reg
  1621. with const1 = const2 }
  1622. DebugMsg(SPeepholeOptimization + 'SxrShl2And done',p);
  1623. taicpu(p).opcode := A_AND;
  1624. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1625. case taicpu(p).opsize Of
  1626. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1627. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1628. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1629. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1630. else
  1631. Internalerror(2017050701)
  1632. end;
  1633. RemoveInstruction(hp1);
  1634. end;
  1635. end;
  1636. end;
  1637. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1638. var
  1639. opsize : topsize;
  1640. hp1, hp2 : tai;
  1641. tmpref : treference;
  1642. ShiftValue : Cardinal;
  1643. BaseValue : TCGInt;
  1644. begin
  1645. result:=false;
  1646. opsize:=taicpu(p).opsize;
  1647. { changes certain "imul const, %reg"'s to lea sequences }
  1648. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1649. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1650. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1651. if (taicpu(p).oper[0]^.val = 1) then
  1652. if (taicpu(p).ops = 2) then
  1653. { remove "imul $1, reg" }
  1654. begin
  1655. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1656. Result := RemoveCurrentP(p);
  1657. end
  1658. else
  1659. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1660. begin
  1661. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1662. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1663. asml.InsertAfter(hp1, p);
  1664. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1665. RemoveCurrentP(p, hp1);
  1666. Result := True;
  1667. end
  1668. else if ((taicpu(p).ops <= 2) or
  1669. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1670. not(cs_opt_size in current_settings.optimizerswitches) and
  1671. (not(GetNextInstruction(p, hp1)) or
  1672. not((tai(hp1).typ = ait_instruction) and
  1673. ((taicpu(hp1).opcode=A_Jcc) and
  1674. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1675. begin
  1676. {
  1677. imul X, reg1, reg2 to
  1678. lea (reg1,reg1,Y), reg2
  1679. shl ZZ,reg2
  1680. imul XX, reg1 to
  1681. lea (reg1,reg1,YY), reg1
  1682. shl ZZ,reg2
  1683. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1684. it does not exist as a separate optimization target in FPC though.
  1685. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1686. at most two zeros
  1687. }
  1688. reference_reset(tmpref,1,[]);
  1689. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1690. begin
  1691. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1692. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1693. TmpRef.base := taicpu(p).oper[1]^.reg;
  1694. TmpRef.index := taicpu(p).oper[1]^.reg;
  1695. if not(BaseValue in [3,5,9]) then
  1696. Internalerror(2018110101);
  1697. TmpRef.ScaleFactor := BaseValue-1;
  1698. if (taicpu(p).ops = 2) then
  1699. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1700. else
  1701. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1702. AsmL.InsertAfter(hp1,p);
  1703. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1704. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1705. RemoveCurrentP(p, hp1);
  1706. if ShiftValue>0 then
  1707. begin
  1708. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1709. AsmL.InsertAfter(hp2,hp1);
  1710. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1711. end;
  1712. Result := True;
  1713. end;
  1714. end;
  1715. end;
  1716. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1717. begin
  1718. Result := False;
  1719. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1720. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1721. begin
  1722. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1723. taicpu(p).opcode := A_MOV;
  1724. Result := True;
  1725. end;
  1726. end;
  1727. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1728. var
  1729. p: taicpu absolute hp; { Implicit typecast }
  1730. i: Integer;
  1731. begin
  1732. Result := False;
  1733. if not assigned(hp) or
  1734. (hp.typ <> ait_instruction) then
  1735. Exit;
  1736. Prefetch(insprop[p.opcode]);
  1737. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1738. with insprop[p.opcode] do
  1739. begin
  1740. case getsubreg(reg) of
  1741. R_SUBW,R_SUBD,R_SUBQ:
  1742. Result:=
  1743. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1744. uncommon flags are checked first }
  1745. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1746. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1747. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1748. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1749. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1750. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1751. R_SUBFLAGCARRY:
  1752. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1753. R_SUBFLAGPARITY:
  1754. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1755. R_SUBFLAGAUXILIARY:
  1756. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1757. R_SUBFLAGZERO:
  1758. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1759. R_SUBFLAGSIGN:
  1760. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1761. R_SUBFLAGOVERFLOW:
  1762. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1763. R_SUBFLAGINTERRUPT:
  1764. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1765. R_SUBFLAGDIRECTION:
  1766. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1767. else
  1768. internalerror(2017050501);
  1769. end;
  1770. exit;
  1771. end;
  1772. { Handle special cases first }
  1773. case p.opcode of
  1774. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1775. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1776. begin
  1777. Result :=
  1778. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1779. (p.oper[1]^.typ = top_reg) and
  1780. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1781. (
  1782. (p.oper[0]^.typ = top_const) or
  1783. (
  1784. (p.oper[0]^.typ = top_reg) and
  1785. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1786. ) or (
  1787. (p.oper[0]^.typ = top_ref) and
  1788. not RegInRef(reg,p.oper[0]^.ref^)
  1789. )
  1790. );
  1791. end;
  1792. A_MUL, A_IMUL:
  1793. Result :=
  1794. (
  1795. (p.ops=3) and { IMUL only }
  1796. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1797. (
  1798. (
  1799. (p.oper[1]^.typ=top_reg) and
  1800. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1801. ) or (
  1802. (p.oper[1]^.typ=top_ref) and
  1803. not RegInRef(reg,p.oper[1]^.ref^)
  1804. )
  1805. )
  1806. ) or (
  1807. (
  1808. (p.ops=1) and
  1809. (
  1810. (
  1811. (
  1812. (p.oper[0]^.typ=top_reg) and
  1813. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1814. )
  1815. ) or (
  1816. (p.oper[0]^.typ=top_ref) and
  1817. not RegInRef(reg,p.oper[0]^.ref^)
  1818. )
  1819. ) and (
  1820. (
  1821. (p.opsize=S_B) and
  1822. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1823. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1824. ) or (
  1825. (p.opsize=S_W) and
  1826. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1827. ) or (
  1828. (p.opsize=S_L) and
  1829. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1830. {$ifdef x86_64}
  1831. ) or (
  1832. (p.opsize=S_Q) and
  1833. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1834. {$endif x86_64}
  1835. )
  1836. )
  1837. )
  1838. );
  1839. A_CBW:
  1840. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1841. {$ifndef x86_64}
  1842. A_LDS:
  1843. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1844. A_LES:
  1845. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1846. {$endif not x86_64}
  1847. A_LFS:
  1848. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1849. A_LGS:
  1850. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1851. A_LSS:
  1852. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1853. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1854. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1855. A_LODSB:
  1856. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1857. A_LODSW:
  1858. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1859. {$ifdef x86_64}
  1860. A_LODSQ:
  1861. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1862. {$endif x86_64}
  1863. A_LODSD:
  1864. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1865. A_FSTSW, A_FNSTSW:
  1866. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1867. else
  1868. begin
  1869. with insprop[p.opcode] do
  1870. begin
  1871. if (
  1872. { xor %reg,%reg etc. is classed as a new value }
  1873. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1874. MatchOpType(p, top_reg, top_reg) and
  1875. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1876. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1877. ) then
  1878. begin
  1879. Result := True;
  1880. Exit;
  1881. end;
  1882. { Make sure the entire register is overwritten }
  1883. if (getregtype(reg) = R_INTREGISTER) then
  1884. begin
  1885. if (p.ops > 0) then
  1886. begin
  1887. if RegInOp(reg, p.oper[0]^) then
  1888. begin
  1889. if (p.oper[0]^.typ = top_ref) then
  1890. begin
  1891. if RegInRef(reg, p.oper[0]^.ref^) then
  1892. begin
  1893. Result := False;
  1894. Exit;
  1895. end;
  1896. end
  1897. else if (p.oper[0]^.typ = top_reg) then
  1898. begin
  1899. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1900. begin
  1901. Result := False;
  1902. Exit;
  1903. end
  1904. else if ([Ch_WOp1]*Ch<>[]) then
  1905. begin
  1906. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1907. Result := True
  1908. else
  1909. begin
  1910. Result := False;
  1911. Exit;
  1912. end;
  1913. end;
  1914. end;
  1915. end;
  1916. if (p.ops > 1) then
  1917. begin
  1918. if RegInOp(reg, p.oper[1]^) then
  1919. begin
  1920. if (p.oper[1]^.typ = top_ref) then
  1921. begin
  1922. if RegInRef(reg, p.oper[1]^.ref^) then
  1923. begin
  1924. Result := False;
  1925. Exit;
  1926. end;
  1927. end
  1928. else if (p.oper[1]^.typ = top_reg) then
  1929. begin
  1930. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1931. begin
  1932. Result := False;
  1933. Exit;
  1934. end
  1935. else if ([Ch_WOp2]*Ch<>[]) then
  1936. begin
  1937. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1938. Result := True
  1939. else
  1940. begin
  1941. Result := False;
  1942. Exit;
  1943. end;
  1944. end;
  1945. end;
  1946. end;
  1947. if (p.ops > 2) then
  1948. begin
  1949. if RegInOp(reg, p.oper[2]^) then
  1950. begin
  1951. if (p.oper[2]^.typ = top_ref) then
  1952. begin
  1953. if RegInRef(reg, p.oper[2]^.ref^) then
  1954. begin
  1955. Result := False;
  1956. Exit;
  1957. end;
  1958. end
  1959. else if (p.oper[2]^.typ = top_reg) then
  1960. begin
  1961. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1962. begin
  1963. Result := False;
  1964. Exit;
  1965. end
  1966. else if ([Ch_WOp3]*Ch<>[]) then
  1967. begin
  1968. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1969. Result := True
  1970. else
  1971. begin
  1972. Result := False;
  1973. Exit;
  1974. end;
  1975. end;
  1976. end;
  1977. end;
  1978. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1979. begin
  1980. if (p.oper[3]^.typ = top_ref) then
  1981. begin
  1982. if RegInRef(reg, p.oper[3]^.ref^) then
  1983. begin
  1984. Result := False;
  1985. Exit;
  1986. end;
  1987. end
  1988. else if (p.oper[3]^.typ = top_reg) then
  1989. begin
  1990. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1991. begin
  1992. Result := False;
  1993. Exit;
  1994. end
  1995. else if ([Ch_WOp4]*Ch<>[]) then
  1996. begin
  1997. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1998. Result := True
  1999. else
  2000. begin
  2001. Result := False;
  2002. Exit;
  2003. end;
  2004. end;
  2005. end;
  2006. end;
  2007. end;
  2008. end;
  2009. end;
  2010. { Don't do these ones first in case an input operand is equal to an explicit output register }
  2011. case getsupreg(reg) of
  2012. RS_EAX:
  2013. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  2014. begin
  2015. Result := True;
  2016. Exit;
  2017. end;
  2018. RS_ECX:
  2019. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  2020. begin
  2021. Result := True;
  2022. Exit;
  2023. end;
  2024. RS_EDX:
  2025. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  2026. begin
  2027. Result := True;
  2028. Exit;
  2029. end;
  2030. RS_EBX:
  2031. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  2032. begin
  2033. Result := True;
  2034. Exit;
  2035. end;
  2036. RS_ESP:
  2037. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  2038. begin
  2039. Result := True;
  2040. Exit;
  2041. end;
  2042. RS_EBP:
  2043. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  2044. begin
  2045. Result := True;
  2046. Exit;
  2047. end;
  2048. RS_ESI:
  2049. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  2050. begin
  2051. Result := True;
  2052. Exit;
  2053. end;
  2054. RS_EDI:
  2055. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  2056. begin
  2057. Result := True;
  2058. Exit;
  2059. end;
  2060. else
  2061. ;
  2062. end;
  2063. end;
  2064. end;
  2065. end;
  2066. end;
  2067. end;
  2068. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  2069. var
  2070. hp2,hp3 : tai;
  2071. begin
  2072. { some x86-64 issue a NOP before the real exit code }
  2073. if MatchInstruction(p,A_NOP,[]) then
  2074. GetNextInstruction(p,p);
  2075. result:=assigned(p) and (p.typ=ait_instruction) and
  2076. ((taicpu(p).opcode = A_RET) or
  2077. ((taicpu(p).opcode=A_LEAVE) and
  2078. GetNextInstruction(p,hp2) and
  2079. MatchInstruction(hp2,A_RET,[S_NO])
  2080. ) or
  2081. (((taicpu(p).opcode=A_LEA) and
  2082. MatchOpType(taicpu(p),top_ref,top_reg) and
  2083. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  2084. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2085. ) and
  2086. GetNextInstruction(p,hp2) and
  2087. MatchInstruction(hp2,A_RET,[S_NO])
  2088. ) or
  2089. ((((taicpu(p).opcode=A_MOV) and
  2090. MatchOpType(taicpu(p),top_reg,top_reg) and
  2091. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  2092. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  2093. ((taicpu(p).opcode=A_LEA) and
  2094. MatchOpType(taicpu(p),top_ref,top_reg) and
  2095. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  2096. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  2097. )
  2098. ) and
  2099. GetNextInstruction(p,hp2) and
  2100. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  2101. MatchOpType(taicpu(hp2),top_reg) and
  2102. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  2103. GetNextInstruction(hp2,hp3) and
  2104. MatchInstruction(hp3,A_RET,[S_NO])
  2105. )
  2106. );
  2107. end;
  2108. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  2109. begin
  2110. isFoldableArithOp := False;
  2111. case hp1.opcode of
  2112. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  2113. isFoldableArithOp :=
  2114. ((taicpu(hp1).oper[0]^.typ = top_const) or
  2115. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  2116. (taicpu(hp1).oper[0]^.reg <> reg))) and
  2117. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2118. (taicpu(hp1).oper[1]^.reg = reg);
  2119. A_INC,A_DEC,A_NEG,A_NOT:
  2120. isFoldableArithOp :=
  2121. (taicpu(hp1).oper[0]^.typ = top_reg) and
  2122. (taicpu(hp1).oper[0]^.reg = reg);
  2123. else
  2124. ;
  2125. end;
  2126. end;
  2127. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  2128. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  2129. var
  2130. hp2: tai;
  2131. begin
  2132. hp2 := p;
  2133. repeat
  2134. hp2 := tai(hp2.previous);
  2135. if assigned(hp2) and
  2136. (hp2.typ = ait_regalloc) and
  2137. (tai_regalloc(hp2).ratype=ra_dealloc) and
  2138. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  2139. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  2140. begin
  2141. RemoveInstruction(hp2);
  2142. break;
  2143. end;
  2144. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  2145. end;
  2146. begin
  2147. case current_procinfo.procdef.returndef.typ of
  2148. arraydef,recorddef,pointerdef,
  2149. stringdef,enumdef,procdef,objectdef,errordef,
  2150. filedef,setdef,procvardef,
  2151. classrefdef,forwarddef:
  2152. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2153. orddef:
  2154. if current_procinfo.procdef.returndef.size <> 0 then
  2155. begin
  2156. DoRemoveLastDeallocForFuncRes(RS_EAX);
  2157. { for int64/qword }
  2158. if current_procinfo.procdef.returndef.size = 8 then
  2159. DoRemoveLastDeallocForFuncRes(RS_EDX);
  2160. end;
  2161. else
  2162. ;
  2163. end;
  2164. end;
  2165. function TX86AsmOptimizer.OptPass1CMOVcc(var p: tai): Boolean;
  2166. var
  2167. hp1: tai;
  2168. operswap: poper;
  2169. begin
  2170. Result := False;
  2171. { Optimise:
  2172. cmov(c) %reg1,%reg2
  2173. mov %reg2,%reg1
  2174. (%reg2 dealloc.)
  2175. To:
  2176. cmov(~c) %reg2,%reg1
  2177. }
  2178. if (taicpu(p).oper[0]^.typ = top_reg) then
  2179. while GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) and
  2180. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  2181. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  2182. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[0]^.reg) do
  2183. begin
  2184. TransferUsedRegs(TmpUsedRegs);
  2185. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2186. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  2187. begin
  2188. DebugMsg(SPeepholeOptimization + 'CMOV(c) %reg1,%reg2; MOV %reg2,%reg1 -> CMOV(~c) %reg2,%reg1 (CMovMov2CMov)', p);
  2189. { Save time by swapping the pointers (they're both registers, so
  2190. we don't need to worry about reference counts) }
  2191. operswap := taicpu(p).oper[0];
  2192. taicpu(p).oper[0] := taicpu(p).oper[1];
  2193. taicpu(p).oper[1] := operswap;
  2194. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  2195. RemoveInstruction(hp1);
  2196. { It's still a CMOV, so we can look further ahead }
  2197. Include(OptsToCheck, aoc_ForceNewIteration);
  2198. { But first, let's see if this will get optimised again
  2199. (probably won't happen, but best to be sure) }
  2200. Continue;
  2201. end;
  2202. Break;
  2203. end;
  2204. end;
  2205. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  2206. var
  2207. hp1,hp2 : tai;
  2208. begin
  2209. result:=false;
  2210. if MatchOpType(taicpu(p),top_reg,top_reg) then
  2211. begin
  2212. { vmova* reg1,reg1
  2213. =>
  2214. <nop> }
  2215. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  2216. begin
  2217. RemoveCurrentP(p);
  2218. result:=true;
  2219. exit;
  2220. end;
  2221. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  2222. (hp1.typ = ait_instruction) and
  2223. (
  2224. { Under -O2 and below, the instructions are always adjacent }
  2225. not (cs_opt_level3 in current_settings.optimizerswitches) or
  2226. (taicpu(hp1).ops <= 1) or
  2227. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  2228. { If reg1 = reg3, reg1 must not be modified in between }
  2229. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  2230. ) then
  2231. begin
  2232. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  2233. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2234. begin
  2235. { vmova* reg1,reg2
  2236. ...
  2237. vmova* reg2,reg3
  2238. dealloc reg2
  2239. =>
  2240. vmova* reg1,reg3 }
  2241. TransferUsedRegs(TmpUsedRegs);
  2242. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2243. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2244. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) and
  2245. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2246. begin
  2247. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2248. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2249. TransferUsedRegs(TmpUsedRegs);
  2250. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, TmpUsedRegs);
  2251. RemoveInstruction(hp1);
  2252. result:=true;
  2253. exit;
  2254. end;
  2255. { special case:
  2256. vmova* reg1,<op>
  2257. ...
  2258. vmova* <op>,reg1
  2259. =>
  2260. vmova* reg1,<op> }
  2261. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2262. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2263. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2264. ) then
  2265. begin
  2266. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2267. RemoveInstruction(hp1);
  2268. result:=true;
  2269. exit;
  2270. end
  2271. end
  2272. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2273. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2274. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2275. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2276. ) and
  2277. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2278. begin
  2279. { vmova* reg1,reg2
  2280. ...
  2281. vmovs* reg2,<op>
  2282. dealloc reg2
  2283. =>
  2284. vmovs* reg1,<op> }
  2285. TransferUsedRegs(TmpUsedRegs);
  2286. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2287. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2288. begin
  2289. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2290. taicpu(p).opcode:=taicpu(hp1).opcode;
  2291. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2292. TransferUsedRegs(TmpUsedRegs);
  2293. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, TmpUsedRegs);
  2294. RemoveInstruction(hp1);
  2295. result:=true;
  2296. exit;
  2297. end
  2298. end;
  2299. if MatchInstruction(hp1,[A_VFMADDPD,
  2300. A_VFMADD132PD,
  2301. A_VFMADD132PS,
  2302. A_VFMADD132SD,
  2303. A_VFMADD132SS,
  2304. A_VFMADD213PD,
  2305. A_VFMADD213PS,
  2306. A_VFMADD213SD,
  2307. A_VFMADD213SS,
  2308. A_VFMADD231PD,
  2309. A_VFMADD231PS,
  2310. A_VFMADD231SD,
  2311. A_VFMADD231SS,
  2312. A_VFMADDSUB132PD,
  2313. A_VFMADDSUB132PS,
  2314. A_VFMADDSUB213PD,
  2315. A_VFMADDSUB213PS,
  2316. A_VFMADDSUB231PD,
  2317. A_VFMADDSUB231PS,
  2318. A_VFMSUB132PD,
  2319. A_VFMSUB132PS,
  2320. A_VFMSUB132SD,
  2321. A_VFMSUB132SS,
  2322. A_VFMSUB213PD,
  2323. A_VFMSUB213PS,
  2324. A_VFMSUB213SD,
  2325. A_VFMSUB213SS,
  2326. A_VFMSUB231PD,
  2327. A_VFMSUB231PS,
  2328. A_VFMSUB231SD,
  2329. A_VFMSUB231SS,
  2330. A_VFMSUBADD132PD,
  2331. A_VFMSUBADD132PS,
  2332. A_VFMSUBADD213PD,
  2333. A_VFMSUBADD213PS,
  2334. A_VFMSUBADD231PD,
  2335. A_VFMSUBADD231PS,
  2336. A_VFNMADD132PD,
  2337. A_VFNMADD132PS,
  2338. A_VFNMADD132SD,
  2339. A_VFNMADD132SS,
  2340. A_VFNMADD213PD,
  2341. A_VFNMADD213PS,
  2342. A_VFNMADD213SD,
  2343. A_VFNMADD213SS,
  2344. A_VFNMADD231PD,
  2345. A_VFNMADD231PS,
  2346. A_VFNMADD231SD,
  2347. A_VFNMADD231SS,
  2348. A_VFNMSUB132PD,
  2349. A_VFNMSUB132PS,
  2350. A_VFNMSUB132SD,
  2351. A_VFNMSUB132SS,
  2352. A_VFNMSUB213PD,
  2353. A_VFNMSUB213PS,
  2354. A_VFNMSUB213SD,
  2355. A_VFNMSUB213SS,
  2356. A_VFNMSUB231PD,
  2357. A_VFNMSUB231PS,
  2358. A_VFNMSUB231SD,
  2359. A_VFNMSUB231SS],[S_NO]) and
  2360. { we mix single and double opperations here because we assume that the compiler
  2361. generates vmovapd only after double operations and vmovaps only after single operations }
  2362. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2363. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2364. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2365. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2366. begin
  2367. TransferUsedRegs(TmpUsedRegs);
  2368. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2369. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2370. begin
  2371. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2372. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2373. RemoveCurrentP(p)
  2374. else
  2375. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2376. RemoveInstruction(hp2);
  2377. end;
  2378. end
  2379. else if (hp1.typ = ait_instruction) and
  2380. (((taicpu(p).opcode=A_MOVAPS) and
  2381. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2382. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2383. ((taicpu(p).opcode=A_MOVAPD) and
  2384. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2385. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2386. ) and
  2387. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2388. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2389. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2390. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2391. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2392. { change
  2393. movapX reg,reg2
  2394. addsX/subsX/... reg3, reg2
  2395. movapX reg2,reg
  2396. to
  2397. addsX/subsX/... reg3,reg
  2398. }
  2399. begin
  2400. TransferUsedRegs(TmpUsedRegs);
  2401. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2402. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2403. begin
  2404. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2405. debug_op2str(taicpu(p).opcode)+' '+
  2406. debug_op2str(taicpu(hp1).opcode)+' '+
  2407. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2408. { we cannot eliminate the first move if
  2409. the operations uses the same register for source and dest }
  2410. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2411. { Remember that hp1 is not necessarily the immediate
  2412. next instruction }
  2413. RemoveCurrentP(p);
  2414. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2415. RemoveInstruction(hp2);
  2416. result:=true;
  2417. end;
  2418. end
  2419. else if (hp1.typ = ait_instruction) and
  2420. (((taicpu(p).opcode=A_VMOVAPD) and
  2421. (taicpu(hp1).opcode=A_VCOMISD)) or
  2422. ((taicpu(p).opcode=A_VMOVAPS) and
  2423. ((taicpu(hp1).opcode=A_VCOMISS))
  2424. )
  2425. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2426. { change
  2427. movapX reg,reg1
  2428. vcomisX reg1,reg1
  2429. to
  2430. vcomisX reg,reg
  2431. }
  2432. begin
  2433. TransferUsedRegs(TmpUsedRegs);
  2434. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2435. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2436. begin
  2437. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2438. debug_op2str(taicpu(p).opcode)+' '+
  2439. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2440. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2441. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2442. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2443. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2444. RemoveCurrentP(p);
  2445. result:=true;
  2446. exit;
  2447. end;
  2448. end
  2449. end;
  2450. end;
  2451. end;
  2452. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2453. var
  2454. hp1 : tai;
  2455. begin
  2456. result:=false;
  2457. { replace
  2458. V<Op>X %mreg1,%mreg2,%mreg3
  2459. VMovX %mreg3,%mreg4
  2460. dealloc %mreg3
  2461. by
  2462. V<Op>X %mreg1,%mreg2,%mreg4
  2463. ?
  2464. }
  2465. if GetNextInstruction(p,hp1) and
  2466. { we mix single and double operations here because we assume that the compiler
  2467. generates vmovapd only after double operations and vmovaps only after single operations }
  2468. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2469. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2470. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2471. begin
  2472. TransferUsedRegs(TmpUsedRegs);
  2473. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2474. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2475. begin
  2476. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2477. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2478. RemoveInstruction(hp1);
  2479. result:=true;
  2480. end;
  2481. end;
  2482. end;
  2483. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2484. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2485. begin
  2486. Result := False;
  2487. { For safety reasons, only check for exact register matches }
  2488. { Check base register }
  2489. if (ref.base = AOldReg) then
  2490. begin
  2491. ref.base := ANewReg;
  2492. Result := True;
  2493. end;
  2494. { Check index register }
  2495. if (ref.index = AOldReg) and (getsupreg(ANewReg)<>RS_ESP) then
  2496. begin
  2497. ref.index := ANewReg;
  2498. Result := True;
  2499. end;
  2500. end;
  2501. { Replaces all references to AOldReg in an operand to ANewReg }
  2502. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2503. var
  2504. OldSupReg, NewSupReg: TSuperRegister;
  2505. OldSubReg, NewSubReg: TSubRegister;
  2506. OldRegType: TRegisterType;
  2507. ThisOper: POper;
  2508. begin
  2509. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2510. Result := False;
  2511. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2512. InternalError(2020011801);
  2513. OldSupReg := getsupreg(AOldReg);
  2514. OldSubReg := getsubreg(AOldReg);
  2515. OldRegType := getregtype(AOldReg);
  2516. NewSupReg := getsupreg(ANewReg);
  2517. NewSubReg := getsubreg(ANewReg);
  2518. if OldRegType <> getregtype(ANewReg) then
  2519. InternalError(2020011802);
  2520. if OldSubReg <> NewSubReg then
  2521. InternalError(2020011803);
  2522. case ThisOper^.typ of
  2523. top_reg:
  2524. if (
  2525. (ThisOper^.reg = AOldReg) or
  2526. (
  2527. (OldRegType = R_INTREGISTER) and
  2528. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2529. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2530. (
  2531. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2532. {$ifndef x86_64}
  2533. and (
  2534. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2535. don't have an 8-bit representation }
  2536. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2537. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2538. )
  2539. {$endif x86_64}
  2540. )
  2541. )
  2542. ) then
  2543. begin
  2544. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2545. Result := True;
  2546. end;
  2547. top_ref:
  2548. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2549. Result := True;
  2550. else
  2551. ;
  2552. end;
  2553. end;
  2554. { Replaces all references to AOldReg in an instruction to ANewReg }
  2555. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2556. const
  2557. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2558. var
  2559. OperIdx: Integer;
  2560. begin
  2561. Result := False;
  2562. for OperIdx := 0 to p.ops - 1 do
  2563. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2564. begin
  2565. { The shift and rotate instructions can only use CL }
  2566. if not (
  2567. (OperIdx = 0) and
  2568. { This second condition just helps to avoid unnecessarily
  2569. calling MatchInstruction for 10 different opcodes }
  2570. (p.oper[0]^.reg = NR_CL) and
  2571. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2572. ) then
  2573. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2574. end
  2575. else if p.oper[OperIdx]^.typ = top_ref then
  2576. { It's okay to replace registers in references that get written to }
  2577. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2578. end;
  2579. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2580. begin
  2581. Result :=
  2582. (ref^.index = NR_NO) and
  2583. (
  2584. {$ifdef x86_64}
  2585. (
  2586. (ref^.base = NR_RIP) and
  2587. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2588. ) or
  2589. {$endif x86_64}
  2590. (ref^.refaddr = addr_full) or
  2591. (ref^.base = NR_STACK_POINTER_REG) or
  2592. (ref^.base = current_procinfo.framepointer)
  2593. );
  2594. end;
  2595. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2596. var
  2597. l: asizeint;
  2598. begin
  2599. Result := False;
  2600. { Should have been checked previously }
  2601. if p.opcode <> A_LEA then
  2602. InternalError(2020072501);
  2603. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2604. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2605. not(cs_opt_size in current_settings.optimizerswitches) then
  2606. exit;
  2607. with p.oper[0]^.ref^ do
  2608. begin
  2609. if (base <> p.oper[1]^.reg) or
  2610. (index <> NR_NO) or
  2611. assigned(symbol) then
  2612. exit;
  2613. l:=offset;
  2614. if (l=1) and UseIncDec then
  2615. begin
  2616. p.opcode:=A_INC;
  2617. p.loadreg(0,p.oper[1]^.reg);
  2618. p.ops:=1;
  2619. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2620. end
  2621. else if (l=-1) and UseIncDec then
  2622. begin
  2623. p.opcode:=A_DEC;
  2624. p.loadreg(0,p.oper[1]^.reg);
  2625. p.ops:=1;
  2626. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2627. end
  2628. else
  2629. begin
  2630. if (l<0) and (l<>-2147483648) then
  2631. begin
  2632. p.opcode:=A_SUB;
  2633. p.loadConst(0,-l);
  2634. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2635. end
  2636. else
  2637. begin
  2638. p.opcode:=A_ADD;
  2639. p.loadConst(0,l);
  2640. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2641. end;
  2642. end;
  2643. end;
  2644. Result := True;
  2645. end;
  2646. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2647. var
  2648. CurrentReg, ReplaceReg: TRegister;
  2649. begin
  2650. Result := False;
  2651. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2652. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2653. case hp.opcode of
  2654. A_FSTSW, A_FNSTSW,
  2655. A_IN, A_INS, A_OUT, A_OUTS,
  2656. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2657. { These routines have explicit operands, but they are restricted in
  2658. what they can be (e.g. IN and OUT can only read from AL, AX or
  2659. EAX. }
  2660. Exit;
  2661. A_IMUL:
  2662. begin
  2663. { The 1-operand version writes to implicit registers
  2664. The 2-operand version reads from the first operator, and reads
  2665. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2666. the 3-operand version reads from a register that it doesn't write to
  2667. }
  2668. case hp.ops of
  2669. 1:
  2670. if (
  2671. (
  2672. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2673. ) or
  2674. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2675. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2676. begin
  2677. Result := True;
  2678. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2679. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2680. end;
  2681. 2:
  2682. { Only modify the first parameter }
  2683. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2684. begin
  2685. Result := True;
  2686. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2687. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2688. end;
  2689. 3:
  2690. { Only modify the second parameter }
  2691. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2692. begin
  2693. Result := True;
  2694. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2695. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2696. end;
  2697. else
  2698. InternalError(2020012901);
  2699. end;
  2700. end;
  2701. else
  2702. if (hp.ops > 0) and
  2703. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2704. begin
  2705. Result := True;
  2706. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2707. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2708. end;
  2709. end;
  2710. end;
  2711. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2712. var
  2713. hp2, hp_regalloc: tai;
  2714. p_SourceReg, p_TargetReg: TRegister;
  2715. begin
  2716. Result := False;
  2717. { Backward optimisation. If we have:
  2718. func. %reg1,%reg2
  2719. mov %reg2,%reg3
  2720. (dealloc %reg2)
  2721. Change to:
  2722. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2723. Perform similar optimisations with 1, 3 and 4-operand instructions
  2724. that only have one output.
  2725. }
  2726. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2727. begin
  2728. p_SourceReg := taicpu(p).oper[0]^.reg;
  2729. p_TargetReg := taicpu(p).oper[1]^.reg;
  2730. TransferUsedRegs(TmpUsedRegs);
  2731. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2732. GetLastInstruction(p, hp2) and
  2733. (hp2.typ = ait_instruction) and
  2734. { Have to make sure it's an instruction that only reads from
  2735. the first operands and only writes (not reads or modifies) to
  2736. the last one; in essence, a pure function such as BSR, POPCNT
  2737. or ANDN }
  2738. (
  2739. (
  2740. (taicpu(hp2).ops = 1) and
  2741. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2742. ) or
  2743. (
  2744. (taicpu(hp2).ops = 2) and
  2745. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2746. ) or
  2747. (
  2748. (taicpu(hp2).ops = 3) and
  2749. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2750. ) or
  2751. (
  2752. (taicpu(hp2).ops = 4) and
  2753. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2754. )
  2755. ) and
  2756. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2757. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2758. begin
  2759. case taicpu(hp2).opcode of
  2760. A_FSTSW, A_FNSTSW,
  2761. A_IN, A_INS, A_OUT, A_OUTS,
  2762. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2763. { These routines have explicit operands, but they are restricted in
  2764. what they can be (e.g. IN and OUT can only read from AL, AX or
  2765. EAX. }
  2766. ;
  2767. else
  2768. begin
  2769. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2770. { if %reg2 (p_SourceReg) is allocated before func., remove it completely }
  2771. hp_regalloc := FindRegAllocBackward(p_SourceReg, hp2);
  2772. if Assigned(hp_regalloc) then
  2773. begin
  2774. Asml.Remove(hp_regalloc);
  2775. if Assigned(FindRegDealloc(p_SourceReg, p)) then
  2776. begin
  2777. ExcludeRegFromUsedRegs(p_SourceReg, UsedRegs);
  2778. hp_regalloc.Free;
  2779. end
  2780. else
  2781. { If the register is not explicitly deallocated, it's
  2782. being reused, so move the allocation to after func. }
  2783. AsmL.InsertAfter(hp_regalloc, hp2);
  2784. end;
  2785. if not RegInInstruction(p_TargetReg, hp2) then
  2786. begin
  2787. TransferUsedRegs(TmpUsedRegs);
  2788. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2789. end;
  2790. { Actually make the changes }
  2791. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2792. RemoveCurrentp(p, hp1);
  2793. { If the Func was another MOV instruction, we might get
  2794. "mov %reg,%reg" that doesn't get removed in Pass 2
  2795. otherwise, so deal with it here (also do something
  2796. similar with lea (%reg),%reg}
  2797. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2798. begin
  2799. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2800. if p = hp2 then
  2801. RemoveCurrentp(p)
  2802. else
  2803. RemoveInstruction(hp2);
  2804. end;
  2805. Result := True;
  2806. Exit;
  2807. end;
  2808. end;
  2809. end;
  2810. end;
  2811. end;
  2812. function TX86AsmOptimizer.CheckMovMov2MovMov2(const p, hp1: tai) : boolean;
  2813. begin
  2814. Result := False;
  2815. if MatchOpType(taicpu(p),top_ref,top_reg) and
  2816. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2817. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2818. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2819. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2820. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2821. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2822. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2823. begin
  2824. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2825. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2826. Result := True;
  2827. Include(OptsToCheck, aoc_ForceNewIteration);
  2828. end;
  2829. end;
  2830. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2831. var
  2832. hp1, hp2, hp3, hp4: tai;
  2833. DoOptimisation, TempBool: Boolean;
  2834. {$ifdef x86_64}
  2835. NewConst: TCGInt;
  2836. {$endif x86_64}
  2837. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2838. begin
  2839. if taicpu(hp1).opcode = signed_movop then
  2840. begin
  2841. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2842. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2843. end
  2844. else
  2845. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2846. end;
  2847. function TryConstMerge(var p1, p2: tai): Boolean;
  2848. var
  2849. ThisRef: TReference;
  2850. begin
  2851. Result := False;
  2852. ThisRef := taicpu(p2).oper[1]^.ref^;
  2853. { Only permit writes to the stack, since we can guarantee alignment with that }
  2854. if (ThisRef.index = NR_NO) and
  2855. (
  2856. (ThisRef.base = NR_STACK_POINTER_REG) or
  2857. (ThisRef.base = current_procinfo.framepointer)
  2858. ) then
  2859. begin
  2860. case taicpu(p).opsize of
  2861. S_B:
  2862. begin
  2863. { Word writes must be on a 2-byte boundary }
  2864. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2865. begin
  2866. { Reduce offset of second reference to see if it is sequential with the first }
  2867. Dec(ThisRef.offset, 1);
  2868. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2869. begin
  2870. { Make sure the constants aren't represented as a
  2871. negative number, as these won't merge properly }
  2872. taicpu(p1).opsize := S_W;
  2873. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2874. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2875. RemoveInstruction(p2);
  2876. Result := True;
  2877. end;
  2878. end;
  2879. end;
  2880. S_W:
  2881. begin
  2882. { Longword writes must be on a 4-byte boundary }
  2883. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2884. begin
  2885. { Reduce offset of second reference to see if it is sequential with the first }
  2886. Dec(ThisRef.offset, 2);
  2887. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2888. begin
  2889. { Make sure the constants aren't represented as a
  2890. negative number, as these won't merge properly }
  2891. taicpu(p1).opsize := S_L;
  2892. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2893. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2894. RemoveInstruction(p2);
  2895. Result := True;
  2896. end;
  2897. end;
  2898. end;
  2899. {$ifdef x86_64}
  2900. S_L:
  2901. begin
  2902. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2903. see if the constants can be encoded this way. }
  2904. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2905. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2906. { Quadword writes must be on an 8-byte boundary }
  2907. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2908. begin
  2909. { Reduce offset of second reference to see if it is sequential with the first }
  2910. Dec(ThisRef.offset, 4);
  2911. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2912. begin
  2913. { Make sure the constants aren't represented as a
  2914. negative number, as these won't merge properly }
  2915. taicpu(p1).opsize := S_Q;
  2916. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2917. taicpu(p1).oper[0]^.val := NewConst;
  2918. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2919. RemoveInstruction(p2);
  2920. Result := True;
  2921. end;
  2922. end;
  2923. end;
  2924. {$endif x86_64}
  2925. else
  2926. ;
  2927. end;
  2928. end;
  2929. end;
  2930. var
  2931. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2932. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2933. NewSize: topsize; NewOffset: asizeint;
  2934. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2935. SourceRef, TargetRef: TReference;
  2936. MovAligned, MovUnaligned: TAsmOp;
  2937. ThisRef: TReference;
  2938. JumpTracking: TLinkedList;
  2939. begin
  2940. Result:=false;
  2941. { remove mov reg1,reg1? }
  2942. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2943. then
  2944. begin
  2945. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2946. { take care of the register (de)allocs following p }
  2947. RemoveCurrentP(p);
  2948. Result := True;
  2949. exit;
  2950. end;
  2951. { Prevent compiler warnings }
  2952. p_SourceReg := NR_NO;
  2953. p_TargetReg := NR_NO;
  2954. if taicpu(p).oper[1]^.typ = top_reg then
  2955. begin
  2956. { Saves on a large number of dereferences }
  2957. p_TargetReg := taicpu(p).oper[1]^.reg;
  2958. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  2959. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_TargetReg)
  2960. else
  2961. GetNextInstruction_p := GetNextInstruction(p, hp1);
  2962. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  2963. while True do
  2964. begin
  2965. if (taicpu(hp1).opcode = A_AND) and
  2966. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2967. begin
  2968. { A change has occurred, just not in p }
  2969. Include(OptsToCheck, aoc_ForceNewIteration);
  2970. if MatchOperand(taicpu(hp1).oper[1]^, p_TargetReg) then
  2971. begin
  2972. case taicpu(p).opsize of
  2973. S_L:
  2974. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2975. begin
  2976. { Optimize out:
  2977. mov x, %reg
  2978. and ffffffffh, %reg
  2979. }
  2980. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2981. RemoveInstruction(hp1);
  2982. Result:=true;
  2983. exit;
  2984. end;
  2985. S_Q: { TODO: Confirm if this is even possible }
  2986. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2987. begin
  2988. { Optimize out:
  2989. mov x, %reg
  2990. and ffffffffffffffffh, %reg
  2991. }
  2992. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2993. RemoveInstruction(hp1);
  2994. Result:=true;
  2995. exit;
  2996. end;
  2997. else
  2998. ;
  2999. end;
  3000. if (
  3001. { Make sure that if a reference is used, its registers
  3002. are not modified in between }
  3003. (
  3004. (taicpu(p).oper[0]^.typ = top_reg) and
  3005. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  3006. ) or
  3007. (
  3008. (taicpu(p).oper[0]^.typ = top_ref) and
  3009. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  3010. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1)
  3011. )
  3012. ) and
  3013. GetNextInstruction(hp1,hp2) and
  3014. MatchInstruction(hp2,A_TEST,[]) and
  3015. (
  3016. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  3017. (
  3018. { If the register being tested is smaller than the one
  3019. that received a bitwise AND, permit it if the constant
  3020. fits into the smaller size }
  3021. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  3022. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  3023. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  3024. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  3025. (
  3026. (
  3027. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  3028. (taicpu(hp1).oper[0]^.val <= $FF)
  3029. ) or
  3030. (
  3031. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  3032. (taicpu(hp1).oper[0]^.val <= $FFFF)
  3033. {$ifdef x86_64}
  3034. ) or
  3035. (
  3036. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  3037. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  3038. {$endif x86_64}
  3039. )
  3040. )
  3041. )
  3042. ) and
  3043. (
  3044. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  3045. MatchOperand(taicpu(hp2).oper[0]^,-1)
  3046. ) and
  3047. GetNextInstruction(hp2,hp3) and
  3048. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  3049. (taicpu(hp3).condition in [C_E,C_NE]) then
  3050. begin
  3051. TransferUsedRegs(TmpUsedRegs);
  3052. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3053. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3054. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  3055. begin
  3056. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  3057. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  3058. taicpu(hp1).opcode:=A_TEST;
  3059. { Shrink the TEST instruction down to the smallest possible size }
  3060. case taicpu(hp1).oper[0]^.val of
  3061. 0..255:
  3062. if (taicpu(hp1).opsize <> S_B)
  3063. {$ifndef x86_64}
  3064. and (
  3065. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  3066. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  3067. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  3068. )
  3069. {$endif x86_64}
  3070. then
  3071. begin
  3072. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3073. { Only print debug message if the TEST instruction
  3074. is a different size before and after }
  3075. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  3076. taicpu(hp1).opsize := S_B;
  3077. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3078. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3079. end;
  3080. 256..65535:
  3081. if (taicpu(hp1).opsize <> S_W) then
  3082. begin
  3083. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3084. { Only print debug message if the TEST instruction
  3085. is a different size before and after }
  3086. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3087. taicpu(hp1).opsize := S_W;
  3088. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3089. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3090. end;
  3091. {$ifdef x86_64}
  3092. 65536..$7FFFFFFF:
  3093. if (taicpu(hp1).opsize <> S_L) then
  3094. begin
  3095. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3096. { Only print debug message if the TEST instruction
  3097. is a different size before and after }
  3098. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3099. taicpu(hp1).opsize := S_L;
  3100. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3101. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3102. end;
  3103. {$endif x86_64}
  3104. else
  3105. ;
  3106. end;
  3107. RemoveInstruction(hp2);
  3108. RemoveCurrentP(p);
  3109. Result:=true;
  3110. exit;
  3111. end;
  3112. end;
  3113. end;
  3114. if IsMOVZXAcceptable and
  3115. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3116. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3117. (getsupreg(p_TargetReg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3118. then
  3119. begin
  3120. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3121. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3122. case taicpu(p).opsize of
  3123. S_B:
  3124. if (taicpu(hp1).oper[0]^.val = $ff) then
  3125. begin
  3126. { Convert:
  3127. movb x, %regl movb x, %regl
  3128. andw ffh, %regw andl ffh, %regd
  3129. To:
  3130. movzbw x, %regd movzbl x, %regd
  3131. (Identical registers, just different sizes)
  3132. }
  3133. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3134. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3135. case taicpu(hp1).opsize of
  3136. S_W: NewSize := S_BW;
  3137. S_L: NewSize := S_BL;
  3138. {$ifdef x86_64}
  3139. S_Q: NewSize := S_BQ;
  3140. {$endif x86_64}
  3141. else
  3142. InternalError(2018011510);
  3143. end;
  3144. end
  3145. else
  3146. NewSize := S_NO;
  3147. S_W:
  3148. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3149. begin
  3150. { Convert:
  3151. movw x, %regw
  3152. andl ffffh, %regd
  3153. To:
  3154. movzwl x, %regd
  3155. (Identical registers, just different sizes)
  3156. }
  3157. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3158. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3159. case taicpu(hp1).opsize of
  3160. S_L: NewSize := S_WL;
  3161. {$ifdef x86_64}
  3162. S_Q: NewSize := S_WQ;
  3163. {$endif x86_64}
  3164. else
  3165. InternalError(2018011511);
  3166. end;
  3167. end
  3168. else
  3169. NewSize := S_NO;
  3170. else
  3171. NewSize := S_NO;
  3172. end;
  3173. if NewSize <> S_NO then
  3174. begin
  3175. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3176. { The actual optimization }
  3177. taicpu(p).opcode := A_MOVZX;
  3178. taicpu(p).changeopsize(NewSize);
  3179. taicpu(p).loadoper(1, taicpu(hp1).oper[1]^);
  3180. { Make sure we deal with any reference counts that were increased }
  3181. if taicpu(hp1).oper[1]^.typ = top_ref then
  3182. begin
  3183. if Assigned(taicpu(hp1).oper[1]^.ref^.symbol) then
  3184. taicpu(hp1).oper[1]^.ref^.symbol.decrefs;
  3185. if Assigned(taicpu(hp1).oper[1]^.ref^.relsymbol) then
  3186. taicpu(hp1).oper[1]^.ref^.relsymbol.decrefs;
  3187. end;
  3188. { Safeguard if "and" is followed by a conditional command }
  3189. TransferUsedRegs(TmpUsedRegs);
  3190. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.next), hp1);
  3191. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3192. begin
  3193. { At this point, the "and" command is effectively equivalent to
  3194. "test %reg,%reg". This will be handled separately by the
  3195. Peephole Optimizer. [Kit] }
  3196. DebugMsg(SPeepholeOptimization + PreMessage +
  3197. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3198. end
  3199. else
  3200. begin
  3201. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3202. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3203. RemoveInstruction(hp1);
  3204. end;
  3205. Result := True;
  3206. Exit;
  3207. { Go through DeepMOVOpt again (jump to "while True do") }
  3208. Continue;
  3209. end;
  3210. end;
  3211. end;
  3212. if taicpu(p).oper[0]^.typ = top_reg then
  3213. begin
  3214. p_SourceReg := taicpu(p).oper[0]^.reg;
  3215. { Look for:
  3216. mov %reg1,%reg2
  3217. ??? %reg2,r/m
  3218. Change to:
  3219. mov %reg1,%reg2
  3220. ??? %reg1,r/m
  3221. }
  3222. if RegReadByInstruction(p_TargetReg, hp1) and
  3223. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3224. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  3225. begin
  3226. { A change has occurred, just not in p }
  3227. Include(OptsToCheck, aoc_ForceNewIteration);
  3228. TransferUsedRegs(TmpUsedRegs);
  3229. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3230. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3231. { Just in case something didn't get modified (e.g. an
  3232. implicit register) }
  3233. not RegReadByInstruction(p_TargetReg, hp1) then
  3234. begin
  3235. { We can remove the original MOV }
  3236. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  3237. RemoveCurrentP(p);
  3238. { UsedRegs got updated by RemoveCurrentp }
  3239. Result := True;
  3240. Exit;
  3241. end;
  3242. { If we know a MOV instruction has become a null operation, we might as well
  3243. get rid of it now to save time. }
  3244. if (taicpu(hp1).opcode = A_MOV) and
  3245. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3246. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  3247. { Just being a register is enough to confirm it's a null operation }
  3248. (taicpu(hp1).oper[0]^.typ = top_reg) then
  3249. begin
  3250. Result := True;
  3251. { Speed-up to reduce a pipeline stall... if we had something like...
  3252. movl %eax,%edx
  3253. movw %dx,%ax
  3254. ... the second instruction would change to movw %ax,%ax, but
  3255. given that it is now %ax that's active rather than %eax,
  3256. penalties might occur due to a partial register write, so instead,
  3257. change it to a MOVZX instruction when optimising for speed.
  3258. }
  3259. if not (cs_opt_size in current_settings.optimizerswitches) and
  3260. IsMOVZXAcceptable and
  3261. (taicpu(hp1).opsize < taicpu(p).opsize)
  3262. {$ifdef x86_64}
  3263. { operations already implicitly set the upper 64 bits to zero }
  3264. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  3265. {$endif x86_64}
  3266. then
  3267. begin
  3268. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  3269. case taicpu(p).opsize of
  3270. S_W:
  3271. if taicpu(hp1).opsize = S_B then
  3272. taicpu(hp1).opsize := S_BL
  3273. else
  3274. InternalError(2020012911);
  3275. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  3276. case taicpu(hp1).opsize of
  3277. S_B:
  3278. taicpu(hp1).opsize := S_BL;
  3279. S_W:
  3280. taicpu(hp1).opsize := S_WL;
  3281. else
  3282. InternalError(2020012912);
  3283. end;
  3284. else
  3285. InternalError(2020012910);
  3286. end;
  3287. taicpu(hp1).opcode := A_MOVZX;
  3288. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3289. end
  3290. else
  3291. begin
  3292. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  3293. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  3294. RemoveInstruction(hp1);
  3295. { The instruction after what was hp1 is now the immediate next instruction,
  3296. so we can continue to make optimisations if it's present }
  3297. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  3298. Exit;
  3299. hp1 := hp2;
  3300. end;
  3301. end;
  3302. end;
  3303. {$ifdef x86_64}
  3304. { Change:
  3305. movl %reg1l,%reg2l
  3306. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3307. To:
  3308. movl %reg1l,%reg2l
  3309. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3310. If %reg1 = %reg3, convert to:
  3311. movl %reg1l,%reg2l
  3312. andl %reg1l,%reg1l
  3313. }
  3314. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3315. not RegModifiedBetween(p_SourceReg, p, hp1) and
  3316. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3317. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg) then
  3318. begin
  3319. TransferUsedRegs(TmpUsedRegs);
  3320. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3321. taicpu(hp1).opsize := S_L;
  3322. taicpu(hp1).loadreg(0, p_SourceReg);
  3323. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3324. AllocRegBetween(p_SourceReg, p, hp1, UsedRegs);
  3325. if (p_SourceReg = taicpu(hp1).oper[1]^.reg) then
  3326. begin
  3327. { %reg1 = %reg3 }
  3328. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3329. taicpu(hp1).opcode := A_AND;
  3330. end
  3331. else
  3332. begin
  3333. { %reg1 <> %reg3 }
  3334. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3335. end;
  3336. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3337. begin
  3338. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3339. RemoveCurrentP(p);
  3340. Result := True;
  3341. Exit;
  3342. end
  3343. else
  3344. begin
  3345. { Initial instruction wasn't actually changed }
  3346. Include(OptsToCheck, aoc_ForceNewIteration);
  3347. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3348. appears below since %reg1 has technically changed }
  3349. if taicpu(hp1).opcode = A_AND then
  3350. Exit;
  3351. end;
  3352. end;
  3353. {$endif x86_64}
  3354. end
  3355. else if taicpu(p).oper[0]^.typ = top_const then
  3356. begin
  3357. if (taicpu(hp1).opcode = A_OR) and
  3358. (taicpu(p).oper[1]^.typ = top_reg) and
  3359. MatchOperand(taicpu(p).oper[0]^, 0) and
  3360. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3361. begin
  3362. { mov 0, %reg
  3363. or ###,%reg
  3364. Change to (only if the flags are not used):
  3365. mov ###,%reg
  3366. }
  3367. TransferUsedRegs(TmpUsedRegs);
  3368. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3369. DoOptimisation := True;
  3370. { Even if the flags are used, we might be able to do the optimisation
  3371. if the conditions are predictable }
  3372. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3373. begin
  3374. { Only perform if ### = %reg (the same register) or equal to 0,
  3375. so %reg is guaranteed to still have a value of zero }
  3376. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3377. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3378. begin
  3379. hp2 := hp1;
  3380. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3381. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3382. GetNextInstruction(hp2, hp3) do
  3383. begin
  3384. { Don't continue modifying if the flags state is getting changed }
  3385. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3386. Break;
  3387. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3388. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3389. begin
  3390. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3391. begin
  3392. { Condition is always true }
  3393. case taicpu(hp3).opcode of
  3394. A_Jcc:
  3395. begin
  3396. { Check for jump shortcuts before we destroy the condition }
  3397. hp4 := hp3;
  3398. DoJumpOptimizations(hp3, TempBool);
  3399. { Make sure hp3 hasn't changed }
  3400. if (hp4 = hp3) then
  3401. begin
  3402. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3403. MakeUnconditional(taicpu(hp3));
  3404. end;
  3405. Result := True;
  3406. end;
  3407. A_CMOVcc:
  3408. begin
  3409. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3410. taicpu(hp3).opcode := A_MOV;
  3411. taicpu(hp3).condition := C_None;
  3412. Result := True;
  3413. end;
  3414. A_SETcc:
  3415. begin
  3416. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3417. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3418. taicpu(hp3).opcode := A_MOV;
  3419. taicpu(hp3).ops := 2;
  3420. taicpu(hp3).condition := C_None;
  3421. taicpu(hp3).opsize := S_B;
  3422. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3423. taicpu(hp3).loadconst(0, 1);
  3424. Result := True;
  3425. end;
  3426. else
  3427. InternalError(2021090701);
  3428. end;
  3429. end
  3430. 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
  3431. begin
  3432. { Condition is always false }
  3433. case taicpu(hp3).opcode of
  3434. A_Jcc:
  3435. begin
  3436. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3437. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3438. RemoveInstruction(hp3);
  3439. Result := True;
  3440. { Since hp3 was deleted, hp2 must not be updated }
  3441. Continue;
  3442. end;
  3443. A_CMOVcc:
  3444. begin
  3445. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3446. RemoveInstruction(hp3);
  3447. Result := True;
  3448. { Since hp3 was deleted, hp2 must not be updated }
  3449. Continue;
  3450. end;
  3451. A_SETcc:
  3452. begin
  3453. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3454. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3455. taicpu(hp3).opcode := A_MOV;
  3456. taicpu(hp3).ops := 2;
  3457. taicpu(hp3).condition := C_None;
  3458. taicpu(hp3).opsize := S_B;
  3459. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3460. taicpu(hp3).loadconst(0, 0);
  3461. Result := True;
  3462. end;
  3463. else
  3464. InternalError(2021090702);
  3465. end;
  3466. end
  3467. else
  3468. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3469. DoOptimisation := False;
  3470. end;
  3471. hp2 := hp3;
  3472. end;
  3473. if DoOptimisation then
  3474. begin
  3475. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3476. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3477. { Flags are still in use - don't optimise }
  3478. DoOptimisation := False;
  3479. end;
  3480. end
  3481. else
  3482. DoOptimisation := False;
  3483. end;
  3484. if DoOptimisation then
  3485. begin
  3486. {$ifdef x86_64}
  3487. { OR only supports 32-bit sign-extended constants for 64-bit
  3488. instructions, so compensate for this if the constant is
  3489. encoded as a value greater than or equal to 2^31 }
  3490. if (taicpu(hp1).opsize = S_Q) and
  3491. (taicpu(hp1).oper[0]^.typ = top_const) and
  3492. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3493. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3494. {$endif x86_64}
  3495. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3496. taicpu(hp1).opcode := A_MOV;
  3497. RemoveCurrentP(p);
  3498. Result := True;
  3499. Exit;
  3500. end;
  3501. end;
  3502. end
  3503. else if
  3504. { oper[0] is a reference }
  3505. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) then
  3506. begin
  3507. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  3508. begin
  3509. if ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3510. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3511. ) or
  3512. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3513. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3514. )
  3515. ) and
  3516. not RegModifiedBetween(Taicpu(hp1).oper[1]^.reg, p, hp1) then
  3517. { mov ref,reg1
  3518. lea (reg1,reg2),reg2
  3519. to
  3520. add ref,reg2 }
  3521. begin
  3522. TransferUsedRegs(TmpUsedRegs);
  3523. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3524. { If the flags register is in use, don't change the instruction to an
  3525. ADD otherwise this will scramble the flags. [Kit] }
  3526. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3527. { reg1 may not be used afterwards }
  3528. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3529. begin
  3530. Taicpu(hp1).opcode:=A_ADD;
  3531. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3532. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3533. RemoveCurrentp(p);
  3534. result:=true;
  3535. exit;
  3536. end;
  3537. end;
  3538. { If the LEA instruction can be converted into an arithmetic instruction,
  3539. it may be possible to then fold it in the next optimisation. }
  3540. if ConvertLEA(taicpu(hp1)) then
  3541. Include(OptsToCheck, aoc_ForceNewIteration);
  3542. end;
  3543. {
  3544. mov ref,reg0
  3545. <op> reg0,reg1
  3546. dealloc reg0
  3547. to
  3548. <op> ref,reg1
  3549. }
  3550. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3551. (taicpu(hp1).oper[0]^.reg = p_TargetReg) and
  3552. MatchInstruction(hp1, [A_AND, A_OR, A_XOR, A_ADD, A_SUB, A_CMP, A_TEST, A_CMOVcc, A_BSR, A_BSF, A_POPCNT, A_LZCNT], [taicpu(p).opsize]) and
  3553. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, p_TargetReg) and
  3554. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3555. begin
  3556. TransferUsedRegs(TmpUsedRegs);
  3557. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3558. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) then
  3559. begin
  3560. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  3561. { loadref increases the reference count, so decrement it again }
  3562. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3563. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3564. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3565. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3566. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3567. { See if we can remove the allocation of reg0 }
  3568. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3569. TryRemoveRegAlloc(p_TargetReg, p, hp1);
  3570. RemoveCurrentp(p);
  3571. Result:=true;
  3572. exit;
  3573. end;
  3574. end;
  3575. end;
  3576. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  3577. overwrites the original destination register. e.g.
  3578. movl ###,%reg2d
  3579. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  3580. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  3581. }
  3582. if MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  3583. (taicpu(hp1).oper[1]^.typ = top_reg) and
  3584. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  3585. begin
  3586. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  3587. begin
  3588. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  3589. case taicpu(p).oper[0]^.typ of
  3590. top_const:
  3591. { We have something like:
  3592. movb $x, %regb
  3593. movzbl %regb,%regd
  3594. Change to:
  3595. movl $x, %regd
  3596. }
  3597. begin
  3598. case taicpu(hp1).opsize of
  3599. S_BW:
  3600. begin
  3601. convert_mov_value(A_MOVSX, $FF);
  3602. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  3603. taicpu(p).opsize := S_W;
  3604. end;
  3605. S_BL:
  3606. begin
  3607. convert_mov_value(A_MOVSX, $FF);
  3608. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3609. taicpu(p).opsize := S_L;
  3610. end;
  3611. S_WL:
  3612. begin
  3613. convert_mov_value(A_MOVSX, $FFFF);
  3614. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3615. taicpu(p).opsize := S_L;
  3616. end;
  3617. {$ifdef x86_64}
  3618. S_BQ:
  3619. begin
  3620. convert_mov_value(A_MOVSX, $FF);
  3621. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3622. taicpu(p).opsize := S_Q;
  3623. end;
  3624. S_WQ:
  3625. begin
  3626. convert_mov_value(A_MOVSX, $FFFF);
  3627. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3628. taicpu(p).opsize := S_Q;
  3629. end;
  3630. S_LQ:
  3631. begin
  3632. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  3633. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  3634. taicpu(p).opsize := S_Q;
  3635. end;
  3636. {$endif x86_64}
  3637. else
  3638. { If hp1 was a MOV instruction, it should have been
  3639. optimised already }
  3640. InternalError(2020021001);
  3641. end;
  3642. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  3643. RemoveInstruction(hp1);
  3644. Result := True;
  3645. Exit;
  3646. end;
  3647. top_ref:
  3648. begin
  3649. { We have something like:
  3650. movb mem, %regb
  3651. movzbl %regb,%regd
  3652. Change to:
  3653. movzbl mem, %regd
  3654. }
  3655. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  3656. begin
  3657. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  3658. taicpu(p).opcode := taicpu(hp1).opcode;
  3659. taicpu(p).opsize := taicpu(hp1).opsize;
  3660. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  3661. RemoveInstruction(hp1);
  3662. Result := True;
  3663. Exit;
  3664. end;
  3665. end;
  3666. else
  3667. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  3668. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  3669. Exit;
  3670. end;
  3671. end
  3672. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  3673. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  3674. optimised }
  3675. else
  3676. begin
  3677. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  3678. RemoveCurrentP(p);
  3679. Result := True;
  3680. Exit;
  3681. end;
  3682. end;
  3683. if (taicpu(hp1).opcode = A_MOV) and
  3684. (
  3685. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  3686. {$ifdef x86_64}
  3687. or (
  3688. { Permit zero extension from 32- to 64-bit when writing
  3689. a constant (it will be checked to see if it fits into
  3690. a signed 32-bit integer) }
  3691. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3692. (
  3693. { Valid situations... writing an unsigned 32-bit
  3694. immediate, or the destination is a 64-bit register }
  3695. (taicpu(p).oper[0]^.typ = top_const) or
  3696. (taicpu(hp1).oper[1]^.typ = top_reg)
  3697. ) and
  3698. (taicpu(hp1).oper[0]^.typ = top_reg) and
  3699. SuperRegistersEqual(p_TargetReg, taicpu(hp1).oper[0]^.reg)
  3700. )
  3701. {$endif x86_64}
  3702. ) then
  3703. begin
  3704. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3705. TransferUsedRegs(TmpUsedRegs);
  3706. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  3707. { we have
  3708. mov x, %treg
  3709. mov %treg, y
  3710. }
  3711. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3712. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3713. begin
  3714. { we've got
  3715. mov x, %treg
  3716. mov %treg, y
  3717. with %treg is not used after }
  3718. case taicpu(p).oper[0]^.typ Of
  3719. { top_reg is covered by DeepMOVOpt }
  3720. top_const:
  3721. begin
  3722. { change
  3723. mov const, %treg
  3724. mov %treg, y
  3725. to
  3726. mov const, y
  3727. }
  3728. {$ifdef x86_64}
  3729. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3730. (
  3731. { For 32-to-64-bit zero-extension, the immediate
  3732. must be between 0 and 2^31 - 1}
  3733. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3734. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3735. ) or
  3736. (
  3737. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3738. (
  3739. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3740. )
  3741. ) then
  3742. {$endif x86_64}
  3743. begin
  3744. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3745. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done', hp1);
  3746. RemoveCurrentP(p);
  3747. Result := True;
  3748. Exit;
  3749. end;
  3750. end;
  3751. top_ref:
  3752. case taicpu(hp1).oper[1]^.typ of
  3753. top_reg:
  3754. { change
  3755. mov mem, %treg
  3756. mov %treg, %reg
  3757. to
  3758. mov mem, %reg"
  3759. }
  3760. if not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1) then
  3761. begin
  3762. {$ifdef x86_64}
  3763. { If zero extending from 32-bit to 64-bit,
  3764. we have to make sure the replaced
  3765. register is the right size }
  3766. taicpu(p).loadreg(1, newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),getsubreg(p_TargetReg)));
  3767. {$else}
  3768. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3769. {$endif x86_64}
  3770. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3a done', p);
  3771. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  3772. RemoveInstruction(hp1);
  3773. Result := True;
  3774. Exit;
  3775. end
  3776. else if
  3777. { Make sure that if a reference is used, its
  3778. registers are not modified in between }
  3779. not RefModifiedBetween(taicpu(p).oper[0]^.ref^, topsize2memsize[taicpu(p).opsize] shr 3, p, hp1) then
  3780. begin
  3781. if (taicpu(p).oper[0]^.ref^.base <> NR_NO){$ifdef x86_64} and (taicpu(p).oper[0]^.ref^.base <> NR_RIP){$endif x86_64} then
  3782. AllocRegBetween(taicpu(p).oper[0]^.ref^.base, p, hp1, UsedRegs);
  3783. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and (taicpu(p).oper[0]^.ref^.index <> taicpu(p).oper[0]^.ref^.base) then
  3784. AllocRegBetween(taicpu(p).oper[0]^.ref^.index, p, hp1, UsedRegs);
  3785. taicpu(hp1).loadref(0, taicpu(p).oper[0]^.ref^);
  3786. if Assigned(taicpu(p).oper[0]^.ref^.symbol) then
  3787. taicpu(p).oper[0]^.ref^.symbol.decrefs;
  3788. if Assigned(taicpu(p).oper[0]^.ref^.relsymbol) then
  3789. taicpu(p).oper[0]^.ref^.relsymbol.decrefs;
  3790. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done', hp1);
  3791. RemoveCurrentP(p);
  3792. Result := True;
  3793. Exit;
  3794. end;
  3795. top_ref:
  3796. if not RegInRef(p_TargetReg, taicpu(p).oper[0]^.ref^) then
  3797. begin
  3798. {$ifdef x86_64}
  3799. { Look for the following to simplify:
  3800. mov x(mem1), %reg
  3801. mov %reg, y(mem2)
  3802. mov x+8(mem1), %reg
  3803. mov %reg, y+8(mem2)
  3804. Change to:
  3805. movdqu x(mem1), %xmmreg
  3806. movdqu %xmmreg, y(mem2)
  3807. ...but only as long as the memory blocks don't overlap
  3808. }
  3809. SourceRef := taicpu(p).oper[0]^.ref^;
  3810. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3811. if (taicpu(p).opsize = S_Q) and
  3812. not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  3813. GetNextInstruction(hp1, hp2) and
  3814. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3815. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3816. begin
  3817. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3818. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3819. Inc(SourceRef.offset, 8);
  3820. if UseAVX then
  3821. begin
  3822. MovAligned := A_VMOVDQA;
  3823. MovUnaligned := A_VMOVDQU;
  3824. end
  3825. else
  3826. begin
  3827. MovAligned := A_MOVDQA;
  3828. MovUnaligned := A_MOVDQU;
  3829. end;
  3830. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3831. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3832. begin
  3833. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3834. Inc(TargetRef.offset, 8);
  3835. if GetNextInstruction(hp2, hp3) and
  3836. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3837. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3838. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3839. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3840. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3841. begin
  3842. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3843. if NewMMReg <> NR_NO then
  3844. begin
  3845. { Remember that the offsets are 8 ahead }
  3846. if ((SourceRef.offset mod 16) = 8) and
  3847. (
  3848. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3849. (SourceRef.base = current_procinfo.framepointer) or
  3850. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3851. ) then
  3852. taicpu(p).opcode := MovAligned
  3853. else
  3854. taicpu(p).opcode := MovUnaligned;
  3855. taicpu(p).opsize := S_XMM;
  3856. taicpu(p).oper[1]^.reg := NewMMReg;
  3857. if ((TargetRef.offset mod 16) = 8) and
  3858. (
  3859. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3860. (TargetRef.base = current_procinfo.framepointer) or
  3861. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3862. ) then
  3863. taicpu(hp1).opcode := MovAligned
  3864. else
  3865. taicpu(hp1).opcode := MovUnaligned;
  3866. taicpu(hp1).opsize := S_XMM;
  3867. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3868. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3869. RemoveInstruction(hp2);
  3870. RemoveInstruction(hp3);
  3871. Result := True;
  3872. Exit;
  3873. end;
  3874. end;
  3875. end
  3876. else
  3877. begin
  3878. { See if the next references are 8 less rather than 8 greater }
  3879. Dec(SourceRef.offset, 16); { -8 the other way }
  3880. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3881. begin
  3882. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3883. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3884. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3885. GetNextInstruction(hp2, hp3) and
  3886. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3887. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3888. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3889. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3890. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3891. begin
  3892. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3893. if NewMMReg <> NR_NO then
  3894. begin
  3895. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3896. if ((SourceRef.offset mod 16) = 0) and
  3897. (
  3898. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3899. (SourceRef.base = current_procinfo.framepointer) or
  3900. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3901. ) then
  3902. taicpu(hp2).opcode := MovAligned
  3903. else
  3904. taicpu(hp2).opcode := MovUnaligned;
  3905. taicpu(hp2).opsize := S_XMM;
  3906. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3907. if ((TargetRef.offset mod 16) = 0) and
  3908. (
  3909. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3910. (TargetRef.base = current_procinfo.framepointer) or
  3911. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3912. ) then
  3913. taicpu(hp3).opcode := MovAligned
  3914. else
  3915. taicpu(hp3).opcode := MovUnaligned;
  3916. taicpu(hp3).opsize := S_XMM;
  3917. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3918. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3919. RemoveInstruction(hp1);
  3920. RemoveCurrentP(p);
  3921. Result := True;
  3922. Exit;
  3923. end;
  3924. end;
  3925. end;
  3926. end;
  3927. end;
  3928. {$endif x86_64}
  3929. end;
  3930. else
  3931. { The write target should be a reg or a ref }
  3932. InternalError(2021091601);
  3933. end;
  3934. else
  3935. ;
  3936. end;
  3937. end
  3938. else if (taicpu(p).oper[0]^.typ = top_const) and
  3939. { %treg is used afterwards, but all eventualities other
  3940. than the first MOV instruction being a constant are
  3941. covered by DeepMOVOpt, so only check for that }
  3942. (
  3943. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3944. not (cs_opt_size in current_settings.optimizerswitches) or
  3945. (taicpu(hp1).opsize = S_B)
  3946. ) and
  3947. (
  3948. (taicpu(hp1).oper[1]^.typ=top_reg) or
  3949. (
  3950. { For 32-to-64-bit zero-extension, the immediate
  3951. must be between 0 and 2^31 - 1}
  3952. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and
  3953. ((taicpu(p).oper[0]^.val>=0) and (taicpu(p).oper[0]^.val<=high(longint)))
  3954. ) or
  3955. (
  3956. not ((taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q)) and
  3957. (
  3958. (taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))
  3959. )
  3960. )
  3961. ) then
  3962. begin
  3963. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3964. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3965. Include(OptsToCheck, aoc_ForceNewIteration);
  3966. end;
  3967. end;
  3968. Break;
  3969. end;
  3970. end;
  3971. if taicpu(p).oper[0]^.typ = top_reg then
  3972. begin
  3973. { oper[1] is a reference }
  3974. { Saves on a large number of dereferences }
  3975. p_SourceReg := taicpu(p).oper[0]^.reg;
  3976. if NotFirstIteration and (cs_opt_level3 in current_settings.optimizerswitches) then
  3977. GetNextInstruction_p := GetNextInstructionUsingReg(p, hp1, p_SourceReg)
  3978. else
  3979. GetNextInstruction_p := GetNextInstruction(p, hp1);
  3980. if GetNextInstruction_p and (hp1.typ = ait_instruction) then
  3981. begin
  3982. if taicpu(p).oper[1]^.typ = top_reg then
  3983. begin
  3984. p_TargetReg := taicpu(p).oper[1]^.reg;
  3985. { Change:
  3986. movl %reg1,%reg2
  3987. ...
  3988. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3989. ...
  3990. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3991. To:
  3992. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3993. ...
  3994. movl x(%reg1),%reg1
  3995. ...
  3996. movl %reg1,%regX
  3997. }
  3998. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  3999. (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4000. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  4001. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  4002. not RegModifiedBetween(p_TargetReg, p, hp1) and
  4003. GetNextInstructionUsingReg(hp1, hp2, p_TargetReg) and
  4004. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  4005. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } and
  4006. not RegModifiedBetween(p_SourceReg, hp1, hp2) then
  4007. begin
  4008. SourceRef := taicpu(hp2).oper[0]^.ref^;
  4009. if RegInRef(p_TargetReg, SourceRef) and
  4010. { If %reg1 also appears in the second reference, then it will
  4011. not refer to the same memory block as the first reference }
  4012. not RegInRef(p_SourceReg, SourceRef) then
  4013. begin
  4014. { Check to see if the references match if %reg2 is changed to %reg1 }
  4015. if SourceRef.base = p_TargetReg then
  4016. SourceRef.base := p_SourceReg;
  4017. if SourceRef.index = p_TargetReg then
  4018. SourceRef.index := p_SourceReg;
  4019. { RefsEqual also checks to ensure both references are non-volatile }
  4020. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  4021. begin
  4022. taicpu(hp2).loadreg(0, p_SourceReg);
  4023. TransferUsedRegs(TmpUsedRegs);
  4024. UpdateUsedRegsBetween(TmpUsedRegs, tai(p.Next), hp1);
  4025. { Make sure the register is allocated between these instructions
  4026. even though it doesn't change value, since it may cause
  4027. optimisations on a later pass to behave incorrectly. (Fixes #41155) }
  4028. AllocRegBetween(p_SourceReg, hp1, hp2, TmpUsedRegs);
  4029. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  4030. Result := True;
  4031. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  4032. begin
  4033. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  4034. RemoveCurrentP(p);
  4035. Exit;
  4036. end
  4037. else
  4038. begin
  4039. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  4040. begin
  4041. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  4042. RemoveCurrentP(p);
  4043. Exit;
  4044. end;
  4045. end;
  4046. { If we reach this point, p and hp1 weren't actually modified,
  4047. so we can do a bit more work on this pass }
  4048. end;
  4049. end;
  4050. end;
  4051. end;
  4052. end;
  4053. end;
  4054. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  4055. { All the next optimisations require a next instruction }
  4056. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  4057. Exit;
  4058. { Next instruction is also a MOV ? }
  4059. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  4060. begin
  4061. if MatchOpType(taicpu(p), top_const, top_ref) and
  4062. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4063. TryConstMerge(p, hp1) then
  4064. begin
  4065. Result := True;
  4066. { In case we have four byte writes in a row, check for 2 more
  4067. right now so we don't have to wait for another iteration of
  4068. pass 1
  4069. }
  4070. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  4071. case taicpu(p).opsize of
  4072. S_W:
  4073. begin
  4074. if GetNextInstruction(p, hp1) and
  4075. MatchInstruction(hp1, A_MOV, [S_B]) and
  4076. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4077. GetNextInstruction(hp1, hp2) and
  4078. MatchInstruction(hp2, A_MOV, [S_B]) and
  4079. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4080. { Try to merge the two bytes }
  4081. TryConstMerge(hp1, hp2) then
  4082. { Now try to merge the two words (hp2 will get deleted) }
  4083. TryConstMerge(p, hp1);
  4084. end;
  4085. S_L:
  4086. begin
  4087. { Though this only really benefits x86_64 and not i386, it
  4088. gets a potential optimisation done faster and hence
  4089. reduces the number of times OptPass1MOV is entered }
  4090. if GetNextInstruction(p, hp1) and
  4091. MatchInstruction(hp1, A_MOV, [S_W]) and
  4092. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4093. GetNextInstruction(hp1, hp2) and
  4094. MatchInstruction(hp2, A_MOV, [S_W]) and
  4095. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4096. { Try to merge the two words }
  4097. TryConstMerge(hp1, hp2) then
  4098. { This will always fail on i386, so don't bother
  4099. calling it unless we're doing x86_64 }
  4100. {$ifdef x86_64}
  4101. { Now try to merge the two longwords (hp2 will get deleted) }
  4102. TryConstMerge(p, hp1)
  4103. {$endif x86_64}
  4104. ;
  4105. end;
  4106. else
  4107. ;
  4108. end;
  4109. Exit;
  4110. end;
  4111. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4112. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4113. { mov reg1, mem1 or mov mem1, reg1
  4114. mov mem2, reg2 mov reg2, mem2}
  4115. begin
  4116. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4117. { mov reg1, mem1 or mov mem1, reg1
  4118. mov mem2, reg1 mov reg2, mem1}
  4119. begin
  4120. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4121. { Removes the second statement from
  4122. mov reg1, mem1/reg2
  4123. mov mem1/reg2, reg1 }
  4124. begin
  4125. if taicpu(p).oper[0]^.typ=top_reg then
  4126. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4127. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  4128. RemoveInstruction(hp1);
  4129. Result:=true;
  4130. exit;
  4131. end
  4132. else
  4133. begin
  4134. TransferUsedRegs(TmpUsedRegs);
  4135. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4136. if (taicpu(p).oper[1]^.typ = top_ref) and
  4137. { mov reg1, mem1
  4138. mov mem2, reg1 }
  4139. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  4140. GetNextInstruction(hp1, hp2) and
  4141. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  4142. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  4143. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  4144. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  4145. { change to
  4146. mov reg1, mem1 mov reg1, mem1
  4147. mov mem2, reg1 cmp reg1, mem2
  4148. cmp mem1, reg1
  4149. }
  4150. begin
  4151. RemoveInstruction(hp2);
  4152. taicpu(hp1).opcode := A_CMP;
  4153. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  4154. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4155. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4156. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  4157. end;
  4158. end;
  4159. end
  4160. else if (taicpu(p).oper[1]^.typ=top_ref) and
  4161. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4162. begin
  4163. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  4164. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  4165. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  4166. end
  4167. else
  4168. begin
  4169. TransferUsedRegs(TmpUsedRegs);
  4170. if GetNextInstruction(hp1, hp2) and
  4171. MatchOpType(taicpu(p),top_ref,top_reg) and
  4172. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4173. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4174. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  4175. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  4176. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4177. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  4178. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  4179. { mov mem1, %reg1
  4180. mov %reg1, mem2
  4181. mov mem2, reg2
  4182. to:
  4183. mov mem1, reg2
  4184. mov reg2, mem2}
  4185. begin
  4186. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  4187. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  4188. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  4189. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  4190. RemoveInstruction(hp2);
  4191. Result := True;
  4192. end
  4193. {$ifdef i386}
  4194. { this is enabled for i386 only, as the rules to create the reg sets below
  4195. are too complicated for x86-64, so this makes this code too error prone
  4196. on x86-64
  4197. }
  4198. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  4199. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  4200. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  4201. { mov mem1, reg1 mov mem1, reg1
  4202. mov reg1, mem2 mov reg1, mem2
  4203. mov mem2, reg2 mov mem2, reg1
  4204. to: to:
  4205. mov mem1, reg1 mov mem1, reg1
  4206. mov mem1, reg2 mov reg1, mem2
  4207. mov reg1, mem2
  4208. or (if mem1 depends on reg1
  4209. and/or if mem2 depends on reg2)
  4210. to:
  4211. mov mem1, reg1
  4212. mov reg1, mem2
  4213. mov reg1, reg2
  4214. }
  4215. begin
  4216. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  4217. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  4218. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  4219. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  4220. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4221. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4222. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4223. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  4224. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  4225. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  4226. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  4227. end
  4228. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  4229. begin
  4230. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  4231. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  4232. end
  4233. else
  4234. begin
  4235. RemoveInstruction(hp2);
  4236. end
  4237. {$endif i386}
  4238. ;
  4239. end;
  4240. end
  4241. { movl [mem1],reg1
  4242. movl [mem1],reg2
  4243. to
  4244. movl [mem1],reg1
  4245. movl reg1,reg2
  4246. }
  4247. else if not CheckMovMov2MovMov2(p, hp1) and
  4248. { movl const1,[mem1]
  4249. movl [mem1],reg1
  4250. to
  4251. movl const1,reg1
  4252. movl reg1,[mem1]
  4253. }
  4254. MatchOpType(Taicpu(p),top_const,top_ref) and
  4255. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  4256. (taicpu(p).opsize = taicpu(hp1).opsize) and
  4257. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  4258. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  4259. begin
  4260. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  4261. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  4262. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  4263. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  4264. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  4265. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  4266. Result:=true;
  4267. exit;
  4268. end;
  4269. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  4270. end;
  4271. { search further than the next instruction for a mov (as long as it's not a jump) }
  4272. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  4273. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  4274. (taicpu(p).oper[1]^.typ = top_reg) and
  4275. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  4276. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  4277. begin
  4278. { we work with hp2 here, so hp1 can be still used later on when
  4279. checking for GetNextInstruction_p }
  4280. hp3 := hp1;
  4281. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  4282. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  4283. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  4284. TransferUsedRegs(TmpUsedRegs);
  4285. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4286. if NotFirstIteration then
  4287. JumpTracking := TLinkedList.Create
  4288. else
  4289. JumpTracking := nil;
  4290. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  4291. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  4292. (hp2.typ=ait_instruction) do
  4293. begin
  4294. case taicpu(hp2).opcode of
  4295. A_POP:
  4296. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  4297. begin
  4298. if not CrossJump and
  4299. not RegUsedBetween(p_TargetReg, p, hp2) then
  4300. begin
  4301. { We can remove the original MOV since the register
  4302. wasn't used between it and its popping from the stack }
  4303. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  4304. RemoveCurrentp(p, hp1);
  4305. Result := True;
  4306. JumpTracking.Free;
  4307. Exit;
  4308. end;
  4309. { Can't go any further }
  4310. Break;
  4311. end;
  4312. A_MOV:
  4313. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  4314. ((taicpu(p).oper[0]^.typ=top_const) or
  4315. ((taicpu(p).oper[0]^.typ=top_reg) and
  4316. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  4317. )
  4318. ) then
  4319. begin
  4320. { we have
  4321. mov x, %treg
  4322. mov %treg, y
  4323. }
  4324. { We don't need to call UpdateUsedRegs for every instruction between
  4325. p and hp2 because the register we're concerned about will not
  4326. become deallocated (otherwise GetNextInstructionUsingReg would
  4327. have stopped at an earlier instruction). [Kit] }
  4328. TempRegUsed :=
  4329. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4330. RegReadByInstruction(p_TargetReg, hp3) or
  4331. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4332. case taicpu(p).oper[0]^.typ Of
  4333. top_reg:
  4334. begin
  4335. { change
  4336. mov %reg, %treg
  4337. mov %treg, y
  4338. to
  4339. mov %reg, y
  4340. }
  4341. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  4342. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4343. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  4344. begin
  4345. { %reg = y - remove hp2 completely (doing it here instead of relying on
  4346. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  4347. if TempRegUsed then
  4348. begin
  4349. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  4350. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4351. { Set the start of the next GetNextInstructionUsingRegCond search
  4352. to start at the entry right before hp2 (which is about to be removed) }
  4353. hp3 := tai(hp2.Previous);
  4354. RemoveInstruction(hp2);
  4355. Include(OptsToCheck, aoc_ForceNewIteration);
  4356. { See if there's more we can optimise }
  4357. Continue;
  4358. end
  4359. else
  4360. begin
  4361. RemoveInstruction(hp2);
  4362. { We can remove the original MOV too }
  4363. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  4364. RemoveCurrentP(p, hp1);
  4365. Result:=true;
  4366. JumpTracking.Free;
  4367. Exit;
  4368. end;
  4369. end
  4370. else
  4371. begin
  4372. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  4373. taicpu(hp2).loadReg(0, p_SourceReg);
  4374. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  4375. { Check to see if the register also appears in the reference }
  4376. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  4377. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  4378. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  4379. if not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  4380. begin
  4381. { Don't remove the first instruction if the temporary register is in use }
  4382. if not TempRegUsed then
  4383. begin
  4384. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  4385. RemoveCurrentP(p, hp1);
  4386. Result:=true;
  4387. JumpTracking.Free;
  4388. Exit;
  4389. end;
  4390. { No need to set Result to True here. If there's another instruction later
  4391. on that can be optimised, it will be detected when the main Pass 1 loop
  4392. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  4393. hp3 := hp2;
  4394. Continue;
  4395. end;
  4396. end;
  4397. end;
  4398. top_const:
  4399. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  4400. begin
  4401. { change
  4402. mov const, %treg
  4403. mov %treg, y
  4404. to
  4405. mov const, y
  4406. }
  4407. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  4408. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  4409. begin
  4410. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  4411. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  4412. if TempRegUsed then
  4413. begin
  4414. { Don't remove the first instruction if the temporary register is in use }
  4415. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  4416. { No need to set Result to True. If there's another instruction later on
  4417. that can be optimised, it will be detected when the main Pass 1 loop
  4418. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  4419. end
  4420. else
  4421. begin
  4422. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  4423. RemoveCurrentP(p, hp1);
  4424. Result:=true;
  4425. Exit;
  4426. end;
  4427. end;
  4428. end;
  4429. else
  4430. Internalerror(2019103001);
  4431. end;
  4432. end
  4433. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  4434. begin
  4435. if not CrossJump and
  4436. not RegUsedBetween(p_TargetReg, p, hp2) and
  4437. not RegReadByInstruction(p_TargetReg, hp2) then
  4438. begin
  4439. { Register is not used before it is overwritten }
  4440. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  4441. RemoveCurrentp(p, hp1);
  4442. Result := True;
  4443. Exit;
  4444. end;
  4445. if (taicpu(p).oper[0]^.typ = top_const) and
  4446. (taicpu(hp2).oper[0]^.typ = top_const) then
  4447. begin
  4448. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  4449. begin
  4450. { Same value - register hasn't changed }
  4451. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  4452. RemoveInstruction(hp2);
  4453. Include(OptsToCheck, aoc_ForceNewIteration);
  4454. { See if there's more we can optimise }
  4455. Continue;
  4456. end;
  4457. end;
  4458. {$ifdef x86_64}
  4459. end
  4460. { Change:
  4461. movl %reg1l,%reg2l
  4462. ...
  4463. movq %reg2q,%reg3q (%reg1 <> %reg3)
  4464. To:
  4465. movl %reg1l,%reg2l
  4466. ...
  4467. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4468. If %reg1 = %reg3, convert to:
  4469. movl %reg1l,%reg2l
  4470. ...
  4471. andl %reg1l,%reg1l
  4472. }
  4473. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4474. (taicpu(p).oper[0]^.typ = top_reg) and
  4475. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4476. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4477. not RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2) then
  4478. begin
  4479. TempRegUsed :=
  4480. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4481. RegReadByInstruction(p_TargetReg, hp3) or
  4482. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4483. taicpu(hp2).opsize := S_L;
  4484. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4485. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4486. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4487. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4488. begin
  4489. { %reg1 = %reg3 }
  4490. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4491. taicpu(hp2).opcode := A_AND;
  4492. end
  4493. else
  4494. begin
  4495. { %reg1 <> %reg3 }
  4496. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4497. end;
  4498. if not TempRegUsed then
  4499. begin
  4500. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4501. RemoveCurrentP(p, hp1);
  4502. Result := True;
  4503. Exit;
  4504. end
  4505. else
  4506. begin
  4507. { Initial instruction wasn't actually changed }
  4508. Include(OptsToCheck, aoc_ForceNewIteration);
  4509. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4510. appears below since %reg1 has technically changed }
  4511. if taicpu(hp2).opcode = A_AND then
  4512. Break;
  4513. end;
  4514. {$endif x86_64}
  4515. end
  4516. else if (taicpu(hp2).oper[0]^.typ = top_ref) and
  4517. GetNextInstruction(hp2, hp4) and
  4518. (hp4.typ = ait_instruction) and (taicpu(hp4).opcode = A_MOV) then
  4519. { Optimise the following first:
  4520. movl [mem1],reg1
  4521. movl [mem1],reg2
  4522. to
  4523. movl [mem1],reg1
  4524. movl reg1,reg2
  4525. If [mem1] contains the target register and reg1 is the
  4526. the source register, this optimisation will get missed
  4527. and produce less efficient code later on.
  4528. }
  4529. if CheckMovMov2MovMov2(hp2, hp4) then
  4530. { Initial instruction wasn't actually changed }
  4531. Include(OptsToCheck, aoc_ForceNewIteration);
  4532. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4533. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4534. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4535. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4536. begin
  4537. {
  4538. Change from:
  4539. mov ###, %reg
  4540. ...
  4541. movs/z %reg,%reg (Same register, just different sizes)
  4542. To:
  4543. movs/z ###, %reg (Longer version)
  4544. ...
  4545. (remove)
  4546. }
  4547. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4548. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4549. { Keep the first instruction as mov if ### is a constant }
  4550. if taicpu(p).oper[0]^.typ = top_const then
  4551. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4552. else
  4553. begin
  4554. taicpu(p).opcode := taicpu(hp2).opcode;
  4555. taicpu(p).opsize := taicpu(hp2).opsize;
  4556. end;
  4557. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4558. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4559. RemoveInstruction(hp2);
  4560. Result := True;
  4561. JumpTracking.Free;
  4562. Exit;
  4563. end;
  4564. else
  4565. { Move down to the if-block below };
  4566. end;
  4567. { Also catches MOV/S/Z instructions that aren't modified }
  4568. if taicpu(p).oper[0]^.typ = top_reg then
  4569. begin
  4570. p_SourceReg := taicpu(p).oper[0]^.reg;
  4571. if
  4572. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4573. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4574. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4575. begin
  4576. Result := True;
  4577. { Just in case something didn't get modified (e.g. an
  4578. implicit register). Also, if it does read from this
  4579. register, then there's no longer an advantage to
  4580. changing the register on subsequent instructions.}
  4581. if not RegReadByInstruction(p_TargetReg, hp2) then
  4582. begin
  4583. { If a conditional jump was crossed, do not delete
  4584. the original MOV no matter what }
  4585. if not CrossJump and
  4586. { RegEndOfLife returns True if the register is
  4587. deallocated before the next instruction or has
  4588. been loaded with a new value }
  4589. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4590. begin
  4591. { We can remove the original MOV }
  4592. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4593. RemoveCurrentp(p, hp1);
  4594. JumpTracking.Free;
  4595. Result := True;
  4596. Exit;
  4597. end;
  4598. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4599. begin
  4600. { See if there's more we can optimise }
  4601. hp3 := hp2;
  4602. Continue;
  4603. end;
  4604. end;
  4605. end;
  4606. end;
  4607. { Break out of the while loop under normal circumstances }
  4608. Break;
  4609. end;
  4610. JumpTracking.Free;
  4611. end;
  4612. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4613. (taicpu(p).oper[1]^.typ = top_reg) and
  4614. (taicpu(p).opsize = S_L) and
  4615. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4616. (hp2.typ = ait_instruction) and
  4617. (taicpu(hp2).opcode = A_AND) and
  4618. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4619. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4620. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4621. ) then
  4622. begin
  4623. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4624. begin
  4625. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4626. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4627. begin
  4628. { Optimize out:
  4629. mov x, %reg
  4630. and ffffffffh, %reg
  4631. }
  4632. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4633. RemoveInstruction(hp2);
  4634. Result:=true;
  4635. exit;
  4636. end;
  4637. end;
  4638. end;
  4639. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4640. x >= RetOffset) as it doesn't do anything (it writes either to a
  4641. parameter or to the temporary storage room for the function
  4642. result)
  4643. }
  4644. if IsExitCode(hp1) and
  4645. (taicpu(p).oper[1]^.typ = top_ref) and
  4646. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4647. (
  4648. (
  4649. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4650. not (
  4651. assigned(current_procinfo.procdef.funcretsym) and
  4652. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4653. )
  4654. ) or
  4655. { Also discard writes to the stack that are below the base pointer,
  4656. as this is temporary storage rather than a function result on the
  4657. stack, say. }
  4658. (
  4659. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4660. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4661. )
  4662. ) then
  4663. begin
  4664. RemoveCurrentp(p, hp1);
  4665. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4666. RemoveLastDeallocForFuncRes(p);
  4667. Result:=true;
  4668. exit;
  4669. end;
  4670. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4671. begin
  4672. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4673. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4674. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4675. begin
  4676. { change
  4677. mov reg1, mem1
  4678. test/cmp x, mem1
  4679. to
  4680. mov reg1, mem1
  4681. test/cmp x, reg1
  4682. }
  4683. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4684. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4685. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4686. Result := True;
  4687. Exit;
  4688. end;
  4689. if DoMovCmpMemOpt(p, hp1) then
  4690. begin
  4691. Result := True;
  4692. Exit;
  4693. end;
  4694. end;
  4695. if (taicpu(p).oper[1]^.typ = top_reg) and
  4696. (hp1.typ = ait_instruction) and
  4697. GetNextInstruction(hp1, hp2) and
  4698. MatchInstruction(hp2,A_MOV,[]) and
  4699. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4700. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4701. (
  4702. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4703. {$ifdef x86_64}
  4704. or
  4705. (
  4706. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4707. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4708. )
  4709. {$endif x86_64}
  4710. ) then
  4711. begin
  4712. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4713. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4714. { change movsX/movzX reg/ref, reg2
  4715. add/sub/or/... reg3/$const, reg2
  4716. mov reg2 reg/ref
  4717. dealloc reg2
  4718. to
  4719. add/sub/or/... reg3/$const, reg/ref }
  4720. begin
  4721. TransferUsedRegs(TmpUsedRegs);
  4722. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4723. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4724. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4725. begin
  4726. { by example:
  4727. movswl %si,%eax movswl %si,%eax p
  4728. decl %eax addl %edx,%eax hp1
  4729. movw %ax,%si movw %ax,%si hp2
  4730. ->
  4731. movswl %si,%eax movswl %si,%eax p
  4732. decw %eax addw %edx,%eax hp1
  4733. movw %ax,%si movw %ax,%si hp2
  4734. }
  4735. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4736. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4737. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4738. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4739. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4740. {
  4741. ->
  4742. movswl %si,%eax movswl %si,%eax p
  4743. decw %si addw %dx,%si hp1
  4744. movw %ax,%si movw %ax,%si hp2
  4745. }
  4746. case taicpu(hp1).ops of
  4747. 1:
  4748. begin
  4749. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4750. if taicpu(hp1).oper[0]^.typ=top_reg then
  4751. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4752. end;
  4753. 2:
  4754. begin
  4755. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4756. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4757. (taicpu(hp1).opcode<>A_SHL) and
  4758. (taicpu(hp1).opcode<>A_SHR) and
  4759. (taicpu(hp1).opcode<>A_SAR) then
  4760. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4761. end;
  4762. else
  4763. internalerror(2008042701);
  4764. end;
  4765. {
  4766. ->
  4767. decw %si addw %dx,%si p
  4768. }
  4769. RemoveInstruction(hp2);
  4770. RemoveCurrentP(p, hp1);
  4771. Result:=True;
  4772. Exit;
  4773. end;
  4774. end;
  4775. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4776. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4777. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4778. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4779. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4780. )
  4781. {$ifdef i386}
  4782. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4783. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4784. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4785. {$endif i386}
  4786. then
  4787. { change movsX/movzX reg/ref, reg2
  4788. add/sub/or/... regX/$const, reg2
  4789. mov reg2, reg3
  4790. dealloc reg2
  4791. to
  4792. movsX/movzX reg/ref, reg3
  4793. add/sub/or/... reg3/$const, reg3
  4794. }
  4795. begin
  4796. TransferUsedRegs(TmpUsedRegs);
  4797. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4798. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4799. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4800. begin
  4801. { by example:
  4802. movswl %si,%eax movswl %si,%eax p
  4803. decl %eax addl %edx,%eax hp1
  4804. movw %ax,%si movw %ax,%si hp2
  4805. ->
  4806. movswl %si,%eax movswl %si,%eax p
  4807. decw %eax addw %edx,%eax hp1
  4808. movw %ax,%si movw %ax,%si hp2
  4809. }
  4810. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4811. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4812. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4813. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4814. { limit size of constants as well to avoid assembler errors, but
  4815. check opsize to avoid overflow when left shifting the 1 }
  4816. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4817. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4818. {$ifdef x86_64}
  4819. { Be careful of, for example:
  4820. movl %reg1,%reg2
  4821. addl %reg3,%reg2
  4822. movq %reg2,%reg4
  4823. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4824. }
  4825. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4826. begin
  4827. taicpu(hp2).changeopsize(S_L);
  4828. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4829. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4830. end;
  4831. {$endif x86_64}
  4832. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4833. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4834. if taicpu(p).oper[0]^.typ=top_reg then
  4835. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4836. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4837. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4838. {
  4839. ->
  4840. movswl %si,%eax movswl %si,%eax p
  4841. decw %si addw %dx,%si hp1
  4842. movw %ax,%si movw %ax,%si hp2
  4843. }
  4844. case taicpu(hp1).ops of
  4845. 1:
  4846. begin
  4847. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4848. if taicpu(hp1).oper[0]^.typ=top_reg then
  4849. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4850. end;
  4851. 2:
  4852. begin
  4853. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4854. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4855. (taicpu(hp1).opcode<>A_SHL) and
  4856. (taicpu(hp1).opcode<>A_SHR) and
  4857. (taicpu(hp1).opcode<>A_SAR) then
  4858. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4859. end;
  4860. else
  4861. internalerror(2018111801);
  4862. end;
  4863. {
  4864. ->
  4865. decw %si addw %dx,%si p
  4866. }
  4867. RemoveInstruction(hp2);
  4868. end;
  4869. end;
  4870. end;
  4871. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4872. GetNextInstruction(hp1, hp2) and
  4873. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4874. MatchOperand(Taicpu(p).oper[0]^,0) and
  4875. (Taicpu(p).oper[1]^.typ = top_reg) and
  4876. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4877. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4878. { mov reg1,0
  4879. bts reg1,operand1 --> mov reg1,operand2
  4880. or reg1,operand2 bts reg1,operand1}
  4881. begin
  4882. Taicpu(hp2).opcode:=A_MOV;
  4883. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4884. asml.remove(hp1);
  4885. insertllitem(hp2,hp2.next,hp1);
  4886. RemoveCurrentp(p, hp1);
  4887. Result:=true;
  4888. exit;
  4889. end;
  4890. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4891. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4892. GetNextInstruction(hp1, hp2) and
  4893. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4894. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4895. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4896. { change
  4897. mov reg1,reg2
  4898. sub reg3,reg2
  4899. cmp reg3,reg1
  4900. into
  4901. mov reg1,reg2
  4902. sub reg3,reg2
  4903. }
  4904. begin
  4905. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4906. RemoveInstruction(hp2);
  4907. Result:=true;
  4908. exit;
  4909. end;
  4910. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4911. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4912. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4913. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4914. begin
  4915. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4916. {$ifdef x86_64}
  4917. { Convert:
  4918. movq x(ref),%reg64
  4919. shrq y,%reg64
  4920. To:
  4921. movl x+4(ref),%reg32
  4922. shrl y-32,%reg32 (Remove if y = 32)
  4923. }
  4924. if (taicpu(p).opsize = S_Q) and
  4925. (taicpu(hp1).opcode = A_SHR) and
  4926. (taicpu(hp1).oper[0]^.val >= 32) then
  4927. begin
  4928. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4929. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4930. { Convert to 32-bit }
  4931. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4932. taicpu(p).opsize := S_L;
  4933. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4934. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4935. if (taicpu(hp1).oper[0]^.val = 32) then
  4936. begin
  4937. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4938. RemoveInstruction(hp1);
  4939. end
  4940. else
  4941. begin
  4942. { This will potentially open up more arithmetic operations since
  4943. the peephole optimizer now has a big hint that only the lower
  4944. 32 bits are currently in use (and opcodes are smaller in size) }
  4945. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4946. taicpu(hp1).opsize := S_L;
  4947. Dec(taicpu(hp1).oper[0]^.val, 32);
  4948. DebugMsg(SPeepholeOptimization + PreMessage +
  4949. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4950. end;
  4951. Result := True;
  4952. Exit;
  4953. end;
  4954. {$endif x86_64}
  4955. { Convert:
  4956. movl x(ref),%reg
  4957. shrl $24,%reg
  4958. To:
  4959. movzbl x+3(ref),%reg
  4960. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4961. Also accept sar instead of shr, but convert to movsx instead of movzx
  4962. }
  4963. if taicpu(hp1).opcode = A_SHR then
  4964. MovUnaligned := A_MOVZX
  4965. else
  4966. MovUnaligned := A_MOVSX;
  4967. NewSize := S_NO;
  4968. NewOffset := 0;
  4969. case taicpu(p).opsize of
  4970. S_B:
  4971. { No valid combinations };
  4972. S_W:
  4973. if (taicpu(hp1).oper[0]^.val = 8) then
  4974. begin
  4975. NewSize := S_BW;
  4976. NewOffset := 1;
  4977. end;
  4978. S_L:
  4979. case taicpu(hp1).oper[0]^.val of
  4980. 16:
  4981. begin
  4982. NewSize := S_WL;
  4983. NewOffset := 2;
  4984. end;
  4985. 24:
  4986. begin
  4987. NewSize := S_BL;
  4988. NewOffset := 3;
  4989. end;
  4990. else
  4991. ;
  4992. end;
  4993. {$ifdef x86_64}
  4994. S_Q:
  4995. case taicpu(hp1).oper[0]^.val of
  4996. 32:
  4997. begin
  4998. if taicpu(hp1).opcode = A_SAR then
  4999. begin
  5000. { 32-bit to 64-bit is a distinct instruction }
  5001. MovUnaligned := A_MOVSXD;
  5002. NewSize := S_LQ;
  5003. NewOffset := 4;
  5004. end
  5005. else
  5006. { Should have been handled by MovShr2Mov above }
  5007. InternalError(2022081811);
  5008. end;
  5009. 48:
  5010. begin
  5011. NewSize := S_WQ;
  5012. NewOffset := 6;
  5013. end;
  5014. 56:
  5015. begin
  5016. NewSize := S_BQ;
  5017. NewOffset := 7;
  5018. end;
  5019. else
  5020. ;
  5021. end;
  5022. {$endif x86_64}
  5023. else
  5024. InternalError(2022081810);
  5025. end;
  5026. if (NewSize <> S_NO) and
  5027. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  5028. begin
  5029. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  5030. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  5031. debug_op2str(MovUnaligned);
  5032. {$ifdef x86_64}
  5033. if MovUnaligned <> A_MOVSXD then
  5034. { Don't add size suffix for MOVSXD }
  5035. {$endif x86_64}
  5036. PreMessage := PreMessage + debug_opsize2str(NewSize);
  5037. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  5038. taicpu(p).opcode := MovUnaligned;
  5039. taicpu(p).opsize := NewSize;
  5040. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  5041. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  5042. RemoveInstruction(hp1);
  5043. Result := True;
  5044. Exit;
  5045. end;
  5046. end;
  5047. { Backward optimisation shared with OptPass2MOV }
  5048. if FuncMov2Func(p, hp1) then
  5049. begin
  5050. Result := True;
  5051. Exit;
  5052. end;
  5053. end;
  5054. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  5055. var
  5056. hp1 : tai;
  5057. begin
  5058. Result:=false;
  5059. if taicpu(p).ops <> 2 then
  5060. exit;
  5061. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  5062. GetNextInstruction(p,hp1) then
  5063. begin
  5064. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  5065. (taicpu(hp1).ops = 2) then
  5066. begin
  5067. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  5068. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  5069. { movXX reg1, mem1 or movXX mem1, reg1
  5070. movXX mem2, reg2 movXX reg2, mem2}
  5071. begin
  5072. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  5073. { movXX reg1, mem1 or movXX mem1, reg1
  5074. movXX mem2, reg1 movXX reg2, mem1}
  5075. begin
  5076. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5077. begin
  5078. { Removes the second statement from
  5079. movXX reg1, mem1/reg2
  5080. movXX mem1/reg2, reg1
  5081. }
  5082. if taicpu(p).oper[0]^.typ=top_reg then
  5083. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  5084. { Removes the second statement from
  5085. movXX mem1/reg1, reg2
  5086. movXX reg2, mem1/reg1
  5087. }
  5088. if (taicpu(p).oper[1]^.typ=top_reg) and
  5089. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  5090. begin
  5091. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  5092. RemoveInstruction(hp1);
  5093. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  5094. Result:=true;
  5095. exit;
  5096. end
  5097. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  5098. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  5099. begin
  5100. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  5101. RemoveInstruction(hp1);
  5102. Result:=true;
  5103. exit;
  5104. end;
  5105. end
  5106. end;
  5107. end;
  5108. end;
  5109. end;
  5110. end;
  5111. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  5112. var
  5113. hp1 : tai;
  5114. begin
  5115. result:=false;
  5116. { replace
  5117. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  5118. MovX %mreg2,%mreg1
  5119. dealloc %mreg2
  5120. by
  5121. <Op>X %mreg2,%mreg1
  5122. ?
  5123. }
  5124. if GetNextInstruction(p,hp1) and
  5125. { we mix single and double opperations here because we assume that the compiler
  5126. generates vmovapd only after double operations and vmovaps only after single operations }
  5127. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  5128. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5129. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  5130. (taicpu(p).oper[0]^.typ=top_reg) then
  5131. begin
  5132. TransferUsedRegs(TmpUsedRegs);
  5133. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5134. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5135. begin
  5136. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  5137. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5138. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  5139. RemoveInstruction(hp1);
  5140. result:=true;
  5141. end;
  5142. end;
  5143. end;
  5144. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  5145. var
  5146. hp1, p_label, p_dist, hp1_dist, hp1_last: tai;
  5147. JumpLabel, JumpLabel_dist: TAsmLabel;
  5148. FirstValue, SecondValue: TCGInt;
  5149. function OptimizeJump(var InputP: tai): Boolean;
  5150. var
  5151. TempBool: Boolean;
  5152. begin
  5153. Result := False;
  5154. TempBool := True;
  5155. if DoJumpOptimizations(InputP, TempBool) or
  5156. not TempBool then
  5157. begin
  5158. Result := True;
  5159. if Assigned(InputP) then
  5160. begin
  5161. { CollapseZeroDistJump will be set to the label or an align
  5162. before it after the jump if it optimises, whether or not
  5163. the label is live or dead }
  5164. if (InputP.typ = ait_align) or
  5165. (
  5166. (InputP.typ = ait_label) and
  5167. not (tai_label(InputP).labsym.is_used)
  5168. ) then
  5169. GetNextInstruction(InputP, InputP);
  5170. end;
  5171. Exit;
  5172. end;
  5173. end;
  5174. begin
  5175. Result := False;
  5176. if (taicpu(p).oper[0]^.typ = top_const) and
  5177. (taicpu(p).oper[0]^.val <> -1) then
  5178. begin
  5179. { Convert unsigned maximum constants to -1 to aid optimisation }
  5180. case taicpu(p).opsize of
  5181. S_B:
  5182. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  5183. begin
  5184. taicpu(p).oper[0]^.val := -1;
  5185. Result := True;
  5186. Exit;
  5187. end;
  5188. S_W:
  5189. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  5190. begin
  5191. taicpu(p).oper[0]^.val := -1;
  5192. Result := True;
  5193. Exit;
  5194. end;
  5195. S_L:
  5196. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  5197. begin
  5198. taicpu(p).oper[0]^.val := -1;
  5199. Result := True;
  5200. Exit;
  5201. end;
  5202. {$ifdef x86_64}
  5203. S_Q:
  5204. { Storing anything greater than $7FFFFFFF is not possible so do
  5205. nothing };
  5206. {$endif x86_64}
  5207. else
  5208. InternalError(2021121001);
  5209. end;
  5210. end;
  5211. if GetNextInstruction(p, hp1) and
  5212. TrySwapMovCmp(p, hp1) then
  5213. begin
  5214. Result := True;
  5215. Exit;
  5216. end;
  5217. p_label := nil;
  5218. JumpLabel := nil;
  5219. if MatchInstruction(hp1, A_Jcc, []) then
  5220. begin
  5221. if OptimizeJump(hp1) then
  5222. begin
  5223. Result := True;
  5224. if Assigned(hp1) then
  5225. begin
  5226. { CollapseZeroDistJump will be set to the label or an align
  5227. before it after the jump if it optimises, whether or not
  5228. the label is live or dead }
  5229. if (hp1.typ = ait_align) or
  5230. (
  5231. (hp1.typ = ait_label) and
  5232. not (tai_label(hp1).labsym.is_used)
  5233. ) then
  5234. GetNextInstruction(hp1, hp1);
  5235. end;
  5236. TransferUsedRegs(TmpUsedRegs);
  5237. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5238. if not Assigned(hp1) or
  5239. (
  5240. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  5241. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  5242. ) then
  5243. begin
  5244. { No more conditional jumps; conditional statement is no longer required }
  5245. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  5246. RemoveCurrentP(p);
  5247. end;
  5248. Exit;
  5249. end;
  5250. if IsJumpToLabel(taicpu(hp1)) then
  5251. begin
  5252. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  5253. if Assigned(JumpLabel) then
  5254. p_label := getlabelwithsym(JumpLabel);
  5255. end;
  5256. end;
  5257. { Search for:
  5258. test $x,(reg/ref)
  5259. jne @lbl1
  5260. test $y,(reg/ref) (same register or reference)
  5261. jne @lbl1
  5262. Change to:
  5263. test $(x or y),(reg/ref)
  5264. jne @lbl1
  5265. (Note, this doesn't work with je instead of jne)
  5266. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  5267. Also search for:
  5268. test $x,(reg/ref)
  5269. je @lbl1
  5270. ...
  5271. test $y,(reg/ref)
  5272. je/jne @lbl2
  5273. If (x or y) = x, then the second jump is deterministic
  5274. }
  5275. if (
  5276. (
  5277. (taicpu(p).oper[0]^.typ = top_const) or
  5278. (
  5279. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5280. (taicpu(p).oper[0]^.typ = top_reg) and
  5281. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  5282. )
  5283. ) and
  5284. MatchInstruction(hp1, A_JCC, [])
  5285. ) then
  5286. begin
  5287. if (taicpu(p).oper[0]^.typ = top_reg) and
  5288. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  5289. FirstValue := -1
  5290. else
  5291. FirstValue := taicpu(p).oper[0]^.val;
  5292. { If we have several test/jne's in a row, it might be the case that
  5293. the second label doesn't go to the same location, but the one
  5294. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  5295. so accommodate for this with a while loop.
  5296. }
  5297. hp1_last := hp1;
  5298. while (
  5299. (
  5300. (taicpu(p).oper[1]^.typ = top_reg) and
  5301. GetNextInstructionUsingReg(hp1_last, p_dist, taicpu(p).oper[1]^.reg)
  5302. ) or GetNextInstruction(hp1_last, p_dist)
  5303. ) and (p_dist.typ = ait_instruction) do
  5304. begin
  5305. if (
  5306. (
  5307. (taicpu(p_dist).opcode = A_TEST) and
  5308. (
  5309. (taicpu(p_dist).oper[0]^.typ = top_const) or
  5310. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  5311. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  5312. )
  5313. ) or
  5314. (
  5315. { cmp 0,%reg = test %reg,%reg }
  5316. (taicpu(p_dist).opcode = A_CMP) and
  5317. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  5318. )
  5319. ) and
  5320. { Make sure the destination operands are actually the same }
  5321. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5322. GetNextInstruction(p_dist, hp1_dist) and
  5323. MatchInstruction(hp1_dist, A_JCC, []) then
  5324. begin
  5325. if OptimizeJump(hp1_dist) then
  5326. begin
  5327. Result := True;
  5328. Exit;
  5329. end;
  5330. if
  5331. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  5332. (
  5333. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  5334. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  5335. ) then
  5336. SecondValue := -1
  5337. else
  5338. SecondValue := taicpu(p_dist).oper[0]^.val;
  5339. { If both of the TEST constants are identical, delete the
  5340. second TEST that is unnecessary (be careful though, just
  5341. in case the flags are modified in between) }
  5342. if (FirstValue = SecondValue) then
  5343. begin
  5344. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  5345. begin
  5346. { Since the second jump's condition is a subset of the first, we
  5347. know it will never branch because the first jump dominates it.
  5348. Get it out of the way now rather than wait for the jump
  5349. optimisations for a speed boost. }
  5350. if IsJumpToLabel(taicpu(hp1_dist)) then
  5351. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5352. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  5353. RemoveInstruction(hp1_dist);
  5354. Result := True;
  5355. end
  5356. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  5357. begin
  5358. { If the inverse of the first condition is a subset of the second,
  5359. the second one will definitely branch if the first one doesn't }
  5360. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  5361. { We can remove the TEST instruction too }
  5362. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5363. RemoveInstruction(p_dist);
  5364. MakeUnconditional(taicpu(hp1_dist));
  5365. RemoveDeadCodeAfterJump(hp1_dist);
  5366. { Since the jump is now unconditional, we can't
  5367. continue any further with this particular
  5368. optimisation. The original TEST is still intact
  5369. though, so there might be something else we can
  5370. do }
  5371. Include(OptsToCheck, aoc_ForceNewIteration);
  5372. Break;
  5373. end;
  5374. if Result or
  5375. { If a jump wasn't removed or made unconditional, only
  5376. remove the identical TEST instruction if the flags
  5377. weren't modified }
  5378. not RegModifiedBetween(NR_DEFAULTFLAGS, hp1, p_dist) then
  5379. begin
  5380. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  5381. RemoveInstruction(p_dist);
  5382. { If the jump was removed or made unconditional, we
  5383. don't need to allocate NR_DEFAULTFLAGS over the
  5384. entire range }
  5385. if not Result then
  5386. begin
  5387. { Mark the flags as 'in use' over the entire range }
  5388. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  5389. { Speed gain - continue search from the Jcc instruction }
  5390. hp1_last := hp1_dist;
  5391. { Only the TEST instruction was removed, and the
  5392. original was unchanged, so we can safely do
  5393. another iteration of the while loop }
  5394. Include(OptsToCheck, aoc_ForceNewIteration);
  5395. Continue;
  5396. end;
  5397. Exit;
  5398. end;
  5399. end;
  5400. hp1_last := nil;
  5401. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  5402. (
  5403. { In this situation, the TEST/JNE pairs must be adjacent (fixes #40366) }
  5404. { Always adjacent under -O2 and under }
  5405. not(cs_opt_level3 in current_settings.optimizerswitches) or
  5406. (
  5407. GetNextInstruction(hp1, hp1_last) and
  5408. (hp1_last = p_dist)
  5409. )
  5410. ) and
  5411. (
  5412. (
  5413. { Test the following variant:
  5414. test $x,(reg/ref)
  5415. jne @lbl1
  5416. test $y,(reg/ref)
  5417. je @lbl2
  5418. @lbl1:
  5419. Becomes:
  5420. test $(x or y),(reg/ref)
  5421. je @lbl2
  5422. @lbl1: (may become a dead label)
  5423. }
  5424. (taicpu(hp1_dist).condition in [C_E, C_Z]) and
  5425. GetNextInstruction(hp1_dist, hp1_last) and
  5426. (hp1_last = p_label)
  5427. ) or
  5428. (
  5429. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  5430. { If the first instruction is test %reg,%reg or test $-1,%reg,
  5431. then the second jump will never branch, so it can also be
  5432. removed regardless of where it goes }
  5433. (
  5434. (FirstValue = -1) or
  5435. (SecondValue = -1) or
  5436. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  5437. )
  5438. )
  5439. ) then
  5440. begin
  5441. { Same jump location... can be a register since nothing's changed }
  5442. { If any of the entries are equivalent to test %reg,%reg, then the
  5443. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  5444. taicpu(p).loadconst(0, FirstValue or SecondValue);
  5445. if (hp1_last = p_label) then
  5446. begin
  5447. { Variant }
  5448. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JE/@Lbl merged', p);
  5449. RemoveInstruction(p_dist);
  5450. if Assigned(JumpLabel) then
  5451. JumpLabel.decrefs;
  5452. RemoveInstruction(hp1);
  5453. end
  5454. else
  5455. begin
  5456. { Only remove the second test if no jumps or other conditional instructions follow }
  5457. TransferUsedRegs(TmpUsedRegs);
  5458. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5459. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5460. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  5461. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1_dist, TmpUsedRegs) then
  5462. begin
  5463. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  5464. RemoveInstruction(p_dist);
  5465. { Remove the first jump, not the second, to keep
  5466. any register deallocations between the second
  5467. TEST/JNE pair in the same place. Aids future
  5468. optimisation. }
  5469. if Assigned(JumpLabel) then
  5470. JumpLabel.decrefs;
  5471. RemoveInstruction(hp1);
  5472. end
  5473. else
  5474. begin
  5475. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged (second TEST preserved)', p);
  5476. if IsJumpToLabel(taicpu(hp1_dist)) then
  5477. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  5478. { Remove second jump in this instance }
  5479. RemoveInstruction(hp1_dist);
  5480. end;
  5481. end;
  5482. Result := True;
  5483. Exit;
  5484. end;
  5485. end;
  5486. if { If -O2 and under, it may stop on any old instruction }
  5487. (cs_opt_level3 in current_settings.optimizerswitches) and
  5488. (taicpu(p).oper[1]^.typ = top_reg) and
  5489. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, p_dist) then
  5490. begin
  5491. hp1_last := p_dist;
  5492. Continue;
  5493. end;
  5494. Break;
  5495. end;
  5496. end;
  5497. { Search for:
  5498. test %reg,%reg
  5499. j(c1) @lbl1
  5500. ...
  5501. @lbl:
  5502. test %reg,%reg (same register)
  5503. j(c2) @lbl2
  5504. If c2 is a subset of c1, change to:
  5505. test %reg,%reg
  5506. j(c1) @lbl2
  5507. (@lbl1 may become a dead label as a result)
  5508. }
  5509. if (taicpu(p).oper[1]^.typ = top_reg) and
  5510. (taicpu(p).oper[0]^.typ = top_reg) and
  5511. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  5512. { p_label <> nil is a marker that hp1 is a Jcc to a label }
  5513. Assigned(p_label) and
  5514. GetNextInstruction(p_label, p_dist) and
  5515. MatchInstruction(p_dist, A_TEST, []) and
  5516. { It's fine if the second test uses smaller sub-registers }
  5517. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  5518. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  5519. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  5520. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  5521. GetNextInstruction(p_dist, hp1_dist) and
  5522. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5523. begin
  5524. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5525. if JumpLabel = JumpLabel_dist then
  5526. { This is an infinite loop }
  5527. Exit;
  5528. { Best optimisation when the first condition is a subset (or equal) of the second }
  5529. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  5530. begin
  5531. { Any registers used here will already be allocated }
  5532. if Assigned(JumpLabel) then
  5533. JumpLabel.DecRefs;
  5534. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  5535. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  5536. Result := True;
  5537. Exit;
  5538. end;
  5539. end;
  5540. end;
  5541. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  5542. var
  5543. hp1, hp2: tai;
  5544. ActiveReg: TRegister;
  5545. OldOffset: asizeint;
  5546. ThisConst: TCGInt;
  5547. function RegDeallocated: Boolean;
  5548. begin
  5549. TransferUsedRegs(TmpUsedRegs);
  5550. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5551. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5552. end;
  5553. begin
  5554. result:=false;
  5555. hp1 := nil;
  5556. { replace
  5557. addX const,%reg1
  5558. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5559. dealloc %reg1
  5560. by
  5561. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5562. }
  5563. if MatchOpType(taicpu(p),top_const,top_reg) then
  5564. begin
  5565. ActiveReg := taicpu(p).oper[1]^.reg;
  5566. { Ensures the entire register was updated }
  5567. if (taicpu(p).opsize >= S_L) and
  5568. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5569. MatchInstruction(hp1,A_LEA,[]) and
  5570. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5571. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5572. (
  5573. { Cover the case where the register in the reference is also the destination register }
  5574. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5575. (
  5576. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5577. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5578. RegDeallocated
  5579. )
  5580. ) then
  5581. begin
  5582. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5583. {$push}
  5584. {$R-}{$Q-}
  5585. { Explicitly disable overflow checking for these offset calculation
  5586. as those do not matter for the final result }
  5587. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5588. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5589. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5590. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5591. {$pop}
  5592. {$ifdef x86_64}
  5593. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5594. begin
  5595. { Overflow; abort }
  5596. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5597. end
  5598. else
  5599. {$endif x86_64}
  5600. begin
  5601. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5602. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5603. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5604. RemoveCurrentP(p, hp1)
  5605. else
  5606. RemoveCurrentP(p);
  5607. result:=true;
  5608. Exit;
  5609. end;
  5610. end;
  5611. if (
  5612. { Save calling GetNextInstructionUsingReg again }
  5613. Assigned(hp1) or
  5614. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5615. ) and
  5616. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5617. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5618. begin
  5619. if taicpu(hp1).oper[0]^.typ = top_const then
  5620. begin
  5621. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5622. if taicpu(hp1).opcode = A_ADD then
  5623. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5624. else
  5625. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5626. Result := True;
  5627. { Handle any overflows }
  5628. case taicpu(p).opsize of
  5629. S_B:
  5630. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5631. S_W:
  5632. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5633. S_L:
  5634. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5635. {$ifdef x86_64}
  5636. S_Q:
  5637. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5638. { Overflow; abort }
  5639. Result := False
  5640. else
  5641. taicpu(p).oper[0]^.val := ThisConst;
  5642. {$endif x86_64}
  5643. else
  5644. InternalError(2021102610);
  5645. end;
  5646. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5647. if Result then
  5648. begin
  5649. if (taicpu(p).oper[0]^.val < 0) and
  5650. (
  5651. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5652. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5653. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5654. ) then
  5655. begin
  5656. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5657. taicpu(p).opcode := A_SUB;
  5658. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5659. end
  5660. else
  5661. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5662. RemoveInstruction(hp1);
  5663. end;
  5664. end
  5665. else
  5666. begin
  5667. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5668. TransferUsedRegs(TmpUsedRegs);
  5669. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5670. hp2 := p;
  5671. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5672. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5673. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5674. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5675. begin
  5676. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5677. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5678. Asml.Remove(p);
  5679. Asml.InsertAfter(p, hp1);
  5680. p := hp1;
  5681. Result := True;
  5682. Exit;
  5683. end;
  5684. end;
  5685. end;
  5686. if DoArithCombineOpt(p) then
  5687. Result:=true;
  5688. end;
  5689. end;
  5690. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5691. var
  5692. hp1, hp2: tai;
  5693. ref: Integer;
  5694. saveref: treference;
  5695. offsetcalc: Int64;
  5696. TempReg: TRegister;
  5697. Multiple: TCGInt;
  5698. Adjacent, IntermediateRegDiscarded: Boolean;
  5699. begin
  5700. Result:=false;
  5701. { play save and throw an error if LEA uses a seg register prefix,
  5702. this is most likely an error somewhere else }
  5703. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5704. internalerror(2022022001);
  5705. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5706. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5707. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5708. (
  5709. { do not mess with leas accessing the stack pointer
  5710. unless it's a null operation }
  5711. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5712. (
  5713. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5714. (taicpu(p).oper[0]^.ref^.offset = 0)
  5715. )
  5716. ) and
  5717. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5718. begin
  5719. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5720. begin
  5721. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5722. begin
  5723. taicpu(p).opcode := A_MOV;
  5724. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5725. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5726. end
  5727. else
  5728. begin
  5729. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5730. RemoveCurrentP(p);
  5731. end;
  5732. Result:=true;
  5733. exit;
  5734. end
  5735. else if (
  5736. { continue to use lea to adjust the stack pointer,
  5737. it is the recommended way, but only if not optimizing for size }
  5738. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5739. (cs_opt_size in current_settings.optimizerswitches)
  5740. ) and
  5741. { If the flags register is in use, don't change the instruction
  5742. to an ADD otherwise this will scramble the flags. [Kit] }
  5743. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5744. ConvertLEA(taicpu(p)) then
  5745. begin
  5746. Result:=true;
  5747. exit;
  5748. end;
  5749. end;
  5750. { Don't optimise if the stack or frame pointer is the destination register }
  5751. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5752. Exit;
  5753. if GetNextInstruction(p,hp1) and
  5754. (hp1.typ=ait_instruction) then
  5755. begin
  5756. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5757. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5758. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5759. begin
  5760. TransferUsedRegs(TmpUsedRegs);
  5761. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5762. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5763. begin
  5764. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5765. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5766. RemoveInstruction(hp1);
  5767. result:=true;
  5768. exit;
  5769. end;
  5770. end;
  5771. { changes
  5772. lea <ref1>, reg1
  5773. <op> ...,<ref. with reg1>,...
  5774. to
  5775. <op> ...,<ref1>,... }
  5776. { find a reference which uses reg1 }
  5777. 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
  5778. ref:=0
  5779. 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
  5780. ref:=1
  5781. else
  5782. ref:=-1;
  5783. if (ref<>-1) and
  5784. { reg1 must be either the base or the index }
  5785. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5786. begin
  5787. { reg1 can be removed from the reference }
  5788. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5789. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5790. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5791. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5792. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5793. else
  5794. Internalerror(2019111201);
  5795. { check if the can insert all data of the lea into the second instruction }
  5796. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5797. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5798. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5799. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5800. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5801. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5802. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5803. {$ifdef x86_64}
  5804. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5805. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5806. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5807. )
  5808. {$endif x86_64}
  5809. then
  5810. begin
  5811. { reg1 might not used by the second instruction after it is remove from the reference }
  5812. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5813. begin
  5814. TransferUsedRegs(TmpUsedRegs);
  5815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5816. { reg1 is not updated so it might not be used afterwards }
  5817. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5818. begin
  5819. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5820. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5821. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5822. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5823. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5824. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5825. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5826. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5827. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5828. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5829. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5830. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5831. RemoveCurrentP(p, hp1);
  5832. result:=true;
  5833. exit;
  5834. end
  5835. end;
  5836. end;
  5837. { recover }
  5838. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5839. end;
  5840. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5841. if Adjacent or
  5842. { Check further ahead (up to 2 instructions ahead for -O2) }
  5843. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5844. begin
  5845. { Check common LEA/LEA conditions }
  5846. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5847. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5848. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5849. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5850. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5851. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5852. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5853. (
  5854. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5855. calling it (since it calls GetNextInstruction) }
  5856. Adjacent or
  5857. (
  5858. (
  5859. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5860. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5861. ) and (
  5862. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5863. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5864. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5865. )
  5866. )
  5867. ) then
  5868. begin
  5869. TransferUsedRegs(TmpUsedRegs);
  5870. hp2 := p;
  5871. repeat
  5872. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5873. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  5874. IntermediateRegDiscarded :=
  5875. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) or
  5876. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  5877. { changes
  5878. lea offset1(regX,scale), reg1
  5879. lea offset2(reg1,reg1), reg2
  5880. to
  5881. lea (offset1*scale*2)+offset2(regX,scale*2), reg2
  5882. and
  5883. lea offset1(regX,scale1), reg1
  5884. lea offset2(reg1,scale2), reg2
  5885. to
  5886. lea (offset1*scale1*2)+offset2(regX,scale1*scale2), reg2
  5887. and
  5888. lea offset1(regX,scale1), reg1
  5889. lea offset2(reg3,reg1,scale2), reg2
  5890. to
  5891. lea (offset1*scale*2)+offset2(reg3,regX,scale1*scale2), reg2
  5892. ... so long as the final scale does not exceed 8
  5893. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5894. }
  5895. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5896. (
  5897. { Don't optimise if size is a concern and the intermediate register remains in use }
  5898. IntermediateRegDiscarded or
  5899. (
  5900. not (cs_opt_size in current_settings.optimizerswitches) and
  5901. { If the intermediate register is not discarded, it must not
  5902. appear in the first LEA's reference. (Fixes #41166) }
  5903. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5904. )
  5905. ) and
  5906. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5907. (
  5908. (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[0]^.ref^.index) or
  5909. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5910. ) and (
  5911. (
  5912. { lea (reg1,scale2), reg2 variant }
  5913. (taicpu(hp1).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) and
  5914. (
  5915. Adjacent or
  5916. not RegModifiedBetween(taicpu(hp1).oper[0]^.ref^.base, p, hp1)
  5917. ) and
  5918. (
  5919. (
  5920. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5921. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5922. ) or (
  5923. { lea (regX,regX), reg1 variant }
  5924. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5925. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5926. )
  5927. )
  5928. ) or (
  5929. { lea (reg1,reg1), reg1 variant }
  5930. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5931. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5932. )
  5933. ) then
  5934. begin
  5935. { Make everything homogeneous to make calculations easier }
  5936. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5937. begin
  5938. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5939. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5940. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5941. else
  5942. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5943. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5944. end;
  5945. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  5946. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  5947. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5948. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  5949. begin
  5950. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5951. (taicpu(hp1).oper[0]^.ref^.index <> taicpu(p).oper[1]^.reg) then
  5952. begin
  5953. { Put the register to change in the index register }
  5954. TempReg := taicpu(hp1).oper[0]^.ref^.index;
  5955. taicpu(hp1).oper[0]^.ref^.index := taicpu(hp1).oper[0]^.ref^.base;
  5956. taicpu(hp1).oper[0]^.ref^.base := TempReg;
  5957. end;
  5958. { Change lea (reg,reg) to lea(,reg,2) }
  5959. if (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) then
  5960. begin
  5961. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5962. taicpu(hp1).oper[0]^.ref^.scalefactor := 2;
  5963. end;
  5964. if (taicpu(p).oper[0]^.ref^.offset <> 0) then
  5965. Inc(taicpu(hp1).oper[0]^.ref^.offset, taicpu(p).oper[0]^.ref^.offset * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  5966. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5967. { Just to prevent miscalculations }
  5968. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5969. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5970. else
  5971. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * max(taicpu(p).oper[0]^.ref^.scalefactor, 1);
  5972. { Only remove the first LEA if we don't need the intermediate register's value as is }
  5973. if IntermediateRegDiscarded then
  5974. begin
  5975. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5976. RemoveCurrentP(p);
  5977. end
  5978. else
  5979. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 2 done (intermediate register still in use)',p);
  5980. result:=true;
  5981. exit;
  5982. end;
  5983. end;
  5984. { changes
  5985. lea offset1(regX), reg1
  5986. lea offset2(reg1), reg2
  5987. to
  5988. lea offset1+offset2(regX), reg2 }
  5989. if (
  5990. { Don't optimise if size is a concern and the intermediate register remains in use }
  5991. IntermediateRegDiscarded or
  5992. (
  5993. not (cs_opt_size in current_settings.optimizerswitches) and
  5994. { If the intermediate register is not discarded, it must not
  5995. appear in the first LEA's reference. (Fixes #41166) }
  5996. not RegInRef(taicpu(p).oper[1]^.reg, taicpu(p).oper[0]^.ref^)
  5997. )
  5998. ) and
  5999. (
  6000. (
  6001. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6002. (getsupreg(taicpu(p).oper[0]^.ref^.base)<>RS_ESP) and
  6003. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  6004. ) or (
  6005. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  6006. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  6007. (
  6008. (
  6009. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6010. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  6011. ) or (
  6012. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  6013. (
  6014. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6015. (
  6016. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6017. (
  6018. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  6019. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  6020. )
  6021. )
  6022. )
  6023. )
  6024. )
  6025. )
  6026. ) then
  6027. begin
  6028. { Make sure the offset doesn't go out of range (use 64-bit arithmetic)}
  6029. offsetcalc := taicpu(hp1).oper[0]^.ref^.offset;
  6030. Inc(offsetcalc, Int64(taicpu(p).oper[0]^.ref^.offset) * max(taicpu(hp1).oper[0]^.ref^.scalefactor, 1));
  6031. if (offsetcalc <= $7FFFFFFF) and (offsetcalc >= -2147483648) then
  6032. begin
  6033. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  6034. begin
  6035. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  6036. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6037. { if the register is used as index and base, we have to increase for base as well
  6038. and adapt base }
  6039. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  6040. begin
  6041. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6042. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6043. end;
  6044. end
  6045. else
  6046. begin
  6047. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  6048. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  6049. end;
  6050. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  6051. begin
  6052. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  6053. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  6054. if (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) then
  6055. { Catch the situation where the base = index
  6056. and treat this as *2. The scalefactor of
  6057. p will be 0 or 1 due to the conditional
  6058. checks above. Fixes i40647 }
  6059. taicpu(hp1).oper[0]^.ref^.scalefactor := 2
  6060. else
  6061. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor;
  6062. end;
  6063. { Only remove the first LEA if we don't need the intermediate register's value as is }
  6064. if IntermediateRegDiscarded then
  6065. begin
  6066. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  6067. RemoveCurrentP(p);
  6068. end
  6069. else
  6070. DebugMsg(SPeepholeOptimization + 'LeaLea2LeaLea 1 done (intermediate register still in use)',p);
  6071. result:=true;
  6072. exit;
  6073. end;
  6074. end;
  6075. end;
  6076. { Change:
  6077. leal/q $x(%reg1),%reg2
  6078. ...
  6079. shll/q $y,%reg2
  6080. To:
  6081. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  6082. }
  6083. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  6084. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  6085. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6086. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  6087. (taicpu(hp1).oper[0]^.val <= 3) then
  6088. begin
  6089. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  6090. TransferUsedRegs(TmpUsedRegs);
  6091. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6092. if
  6093. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  6094. (this works even if scalefactor is zero) }
  6095. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  6096. { Ensure offset doesn't go out of bounds }
  6097. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  6098. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  6099. (
  6100. (
  6101. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  6102. (
  6103. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  6104. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  6105. (
  6106. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  6107. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  6108. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  6109. )
  6110. )
  6111. ) or (
  6112. (
  6113. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  6114. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  6115. ) and
  6116. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  6117. )
  6118. ) then
  6119. begin
  6120. repeat
  6121. with taicpu(p).oper[0]^.ref^ do
  6122. begin
  6123. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  6124. if index = base then
  6125. begin
  6126. if Multiple > 4 then
  6127. { Optimisation will no longer work because resultant
  6128. scale factor will exceed 8 }
  6129. Break;
  6130. base := NR_NO;
  6131. scalefactor := 2;
  6132. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  6133. end
  6134. else if (base <> NR_NO) and (base <> NR_INVALID) then
  6135. begin
  6136. { Scale factor only works on the index register }
  6137. index := base;
  6138. base := NR_NO;
  6139. end;
  6140. { For safety }
  6141. if scalefactor <= 1 then
  6142. begin
  6143. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  6144. scalefactor := Multiple;
  6145. end
  6146. else
  6147. begin
  6148. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  6149. scalefactor := scalefactor * Multiple;
  6150. end;
  6151. offset := offset * Multiple;
  6152. end;
  6153. RemoveInstruction(hp1);
  6154. Result := True;
  6155. Exit;
  6156. { This repeat..until loop exists for the benefit of Break }
  6157. until True;
  6158. end;
  6159. end;
  6160. end;
  6161. end;
  6162. end;
  6163. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  6164. var
  6165. hp1 : tai;
  6166. SubInstr: Boolean;
  6167. ThisConst: TCGInt;
  6168. const
  6169. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  6170. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  6171. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  6172. begin
  6173. Result := False;
  6174. if taicpu(p).oper[0]^.typ <> top_const then
  6175. { Should have been confirmed before calling }
  6176. InternalError(2021102601);
  6177. SubInstr := (taicpu(p).opcode = A_SUB);
  6178. if GetLastInstruction(p, hp1) and
  6179. (hp1.typ = ait_instruction) and
  6180. (taicpu(hp1).opsize = taicpu(p).opsize) then
  6181. begin
  6182. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  6183. { Bad size }
  6184. InternalError(2022042001);
  6185. case taicpu(hp1).opcode Of
  6186. A_INC:
  6187. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6188. begin
  6189. if SubInstr then
  6190. ThisConst := taicpu(p).oper[0]^.val - 1
  6191. else
  6192. ThisConst := taicpu(p).oper[0]^.val + 1;
  6193. end
  6194. else
  6195. Exit;
  6196. A_DEC:
  6197. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  6198. begin
  6199. if SubInstr then
  6200. ThisConst := taicpu(p).oper[0]^.val + 1
  6201. else
  6202. ThisConst := taicpu(p).oper[0]^.val - 1;
  6203. end
  6204. else
  6205. Exit;
  6206. A_SUB:
  6207. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6208. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6209. begin
  6210. if SubInstr then
  6211. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  6212. else
  6213. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  6214. end
  6215. else
  6216. Exit;
  6217. A_ADD:
  6218. if (taicpu(hp1).oper[0]^.typ = top_const) and
  6219. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  6220. begin
  6221. if SubInstr then
  6222. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  6223. else
  6224. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6225. end
  6226. else
  6227. Exit;
  6228. else
  6229. Exit;
  6230. end;
  6231. { Check that the values are in range }
  6232. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  6233. { Overflow; abort }
  6234. Exit;
  6235. if (ThisConst = 0) then
  6236. begin
  6237. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6238. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6239. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  6240. RemoveInstruction(hp1);
  6241. hp1 := tai(p.next);
  6242. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  6243. if not GetLastInstruction(hp1, p) then
  6244. p := hp1;
  6245. end
  6246. else
  6247. begin
  6248. if taicpu(hp1).opercnt=1 then
  6249. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6250. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  6251. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6252. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  6253. else
  6254. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  6255. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  6256. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  6257. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  6258. RemoveInstruction(hp1);
  6259. taicpu(p).loadconst(0, ThisConst);
  6260. end;
  6261. Result := True;
  6262. end;
  6263. end;
  6264. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai) : Boolean;
  6265. begin
  6266. Result := False;
  6267. if MatchOpType(taicpu(p),top_ref,top_reg) and
  6268. { The x86 assemblers have difficulty comparing values against absolute addresses }
  6269. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  6270. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  6271. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  6272. (
  6273. (
  6274. (taicpu(hp1).opcode = A_TEST)
  6275. ) or (
  6276. (taicpu(hp1).opcode = A_CMP) and
  6277. { A sanity check more than anything }
  6278. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  6279. )
  6280. ) then
  6281. begin
  6282. { change
  6283. mov mem, %reg
  6284. ...
  6285. cmp/test x, %reg / test %reg,%reg
  6286. (reg deallocated)
  6287. to
  6288. cmp/test x, mem / cmp 0, mem
  6289. }
  6290. TransferUsedRegs(TmpUsedRegs);
  6291. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6292. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6293. begin
  6294. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  6295. if (taicpu(hp1).opcode = A_TEST) and
  6296. (
  6297. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  6298. MatchOperand(taicpu(hp1).oper[0]^, -1)
  6299. ) then
  6300. begin
  6301. taicpu(hp1).opcode := A_CMP;
  6302. taicpu(hp1).loadconst(0, 0);
  6303. end;
  6304. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  6305. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  6306. RemoveCurrentP(p);
  6307. if (p <> hp1) then
  6308. { Correctly update TmpUsedRegs if p and hp1 aren't adjacent }
  6309. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  6310. { Make sure the flags are allocated across the CMP instruction }
  6311. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6312. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1, TmpUsedRegs);
  6313. Result := True;
  6314. Exit;
  6315. end;
  6316. end;
  6317. end;
  6318. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  6319. var
  6320. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  6321. ThisReg, SecondReg: TRegister;
  6322. JumpLoc: TAsmLabel;
  6323. NewSize: TOpSize;
  6324. begin
  6325. Result := False;
  6326. {
  6327. Convert:
  6328. j<c> .L1
  6329. .L2:
  6330. mov 1,reg
  6331. jmp .L3 (or ret, although it might not be a RET yet)
  6332. .L1:
  6333. mov 0,reg
  6334. jmp .L3 (or ret)
  6335. ( As long as .L3 <> .L1 or .L2)
  6336. To:
  6337. mov 0,reg
  6338. set<not(c)> reg
  6339. jmp .L3 (or ret)
  6340. .L2:
  6341. mov 1,reg
  6342. jmp .L3 (or ret)
  6343. .L1:
  6344. mov 0,reg
  6345. jmp .L3 (or ret)
  6346. }
  6347. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  6348. Exit;
  6349. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  6350. if GetNextInstruction(hp_label, hp2) and
  6351. MatchInstruction(hp2,A_MOV,[]) and
  6352. (taicpu(hp2).oper[0]^.typ = top_const) and
  6353. (
  6354. (
  6355. (taicpu(hp2).oper[1]^.typ = top_reg)
  6356. {$ifdef i386}
  6357. { Under i386, ESI, EDI, EBP and ESP
  6358. don't have an 8-bit representation }
  6359. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6360. {$endif i386}
  6361. ) or (
  6362. {$ifdef i386}
  6363. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  6364. {$endif i386}
  6365. (taicpu(hp2).opsize = S_B)
  6366. )
  6367. ) and
  6368. GetNextInstruction(hp2, hp3) and
  6369. MatchInstruction(hp3, A_JMP, A_RET, []) and
  6370. (
  6371. (taicpu(hp3).opcode=A_RET) or
  6372. (
  6373. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  6374. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  6375. )
  6376. ) and
  6377. GetNextInstruction(hp3, hp4) and
  6378. FindLabel(JumpLoc, hp4) and
  6379. (
  6380. not (cs_opt_size in current_settings.optimizerswitches) or
  6381. { If the initial jump is the label's only reference, then it will
  6382. become a dead label if the other conditions are met and hence
  6383. remove at least 2 instructions, including a jump }
  6384. (JumpLoc.getrefs = 1)
  6385. ) and
  6386. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  6387. that will be optimised out }
  6388. GetNextInstruction(hp4, hp5) and
  6389. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  6390. (taicpu(hp5).oper[0]^.typ = top_const) and
  6391. (
  6392. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  6393. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  6394. ) and
  6395. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  6396. GetNextInstruction(hp5,hp6) and
  6397. (
  6398. not (hp6.typ in [ait_align, ait_label]) or
  6399. SkipLabels(hp6, hp6)
  6400. ) and
  6401. (hp6.typ=ait_instruction) then
  6402. begin
  6403. { First, let's look at the two jumps that are hp3 and hp6 }
  6404. if not
  6405. (
  6406. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6407. (
  6408. (taicpu(hp6).opcode=A_RET) or
  6409. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6410. )
  6411. ) then
  6412. { If condition is False, then the JMP/RET instructions matched conventionally }
  6413. begin
  6414. { See if one of the jumps can be instantly converted into a RET }
  6415. if (taicpu(hp3).opcode=A_JMP) then
  6416. begin
  6417. { Reuse hp5 }
  6418. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  6419. { Make sure hp5 doesn't jump back to .L1 (zero distance jump) or .L2 (infinite loop) }
  6420. if not Assigned(hp5) or (hp5 = hp_label) or (hp5 = hp4) or not GetNextInstruction(hp5, hp5) then
  6421. Exit;
  6422. if MatchInstruction(hp5, A_RET, []) then
  6423. begin
  6424. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  6425. ConvertJumpToRET(hp3, hp5);
  6426. Result := True;
  6427. end
  6428. else
  6429. Exit;
  6430. end;
  6431. if (taicpu(hp6).opcode=A_JMP) then
  6432. begin
  6433. { Reuse hp5 }
  6434. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  6435. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  6436. Exit;
  6437. if MatchInstruction(hp5, A_RET, []) then
  6438. begin
  6439. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  6440. ConvertJumpToRET(hp6, hp5);
  6441. Result := True;
  6442. end
  6443. else
  6444. Exit;
  6445. end;
  6446. if not
  6447. (
  6448. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  6449. (
  6450. (taicpu(hp6).opcode=A_RET) or
  6451. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  6452. )
  6453. ) then
  6454. { Still doesn't match }
  6455. Exit;
  6456. end;
  6457. if (taicpu(hp2).oper[0]^.val = 1) then
  6458. begin
  6459. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6460. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  6461. end
  6462. else
  6463. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  6464. if taicpu(hp2).opsize=S_B then
  6465. begin
  6466. if taicpu(hp2).oper[1]^.typ = top_reg then
  6467. begin
  6468. SecondReg := taicpu(hp2).oper[1]^.reg;
  6469. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  6470. end
  6471. else
  6472. begin
  6473. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  6474. SecondReg := NR_NO;
  6475. end;
  6476. hp_pos := p;
  6477. hp_allocstart := hp4;
  6478. end
  6479. else
  6480. begin
  6481. { Will be a register because the size can't be S_B otherwise }
  6482. SecondReg:=taicpu(hp2).oper[1]^.reg;
  6483. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  6484. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  6485. if (cs_opt_size in current_settings.optimizerswitches) then
  6486. begin
  6487. { Favour using MOVZX when optimising for size }
  6488. case taicpu(hp2).opsize of
  6489. S_W:
  6490. NewSize := S_BW;
  6491. S_L:
  6492. NewSize := S_BL;
  6493. {$ifdef x86_64}
  6494. S_Q:
  6495. begin
  6496. NewSize := S_BL;
  6497. { Will implicitly zero-extend to 64-bit }
  6498. setsubreg(SecondReg, R_SUBD);
  6499. end;
  6500. {$endif x86_64}
  6501. else
  6502. InternalError(2022101301);
  6503. end;
  6504. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  6505. { Inserting it right before p will guarantee that the flags are also tracked }
  6506. Asml.InsertBefore(hp5, p);
  6507. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  6508. hp_pos := hp5;
  6509. hp_allocstart := hp4;
  6510. end
  6511. else
  6512. begin
  6513. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  6514. { Inserting it right before p will guarantee that the flags are also tracked }
  6515. Asml.InsertBefore(hp5, p);
  6516. hp_pos := p;
  6517. hp_allocstart := hp5;
  6518. end;
  6519. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  6520. end;
  6521. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  6522. taicpu(hp4).condition := taicpu(p).condition;
  6523. asml.InsertBefore(hp4, hp_pos);
  6524. if taicpu(hp3).is_jmp then
  6525. begin
  6526. JumpLoc.decrefs;
  6527. MakeUnconditional(taicpu(p));
  6528. { This also increases the reference count }
  6529. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  6530. end
  6531. else
  6532. ConvertJumpToRET(p, hp3);
  6533. if SecondReg <> NR_NO then
  6534. { Ensure the destination register is allocated over this region }
  6535. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  6536. if (JumpLoc.getrefs = 0) then
  6537. RemoveDeadCodeAfterJump(hp3);
  6538. Result:=true;
  6539. exit;
  6540. end;
  6541. end;
  6542. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  6543. var
  6544. hp1, hp2: tai;
  6545. ActiveReg: TRegister;
  6546. OldOffset: asizeint;
  6547. ThisConst: TCGInt;
  6548. function RegDeallocated: Boolean;
  6549. begin
  6550. TransferUsedRegs(TmpUsedRegs);
  6551. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6552. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  6553. end;
  6554. begin
  6555. Result:=false;
  6556. hp1 := nil;
  6557. { replace
  6558. subX const,%reg1
  6559. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  6560. dealloc %reg1
  6561. by
  6562. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  6563. }
  6564. if MatchOpType(taicpu(p),top_const,top_reg) then
  6565. begin
  6566. ActiveReg := taicpu(p).oper[1]^.reg;
  6567. { Ensures the entire register was updated }
  6568. if (taicpu(p).opsize >= S_L) and
  6569. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  6570. MatchInstruction(hp1,A_LEA,[]) and
  6571. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  6572. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  6573. (
  6574. { Cover the case where the register in the reference is also the destination register }
  6575. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  6576. (
  6577. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  6578. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  6579. RegDeallocated
  6580. )
  6581. ) then
  6582. begin
  6583. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  6584. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.base) then
  6585. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  6586. if SuperRegistersEqual(ActiveReg,taicpu(hp1).oper[0]^.ref^.index) then
  6587. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  6588. {$ifdef x86_64}
  6589. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  6590. begin
  6591. { Overflow; abort }
  6592. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  6593. end
  6594. else
  6595. {$endif x86_64}
  6596. begin
  6597. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  6598. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  6599. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  6600. RemoveCurrentP(p, hp1)
  6601. else
  6602. RemoveCurrentP(p);
  6603. result:=true;
  6604. Exit;
  6605. end;
  6606. end;
  6607. if (
  6608. { Save calling GetNextInstructionUsingReg again }
  6609. Assigned(hp1) or
  6610. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  6611. ) and
  6612. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  6613. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  6614. begin
  6615. if taicpu(hp1).oper[0]^.typ = top_const then
  6616. begin
  6617. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  6618. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  6619. Result := True;
  6620. { Handle any overflows }
  6621. case taicpu(p).opsize of
  6622. S_B:
  6623. taicpu(p).oper[0]^.val := ThisConst and $FF;
  6624. S_W:
  6625. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  6626. S_L:
  6627. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  6628. {$ifdef x86_64}
  6629. S_Q:
  6630. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6631. { Overflow; abort }
  6632. Result := False
  6633. else
  6634. taicpu(p).oper[0]^.val := ThisConst;
  6635. {$endif x86_64}
  6636. else
  6637. InternalError(2021102611);
  6638. end;
  6639. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6640. if Result then
  6641. begin
  6642. if (taicpu(p).oper[0]^.val < 0) and
  6643. (
  6644. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6645. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6646. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6647. ) then
  6648. begin
  6649. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6650. taicpu(p).opcode := A_SUB;
  6651. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6652. end
  6653. else
  6654. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6655. RemoveInstruction(hp1);
  6656. end;
  6657. end
  6658. else
  6659. begin
  6660. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6661. TransferUsedRegs(TmpUsedRegs);
  6662. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6663. hp2 := p;
  6664. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6665. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6666. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6667. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6668. begin
  6669. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6670. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6671. Asml.Remove(p);
  6672. Asml.InsertAfter(p, hp1);
  6673. p := hp1;
  6674. Result := True;
  6675. Exit;
  6676. end;
  6677. end;
  6678. end;
  6679. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6680. { * change "sub/add const1, reg" or "dec reg" followed by
  6681. "sub const2, reg" to one "sub ..., reg" }
  6682. {$ifdef i386}
  6683. if (taicpu(p).oper[0]^.val = 2) and
  6684. (ActiveReg = NR_ESP) and
  6685. { Don't do the sub/push optimization if the sub }
  6686. { comes from setting up the stack frame (JM) }
  6687. (not(GetLastInstruction(p,hp1)) or
  6688. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6689. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6690. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6691. begin
  6692. hp1 := tai(p.next);
  6693. while Assigned(hp1) and
  6694. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6695. not RegReadByInstruction(NR_ESP,hp1) and
  6696. not RegModifiedByInstruction(NR_ESP,hp1) do
  6697. hp1 := tai(hp1.next);
  6698. if Assigned(hp1) and
  6699. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6700. begin
  6701. taicpu(hp1).changeopsize(S_L);
  6702. if taicpu(hp1).oper[0]^.typ=top_reg then
  6703. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6704. hp1 := tai(p.next);
  6705. RemoveCurrentp(p, hp1);
  6706. Result:=true;
  6707. exit;
  6708. end;
  6709. end;
  6710. {$endif i386}
  6711. if DoArithCombineOpt(p) then
  6712. Result:=true;
  6713. end;
  6714. end;
  6715. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6716. var
  6717. TmpBool1,TmpBool2 : Boolean;
  6718. tmpref : treference;
  6719. hp1,hp2: tai;
  6720. mask, shiftval: tcgint;
  6721. begin
  6722. Result:=false;
  6723. { All these optimisations work on "shl/sal const,%reg" }
  6724. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6725. Exit;
  6726. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6727. (taicpu(p).oper[0]^.val <= 3) then
  6728. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6729. begin
  6730. { should we check the next instruction? }
  6731. TmpBool1 := True;
  6732. { have we found an add/sub which could be
  6733. integrated in the lea? }
  6734. TmpBool2 := False;
  6735. reference_reset(tmpref,2,[]);
  6736. TmpRef.index := taicpu(p).oper[1]^.reg;
  6737. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6738. while TmpBool1 and
  6739. GetNextInstruction(p, hp1) and
  6740. (tai(hp1).typ = ait_instruction) and
  6741. ((((taicpu(hp1).opcode = A_ADD) or
  6742. (taicpu(hp1).opcode = A_SUB)) and
  6743. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6744. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6745. (((taicpu(hp1).opcode = A_INC) or
  6746. (taicpu(hp1).opcode = A_DEC)) and
  6747. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6748. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6749. ((taicpu(hp1).opcode = A_LEA) and
  6750. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6751. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6752. (not GetNextInstruction(hp1,hp2) or
  6753. not instrReadsFlags(hp2)) Do
  6754. begin
  6755. TmpBool1 := False;
  6756. if taicpu(hp1).opcode=A_LEA then
  6757. begin
  6758. if (TmpRef.base = NR_NO) and
  6759. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6760. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6761. { Segment register isn't a concern here }
  6762. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6763. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6764. begin
  6765. TmpBool1 := True;
  6766. TmpBool2 := True;
  6767. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6768. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6769. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6770. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6771. RemoveInstruction(hp1);
  6772. end
  6773. end
  6774. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6775. begin
  6776. TmpBool1 := True;
  6777. TmpBool2 := True;
  6778. case taicpu(hp1).opcode of
  6779. A_ADD:
  6780. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6781. A_SUB:
  6782. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6783. else
  6784. internalerror(2019050536);
  6785. end;
  6786. RemoveInstruction(hp1);
  6787. end
  6788. else
  6789. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6790. (((taicpu(hp1).opcode = A_ADD) and
  6791. (TmpRef.base = NR_NO)) or
  6792. (taicpu(hp1).opcode = A_INC) or
  6793. (taicpu(hp1).opcode = A_DEC)) then
  6794. begin
  6795. TmpBool1 := True;
  6796. TmpBool2 := True;
  6797. case taicpu(hp1).opcode of
  6798. A_ADD:
  6799. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6800. A_INC:
  6801. inc(TmpRef.offset);
  6802. A_DEC:
  6803. dec(TmpRef.offset);
  6804. else
  6805. internalerror(2019050535);
  6806. end;
  6807. RemoveInstruction(hp1);
  6808. end;
  6809. end;
  6810. if TmpBool2
  6811. {$ifndef x86_64}
  6812. or
  6813. ((current_settings.optimizecputype < cpu_Pentium2) and
  6814. (taicpu(p).oper[0]^.val <= 3) and
  6815. not(cs_opt_size in current_settings.optimizerswitches))
  6816. {$endif x86_64}
  6817. then
  6818. begin
  6819. if not(TmpBool2) and
  6820. (taicpu(p).oper[0]^.val=1) then
  6821. begin
  6822. taicpu(p).opcode := A_ADD;
  6823. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6824. end
  6825. else
  6826. begin
  6827. taicpu(p).opcode := A_LEA;
  6828. taicpu(p).loadref(0, TmpRef);
  6829. end;
  6830. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6831. Result := True;
  6832. end;
  6833. end
  6834. {$ifndef x86_64}
  6835. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6836. begin
  6837. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6838. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6839. (unlike shl, which is only Tairable in the U pipe) }
  6840. if taicpu(p).oper[0]^.val=1 then
  6841. begin
  6842. taicpu(p).opcode := A_ADD;
  6843. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6844. Result := True;
  6845. end
  6846. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6847. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6848. else if (taicpu(p).opsize = S_L) and
  6849. (taicpu(p).oper[0]^.val<= 3) then
  6850. begin
  6851. reference_reset(tmpref,2,[]);
  6852. TmpRef.index := taicpu(p).oper[1]^.reg;
  6853. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6854. taicpu(p).opcode := A_LEA;
  6855. taicpu(p).loadref(0, TmpRef);
  6856. Result := True;
  6857. end;
  6858. end
  6859. {$endif x86_64}
  6860. else if
  6861. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6862. (
  6863. (
  6864. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6865. SetAndTest(hp1, hp2)
  6866. {$ifdef x86_64}
  6867. ) or
  6868. (
  6869. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6870. GetNextInstruction(hp1, hp2) and
  6871. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6872. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6873. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6874. {$endif x86_64}
  6875. )
  6876. ) and
  6877. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6878. begin
  6879. { Change:
  6880. shl x, %reg1
  6881. mov -(1<<x), %reg2
  6882. and %reg2, %reg1
  6883. Or:
  6884. shl x, %reg1
  6885. and -(1<<x), %reg1
  6886. To just:
  6887. shl x, %reg1
  6888. Since the and operation only zeroes bits that are already zero from the shl operation
  6889. }
  6890. case taicpu(p).oper[0]^.val of
  6891. 8:
  6892. mask:=$FFFFFFFFFFFFFF00;
  6893. 16:
  6894. mask:=$FFFFFFFFFFFF0000;
  6895. 32:
  6896. mask:=$FFFFFFFF00000000;
  6897. 63:
  6898. { Constant pre-calculated to prevent overflow errors with Int64 }
  6899. mask:=$8000000000000000;
  6900. else
  6901. begin
  6902. if taicpu(p).oper[0]^.val >= 64 then
  6903. { Shouldn't happen realistically, since the register
  6904. is guaranteed to be set to zero at this point }
  6905. mask := 0
  6906. else
  6907. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6908. end;
  6909. end;
  6910. if taicpu(hp1).oper[0]^.val = mask then
  6911. begin
  6912. { Everything checks out, perform the optimisation, as long as
  6913. the FLAGS register isn't being used}
  6914. TransferUsedRegs(TmpUsedRegs);
  6915. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6916. {$ifdef x86_64}
  6917. if (hp1 <> hp2) then
  6918. begin
  6919. { "shl/mov/and" version }
  6920. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6921. { Don't do the optimisation if the FLAGS register is in use }
  6922. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6923. begin
  6924. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6925. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6926. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6927. begin
  6928. RemoveInstruction(hp1);
  6929. Result := True;
  6930. end;
  6931. { Only set Result to True if the 'mov' instruction was removed }
  6932. RemoveInstruction(hp2);
  6933. end;
  6934. end
  6935. else
  6936. {$endif x86_64}
  6937. begin
  6938. { "shl/and" version }
  6939. { Don't do the optimisation if the FLAGS register is in use }
  6940. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6941. begin
  6942. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6943. RemoveInstruction(hp1);
  6944. Result := True;
  6945. end;
  6946. end;
  6947. Exit;
  6948. end
  6949. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6950. begin
  6951. { Even if the mask doesn't allow for its removal, we might be
  6952. able to optimise the mask for the "shl/and" version, which
  6953. may permit other peephole optimisations }
  6954. {$ifdef DEBUG_AOPTCPU}
  6955. mask := taicpu(hp1).oper[0]^.val and mask;
  6956. if taicpu(hp1).oper[0]^.val <> mask then
  6957. begin
  6958. DebugMsg(
  6959. SPeepholeOptimization +
  6960. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6961. ' to $' + debug_tostr(mask) +
  6962. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6963. taicpu(hp1).oper[0]^.val := mask;
  6964. end;
  6965. {$else DEBUG_AOPTCPU}
  6966. { If debugging is off, just set the operand even if it's the same }
  6967. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6968. {$endif DEBUG_AOPTCPU}
  6969. end;
  6970. end;
  6971. {
  6972. change
  6973. shl/sal const,reg
  6974. <op> ...(...,reg,1),...
  6975. into
  6976. <op> ...(...,reg,1 shl const),...
  6977. if const in 1..3
  6978. }
  6979. if MatchOpType(taicpu(p), top_const, top_reg) and
  6980. (taicpu(p).oper[0]^.val in [1..3]) and
  6981. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6982. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6983. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6984. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6985. MatchOpType(taicpu(hp1),top_ref))
  6986. ) and
  6987. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6988. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6989. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6990. begin
  6991. TransferUsedRegs(TmpUsedRegs);
  6992. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6993. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6994. begin
  6995. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6996. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6997. RemoveCurrentP(p);
  6998. Result:=true;
  6999. exit;
  7000. end;
  7001. end;
  7002. if MatchOpType(taicpu(p), top_const, top_reg) and
  7003. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  7004. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  7005. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7006. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  7007. begin
  7008. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  7009. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  7010. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  7011. {$ifdef x86_64}
  7012. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  7013. {$endif x86_64}
  7014. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  7015. begin
  7016. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  7017. taicpu(hp1).opcode:=A_MOV;
  7018. taicpu(hp1).oper[0]^.val:=0;
  7019. end
  7020. else
  7021. begin
  7022. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  7023. taicpu(hp1).oper[0]^.val:=shiftval;
  7024. end;
  7025. RemoveCurrentP(p);
  7026. Result:=true;
  7027. exit;
  7028. end;
  7029. end;
  7030. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  7031. begin
  7032. case shr_size of
  7033. S_B:
  7034. { No valid combinations }
  7035. Result := False;
  7036. S_W:
  7037. Result := (Shift >= 8) and (movz_size = S_BW);
  7038. S_L:
  7039. Result :=
  7040. (Shift >= 24) { Any opsize is valid for this shift } or
  7041. ((Shift >= 16) and (movz_size = S_WL));
  7042. {$ifdef x86_64}
  7043. S_Q:
  7044. Result :=
  7045. (Shift >= 56) { Any opsize is valid for this shift } or
  7046. ((Shift >= 48) and (movz_size = S_WL));
  7047. {$endif x86_64}
  7048. else
  7049. InternalError(2022081510);
  7050. end;
  7051. end;
  7052. function TX86AsmOptimizer.HandleSHRMerge(var p: tai; const PostPeephole: Boolean): Boolean;
  7053. var
  7054. hp1, hp2: tai;
  7055. IdentityMask, Shift: TCGInt;
  7056. LimitSize: Topsize;
  7057. DoNotMerge: Boolean;
  7058. begin
  7059. if not MatchInstruction(p, A_SHR, []) then
  7060. InternalError(2025040301);
  7061. Result := False;
  7062. DoNotMerge := False;
  7063. Shift := taicpu(p).oper[0]^.val;
  7064. LimitSize := taicpu(p).opsize;
  7065. hp1 := p;
  7066. repeat
  7067. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  7068. Exit;
  7069. case taicpu(hp1).opcode of
  7070. A_AND:
  7071. { Detect:
  7072. shr x, %reg
  7073. and y, %reg
  7074. If and y, %reg doesn't actually change the value of %reg (e.g. with
  7075. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  7076. (Post-peephole only)
  7077. }
  7078. if PostPeephole and
  7079. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7080. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7081. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7082. begin
  7083. { Make sure the FLAGS register isn't in use }
  7084. TransferUsedRegs(TmpUsedRegs);
  7085. hp2 := p;
  7086. repeat
  7087. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7088. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  7089. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7090. begin
  7091. { Generate the identity mask }
  7092. case taicpu(p).opsize of
  7093. S_B:
  7094. IdentityMask := $FF shr Shift;
  7095. S_W:
  7096. IdentityMask := $FFFF shr Shift;
  7097. S_L:
  7098. IdentityMask := $FFFFFFFF shr Shift;
  7099. {$ifdef x86_64}
  7100. S_Q:
  7101. { We need to force the operands to be unsigned 64-bit
  7102. integers otherwise the wrong value is generated }
  7103. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  7104. {$endif x86_64}
  7105. else
  7106. InternalError(2022081501);
  7107. end;
  7108. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  7109. begin
  7110. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  7111. { All the possible 1 bits are covered, so we can remove the AND }
  7112. hp2 := tai(hp1.Previous);
  7113. RemoveInstruction(hp1);
  7114. { p wasn't actually changed, so don't set Result to True,
  7115. but a change was nonetheless made elsewhere }
  7116. Include(OptsToCheck, aoc_ForceNewIteration);
  7117. { Do another pass in case other AND or MOVZX instructions
  7118. follow }
  7119. hp1 := hp2;
  7120. Continue;
  7121. end;
  7122. end;
  7123. end;
  7124. A_TEST, A_CMP:
  7125. { Skip over relevant comparisons, but shift instructions must
  7126. now not be merged since the original value is being read }
  7127. begin
  7128. DoNotMerge := True;
  7129. Continue;
  7130. end;
  7131. A_Jcc:
  7132. { Skip over conditional jumps and relevant comparisons }
  7133. Continue;
  7134. A_MOVZX:
  7135. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  7136. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  7137. begin
  7138. { Since the original register is being read as is, subsequent
  7139. SHRs must not be merged at this point }
  7140. DoNotMerge := True;
  7141. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  7142. begin
  7143. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  7144. begin
  7145. { If the MOVZX instruction reads and writes the same register,
  7146. defer this to the post-peephole optimisation stage }
  7147. if PostPeephole then
  7148. begin
  7149. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  7150. { All the possible 1 bits are covered, so we can remove the MOVZX }
  7151. hp2 := tai(hp1.Previous);
  7152. RemoveInstruction(hp1);
  7153. hp1 := hp2;
  7154. end;
  7155. end
  7156. else { Different register target }
  7157. begin
  7158. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  7159. taicpu(hp1).opcode := A_MOV;
  7160. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  7161. case taicpu(hp1).opsize of
  7162. S_BW:
  7163. taicpu(hp1).opsize := S_W;
  7164. S_BL, S_WL:
  7165. taicpu(hp1).opsize := S_L;
  7166. else
  7167. InternalError(2022081503);
  7168. end;
  7169. { p itself hasn't changed, so no need to set Result to True }
  7170. Include(OptsToCheck, aoc_ForceNewIteration);
  7171. { See if there's anything afterwards that can be
  7172. optimised, since the input register hasn't changed }
  7173. Continue;
  7174. end;
  7175. Exit;
  7176. end
  7177. else if PostPeephole and
  7178. (Shift > 0) and
  7179. (taicpu(p).opsize = S_W) and
  7180. (taicpu(hp1).opsize = S_WL) and
  7181. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  7182. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  7183. begin
  7184. { Detect:
  7185. shr x, %ax (x > 0)
  7186. ...
  7187. movzwl %ax,%eax
  7188. -
  7189. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  7190. But first, check to see if movzwl %ax,%eax can be removed...
  7191. }
  7192. hp2 := tai(hp1.Previous);
  7193. TransferUsedRegs(TmpUsedRegs);
  7194. UpdateUsedRegsBetween(UsedRegs, p, hp1);
  7195. if PostPeepholeOptMovZX(hp1) then
  7196. hp1 := hp2
  7197. else
  7198. begin
  7199. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  7200. taicpu(hp1).opcode := A_CWDE;
  7201. taicpu(hp1).clearop(0);
  7202. taicpu(hp1).clearop(1);
  7203. taicpu(hp1).ops := 0;
  7204. end;
  7205. RestoreUsedRegs(TmpUsedRegs);
  7206. { Don't need to set aoc_ForceNewIteration if
  7207. PostPeepholeOptMovZX returned True because it's the
  7208. post-peephole stage }
  7209. end;
  7210. { Move onto the next instruction }
  7211. Continue;
  7212. end;
  7213. A_SHL, A_SAL, A_SHR:
  7214. if (taicpu(hp1).opsize <= LimitSize) and
  7215. MatchOpType(taicpu(hp1), top_const, top_reg) and
  7216. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  7217. begin
  7218. { Make sure the sizes don't exceed the register size limit
  7219. (measured by the shift value falling below the limit) }
  7220. if taicpu(hp1).opsize < LimitSize then
  7221. LimitSize := taicpu(hp1).opsize;
  7222. if taicpu(hp1).opcode = A_SHR then
  7223. Inc(Shift, taicpu(hp1).oper[0]^.val)
  7224. else
  7225. begin
  7226. Dec(Shift, taicpu(hp1).oper[0]^.val);
  7227. DoNotMerge := True;
  7228. end;
  7229. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  7230. Exit;
  7231. { Since we've established that the combined shift is within
  7232. limits, we can actually combine the adjacent SHR
  7233. instructions even if they're different sizes }
  7234. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  7235. begin
  7236. hp2 := tai(hp1.Previous);
  7237. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  7238. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  7239. RemoveInstruction(hp1);
  7240. hp1 := hp2;
  7241. { Though p has changed, only the constant has, and its
  7242. effects can still be detected on the next iteration of
  7243. the repeat..until loop }
  7244. Include(OptsToCheck, aoc_ForceNewIteration);
  7245. end;
  7246. { Move onto the next instruction }
  7247. Continue;
  7248. end;
  7249. else
  7250. ;
  7251. end;
  7252. { If the register isn't actually modified, move onto the next instruction,
  7253. but set DoNotMerge to True since the register is being read }
  7254. if (
  7255. { Under -O2 and below, GetNextInstructionUsingReg only returns
  7256. the next instruction, whether or not it contains the register }
  7257. (cs_opt_level3 in current_settings.optimizerswitches) or
  7258. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1)
  7259. ) and not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  7260. begin
  7261. DoNotMerge := True;
  7262. Continue;
  7263. end;
  7264. Break;
  7265. until False;
  7266. end;
  7267. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  7268. begin
  7269. Result := False;
  7270. { All these optimisations work on "shr const,%reg" }
  7271. if not MatchOpType(taicpu(p), top_const, top_reg) then
  7272. Exit;
  7273. Result := HandleSHRMerge(p, False);
  7274. end;
  7275. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  7276. var
  7277. CurrentRef: TReference;
  7278. FullReg: TRegister;
  7279. hp1, hp2: tai;
  7280. begin
  7281. Result := False;
  7282. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  7283. Exit;
  7284. { We assume you've checked if the operand is actually a reference by
  7285. this point. If it isn't, you'll most likely get an access violation }
  7286. CurrentRef := first_mov.oper[1]^.ref^;
  7287. { Memory must be aligned }
  7288. if (CurrentRef.offset mod 4) <> 0 then
  7289. Exit;
  7290. Inc(CurrentRef.offset);
  7291. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7292. if MatchOperand(second_mov.oper[0]^, 0) and
  7293. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  7294. GetNextInstruction(second_mov, hp1) and
  7295. (hp1.typ = ait_instruction) and
  7296. (taicpu(hp1).opcode = A_MOV) and
  7297. MatchOpType(taicpu(hp1), top_const, top_ref) and
  7298. (taicpu(hp1).oper[0]^.val = 0) then
  7299. begin
  7300. Inc(CurrentRef.offset);
  7301. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  7302. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  7303. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  7304. begin
  7305. case taicpu(hp1).opsize of
  7306. S_B:
  7307. if GetNextInstruction(hp1, hp2) and
  7308. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  7309. MatchOpType(taicpu(hp2), top_const, top_ref) and
  7310. (taicpu(hp2).oper[0]^.val = 0) then
  7311. begin
  7312. Inc(CurrentRef.offset);
  7313. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  7314. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  7315. (taicpu(hp2).opsize = S_B) then
  7316. begin
  7317. RemoveInstruction(hp1);
  7318. RemoveInstruction(hp2);
  7319. first_mov.opsize := S_L;
  7320. if first_mov.oper[0]^.typ = top_reg then
  7321. begin
  7322. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  7323. { Reuse second_mov as a MOVZX instruction }
  7324. second_mov.opcode := A_MOVZX;
  7325. second_mov.opsize := S_BL;
  7326. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7327. second_mov.loadreg(1, FullReg);
  7328. first_mov.oper[0]^.reg := FullReg;
  7329. asml.Remove(second_mov);
  7330. asml.InsertBefore(second_mov, first_mov);
  7331. end
  7332. else
  7333. { It's a value }
  7334. begin
  7335. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  7336. RemoveInstruction(second_mov);
  7337. end;
  7338. Result := True;
  7339. Exit;
  7340. end;
  7341. end;
  7342. S_W:
  7343. begin
  7344. RemoveInstruction(hp1);
  7345. first_mov.opsize := S_L;
  7346. if first_mov.oper[0]^.typ = top_reg then
  7347. begin
  7348. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  7349. { Reuse second_mov as a MOVZX instruction }
  7350. second_mov.opcode := A_MOVZX;
  7351. second_mov.opsize := S_BL;
  7352. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  7353. second_mov.loadreg(1, FullReg);
  7354. first_mov.oper[0]^.reg := FullReg;
  7355. asml.Remove(second_mov);
  7356. asml.InsertBefore(second_mov, first_mov);
  7357. end
  7358. else
  7359. { It's a value }
  7360. begin
  7361. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  7362. RemoveInstruction(second_mov);
  7363. end;
  7364. Result := True;
  7365. Exit;
  7366. end;
  7367. else
  7368. ;
  7369. end;
  7370. end;
  7371. end;
  7372. end;
  7373. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  7374. { returns true if a "continue" should be done after this optimization }
  7375. var
  7376. hp1, hp2, hp3: tai;
  7377. begin
  7378. Result := false;
  7379. hp3 := nil;
  7380. if MatchOpType(taicpu(p),top_ref) and
  7381. GetNextInstruction(p, hp1) and
  7382. (hp1.typ = ait_instruction) and
  7383. (((taicpu(hp1).opcode = A_FLD) and
  7384. (taicpu(p).opcode = A_FSTP)) or
  7385. ((taicpu(p).opcode = A_FISTP) and
  7386. (taicpu(hp1).opcode = A_FILD))) and
  7387. MatchOpType(taicpu(hp1),top_ref) and
  7388. (taicpu(hp1).opsize = taicpu(p).opsize) and
  7389. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7390. begin
  7391. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  7392. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  7393. GetNextInstruction(hp1, hp2) and
  7394. (((hp2.typ = ait_instruction) and
  7395. IsExitCode(hp2) and
  7396. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7397. not(assigned(current_procinfo.procdef.funcretsym) and
  7398. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  7399. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  7400. { fstp <temp>
  7401. fld <temp>
  7402. <dealloc> <temp>
  7403. }
  7404. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7405. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7406. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  7407. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7408. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  7409. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  7410. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  7411. )
  7412. )
  7413. ) then
  7414. begin
  7415. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  7416. RemoveInstruction(hp1);
  7417. RemoveCurrentP(p, hp2);
  7418. { first case: exit code }
  7419. if hp2.typ = ait_instruction then
  7420. RemoveLastDeallocForFuncRes(p);
  7421. Result := true;
  7422. end
  7423. else
  7424. { we can do this only in fast math mode as fstp is rounding ...
  7425. ... still disabled as it breaks the compiler and/or rtl }
  7426. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  7427. { ... or if another fstp equal to the first one follows }
  7428. GetNextInstruction(hp1,hp2) and
  7429. (hp2.typ = ait_instruction) and
  7430. (taicpu(p).opcode=taicpu(hp2).opcode) and
  7431. (taicpu(p).opsize=taicpu(hp2).opsize) then
  7432. begin
  7433. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  7434. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  7435. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  7436. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7437. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  7438. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  7439. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  7440. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  7441. ) then
  7442. begin
  7443. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  7444. RemoveCurrentP(p,hp2);
  7445. RemoveInstruction(hp1);
  7446. Result := true;
  7447. end
  7448. else if { fst can't store an extended/comp value }
  7449. (taicpu(p).opsize <> S_FX) and
  7450. (taicpu(p).opsize <> S_IQ) then
  7451. begin
  7452. if (taicpu(p).opcode = A_FSTP) then
  7453. taicpu(p).opcode := A_FST
  7454. else
  7455. taicpu(p).opcode := A_FIST;
  7456. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  7457. RemoveInstruction(hp1);
  7458. Result := true;
  7459. end;
  7460. end;
  7461. end;
  7462. end;
  7463. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  7464. var
  7465. hp1, hp2, hp3: tai;
  7466. begin
  7467. result:=false;
  7468. if MatchOpType(taicpu(p),top_reg) and
  7469. GetNextInstruction(p, hp1) and
  7470. (hp1.typ = Ait_Instruction) and
  7471. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7472. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  7473. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  7474. { change to
  7475. fld reg fxxx reg,st
  7476. fxxxp st, st1 (hp1)
  7477. Remark: non commutative operations must be reversed!
  7478. }
  7479. begin
  7480. case taicpu(hp1).opcode Of
  7481. A_FMULP,A_FADDP,
  7482. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7483. begin
  7484. case taicpu(hp1).opcode Of
  7485. A_FADDP: taicpu(hp1).opcode := A_FADD;
  7486. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  7487. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  7488. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  7489. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  7490. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  7491. else
  7492. internalerror(2019050534);
  7493. end;
  7494. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7495. taicpu(hp1).oper[1]^.reg := NR_ST;
  7496. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  7497. RemoveCurrentP(p, hp1);
  7498. Result:=true;
  7499. exit;
  7500. end;
  7501. else
  7502. ;
  7503. end;
  7504. end
  7505. else
  7506. if MatchOpType(taicpu(p),top_ref) and
  7507. GetNextInstruction(p, hp2) and
  7508. (hp2.typ = Ait_Instruction) and
  7509. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  7510. (taicpu(p).opsize in [S_FS, S_FL]) and
  7511. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  7512. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  7513. if GetLastInstruction(p, hp1) and
  7514. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  7515. MatchOpType(taicpu(hp1),top_ref) and
  7516. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  7517. if ((taicpu(hp2).opcode = A_FMULP) or
  7518. (taicpu(hp2).opcode = A_FADDP)) then
  7519. { change to
  7520. fld/fst mem1 (hp1) fld/fst mem1
  7521. fld mem1 (p) fadd/
  7522. faddp/ fmul st, st
  7523. fmulp st, st1 (hp2) }
  7524. begin
  7525. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  7526. RemoveCurrentP(p, hp1);
  7527. if (taicpu(hp2).opcode = A_FADDP) then
  7528. taicpu(hp2).opcode := A_FADD
  7529. else
  7530. taicpu(hp2).opcode := A_FMUL;
  7531. taicpu(hp2).oper[1]^.reg := NR_ST;
  7532. end
  7533. else
  7534. { change to
  7535. fld/fst mem1 (hp1) fld/fst mem1
  7536. fld mem1 (p) fld st
  7537. }
  7538. begin
  7539. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  7540. taicpu(p).changeopsize(S_FL);
  7541. taicpu(p).loadreg(0,NR_ST);
  7542. end
  7543. else
  7544. begin
  7545. case taicpu(hp2).opcode Of
  7546. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  7547. { change to
  7548. fld/fst mem1 (hp1) fld/fst mem1
  7549. fld mem2 (p) fxxx mem2
  7550. fxxxp st, st1 (hp2) }
  7551. begin
  7552. case taicpu(hp2).opcode Of
  7553. A_FADDP: taicpu(p).opcode := A_FADD;
  7554. A_FMULP: taicpu(p).opcode := A_FMUL;
  7555. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  7556. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  7557. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  7558. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  7559. else
  7560. internalerror(2019050533);
  7561. end;
  7562. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  7563. RemoveInstruction(hp2);
  7564. end
  7565. else
  7566. ;
  7567. end
  7568. end
  7569. end;
  7570. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  7571. begin
  7572. Result := condition_in(cond1, cond2) or
  7573. { Not strictly subsets due to the actual flags checked, but because we're
  7574. comparing integers, E is a subset of AE and GE and their aliases }
  7575. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  7576. end;
  7577. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  7578. var
  7579. v: TCGInt;
  7580. true_hp1, hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  7581. FirstMatch, TempBool: Boolean;
  7582. NewReg: TRegister;
  7583. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  7584. begin
  7585. Result:=false;
  7586. { All these optimisations need a next instruction }
  7587. if not GetNextInstruction(p, hp1) then
  7588. Exit;
  7589. true_hp1 := hp1;
  7590. { Search for:
  7591. cmp ###,###
  7592. j(c1) @lbl1
  7593. ...
  7594. @lbl:
  7595. cmp ###,### (same comparison as above)
  7596. j(c2) @lbl2
  7597. If c1 is a subset of c2, change to:
  7598. cmp ###,###
  7599. j(c1) @lbl2
  7600. (@lbl1 may become a dead label as a result)
  7601. }
  7602. { Also handle cases where there are multiple jumps in a row }
  7603. p_jump := hp1;
  7604. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  7605. begin
  7606. Prefetch(p_jump.Next);
  7607. if IsJumpToLabel(taicpu(p_jump)) then
  7608. begin
  7609. { Do jump optimisations first in case the condition becomes
  7610. unnecessary }
  7611. TempBool := True;
  7612. if DoJumpOptimizations(p_jump, TempBool) or
  7613. not TempBool then
  7614. begin
  7615. if Assigned(p_jump) then
  7616. begin
  7617. { CollapseZeroDistJump will be set to the label or an align
  7618. before it after the jump if it optimises, whether or not
  7619. the label is live or dead }
  7620. if (p_jump.typ = ait_align) or
  7621. (
  7622. (p_jump.typ = ait_label) and
  7623. not (tai_label(p_jump).labsym.is_used)
  7624. ) then
  7625. GetNextInstruction(p_jump, p_jump);
  7626. end;
  7627. TransferUsedRegs(TmpUsedRegs);
  7628. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7629. if not Assigned(p_jump) or
  7630. (
  7631. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  7632. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  7633. ) then
  7634. begin
  7635. { No more conditional jumps; conditional statement is no longer required }
  7636. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  7637. RemoveCurrentP(p);
  7638. Result := True;
  7639. Exit;
  7640. end;
  7641. hp1 := p_jump;
  7642. Include(OptsToCheck, aoc_ForceNewIteration);
  7643. Continue;
  7644. end;
  7645. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  7646. if GetNextInstruction(p_jump, hp2) and
  7647. (
  7648. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  7649. not TempBool
  7650. ) then
  7651. begin
  7652. hp1 := p_jump;
  7653. Include(OptsToCheck, aoc_ForceNewIteration);
  7654. Continue;
  7655. end;
  7656. p_label := nil;
  7657. if Assigned(JumpLabel) then
  7658. p_label := getlabelwithsym(JumpLabel);
  7659. if Assigned(p_label) and
  7660. GetNextInstruction(p_label, p_dist) and
  7661. MatchInstruction(p_dist, A_CMP, []) and
  7662. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  7663. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  7664. GetNextInstruction(p_dist, hp1_dist) and
  7665. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  7666. begin
  7667. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  7668. if JumpLabel = JumpLabel_dist then
  7669. { This is an infinite loop }
  7670. Exit;
  7671. { Best optimisation when the first condition is a subset (or equal) of the second }
  7672. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  7673. begin
  7674. { Any registers used here will already be allocated }
  7675. if Assigned(JumpLabel) then
  7676. JumpLabel.DecRefs;
  7677. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  7678. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  7679. Include(OptsToCheck, aoc_ForceNewIteration);
  7680. { Don't exit yet. Since p and p_jump haven't actually been
  7681. removed, we can check for more on this iteration }
  7682. end
  7683. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  7684. GetNextInstruction(hp1_dist, hp1_label) and
  7685. (hp1_label.typ = ait_label) then
  7686. begin
  7687. JumpLabel_far := tai_label(hp1_label).labsym;
  7688. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  7689. { This is an infinite loop }
  7690. Exit;
  7691. if Assigned(JumpLabel_far) then
  7692. begin
  7693. { In this situation, if the first jump branches, the second one will never,
  7694. branch so change the destination label to after the second jump }
  7695. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  7696. if Assigned(JumpLabel) then
  7697. JumpLabel.DecRefs;
  7698. JumpLabel_far.IncRefs;
  7699. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  7700. Result := True;
  7701. { Don't exit yet. Since p and p_jump haven't actually been
  7702. removed, we can check for more on this iteration }
  7703. Continue;
  7704. end;
  7705. end;
  7706. end;
  7707. end;
  7708. { Search for:
  7709. cmp ###,###
  7710. j(c1) @lbl1
  7711. cmp ###,### (same as first)
  7712. Remove second cmp
  7713. }
  7714. if GetNextInstruction(p_jump, hp2) and
  7715. (
  7716. (
  7717. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  7718. (
  7719. (
  7720. MatchOpType(taicpu(p), top_const, top_reg) and
  7721. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7722. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  7723. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7724. ) or (
  7725. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  7726. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  7727. )
  7728. )
  7729. ) or (
  7730. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  7731. MatchOperand(taicpu(p).oper[0]^, 0) and
  7732. (taicpu(p).oper[1]^.typ = top_reg) and
  7733. MatchInstruction(hp2, A_TEST, []) and
  7734. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  7735. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  7736. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  7737. )
  7738. ) then
  7739. begin
  7740. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  7741. TransferUsedRegs(TmpUsedRegs);
  7742. AllocRegBetween(NR_DEFAULTFLAGS, p, hp2, TmpUsedRegs);
  7743. RemoveInstruction(hp2);
  7744. Result := True;
  7745. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  7746. end
  7747. else
  7748. begin
  7749. { hp2 is the next instruction, so save time and just set p_jump
  7750. to it instead of calling GetNextInstruction below }
  7751. p_jump := hp2;
  7752. Continue;
  7753. end;
  7754. GetNextInstruction(p_jump, p_jump);
  7755. end;
  7756. if (
  7757. { Don't call GetNextInstruction again if we already have it }
  7758. (true_hp1 = p_jump) or
  7759. GetNextInstruction(p, hp1)
  7760. ) and
  7761. MatchInstruction(hp1, A_Jcc, []) and
  7762. IsJumpToLabel(taicpu(hp1)) and
  7763. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  7764. GetNextInstruction(hp1, hp2) then
  7765. begin
  7766. {
  7767. cmp x, y (or "cmp y, x")
  7768. je @lbl
  7769. mov x, y
  7770. @lbl:
  7771. (x and y can be constants, registers or references)
  7772. Change to:
  7773. mov x, y (x and y will always be equal in the end)
  7774. @lbl: (may beceome a dead label)
  7775. Also:
  7776. cmp x, y (or "cmp y, x")
  7777. jne @lbl
  7778. mov x, y
  7779. @lbl:
  7780. (x and y can be constants, registers or references)
  7781. Change to:
  7782. Absolutely nothing! (Except @lbl if it's still live)
  7783. }
  7784. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7785. (
  7786. (
  7787. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7788. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7789. ) or (
  7790. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7791. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7792. )
  7793. ) and
  7794. GetNextInstruction(hp2, hp1_label) and
  7795. (hp1_label.typ = ait_label) and
  7796. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7797. begin
  7798. tai_label(hp1_label).labsym.DecRefs;
  7799. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7800. begin
  7801. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7802. RemoveInstruction(hp2);
  7803. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7804. end
  7805. else
  7806. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7807. RemoveInstruction(hp1);
  7808. RemoveCurrentp(p, hp2);
  7809. Result := True;
  7810. Exit;
  7811. end;
  7812. {
  7813. Try to optimise the following:
  7814. cmp $x,### ($x and $y can be registers or constants)
  7815. je @lbl1 (only reference)
  7816. cmp $y,### (### are identical)
  7817. @Lbl:
  7818. sete %reg1
  7819. Change to:
  7820. cmp $x,###
  7821. sete %reg2 (allocate new %reg2)
  7822. cmp $y,###
  7823. sete %reg1
  7824. orb %reg2,%reg1
  7825. (dealloc %reg2)
  7826. This adds an instruction (so don't perform under -Os), but it removes
  7827. a conditional branch.
  7828. }
  7829. if not (cs_opt_size in current_settings.optimizerswitches) and
  7830. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7831. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7832. { The first operand of CMP instructions can only be a register or
  7833. immediate anyway, so no need to check }
  7834. GetNextInstruction(hp2, p_label) and
  7835. (p_label.typ = ait_label) and
  7836. (tai_label(p_label).labsym.getrefs = 1) and
  7837. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7838. GetNextInstruction(p_label, p_dist) and
  7839. MatchInstruction(p_dist, A_SETcc, []) and
  7840. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7841. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7842. begin
  7843. TransferUsedRegs(TmpUsedRegs);
  7844. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7845. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7846. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7847. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7848. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7849. { Get the instruction after the SETcc instruction so we can
  7850. allocate a new register over the entire range }
  7851. GetNextInstruction(p_dist, hp1_dist) then
  7852. begin
  7853. { Register can appear in p if it's not used afterwards, so only
  7854. allocate between hp1 and hp1_dist }
  7855. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7856. if NewReg <> NR_NO then
  7857. begin
  7858. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7859. { Change the jump instruction into a SETcc instruction }
  7860. taicpu(hp1).opcode := A_SETcc;
  7861. taicpu(hp1).opsize := S_B;
  7862. taicpu(hp1).loadreg(0, NewReg);
  7863. { This is now a dead label }
  7864. tai_label(p_label).labsym.decrefs;
  7865. { Prefer adding before the next instruction so the FLAGS
  7866. register is deallicated first }
  7867. AsmL.InsertBefore(
  7868. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7869. hp1_dist
  7870. );
  7871. Result := True;
  7872. { Don't exit yet, as p wasn't changed and hp1, while
  7873. modified, is still intact and might be optimised by the
  7874. SETcc optimisation below }
  7875. end;
  7876. end;
  7877. end;
  7878. end;
  7879. if (taicpu(p).oper[0]^.typ = top_const) and
  7880. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7881. begin
  7882. if (taicpu(p).oper[0]^.val = 0) and
  7883. (taicpu(p).oper[1]^.typ = top_reg) then
  7884. begin
  7885. hp2 := p;
  7886. FirstMatch := True;
  7887. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7888. anything meaningful once it's converted to "test %reg,%reg";
  7889. additionally, some jumps will always (or never) branch, so
  7890. evaluate every jump immediately following the
  7891. comparison, optimising the conditions if possible.
  7892. Similarly with SETcc... those that are always set to 0 or 1
  7893. are changed to MOV instructions }
  7894. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7895. (
  7896. GetNextInstruction(hp2, hp1) and
  7897. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7898. ) do
  7899. begin
  7900. Prefetch(hp1.Next);
  7901. FirstMatch := False;
  7902. case taicpu(hp1).condition of
  7903. C_B, C_C, C_NAE, C_O:
  7904. { For B/NAE:
  7905. Will never branch since an unsigned integer can never be below zero
  7906. For C/O:
  7907. Result cannot overflow because 0 is being subtracted
  7908. }
  7909. begin
  7910. if taicpu(hp1).opcode = A_Jcc then
  7911. begin
  7912. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7913. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7914. RemoveInstruction(hp1);
  7915. { Since hp1 was deleted, hp2 must not be updated }
  7916. Continue;
  7917. end
  7918. else
  7919. begin
  7920. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7921. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7922. taicpu(hp1).opcode := A_MOV;
  7923. taicpu(hp1).ops := 2;
  7924. taicpu(hp1).condition := C_None;
  7925. taicpu(hp1).opsize := S_B;
  7926. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7927. taicpu(hp1).loadconst(0, 0);
  7928. end;
  7929. end;
  7930. C_BE, C_NA:
  7931. begin
  7932. { Will only branch if equal to zero }
  7933. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7934. taicpu(hp1).condition := C_E;
  7935. end;
  7936. C_A, C_NBE:
  7937. begin
  7938. { Will only branch if not equal to zero }
  7939. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7940. taicpu(hp1).condition := C_NE;
  7941. end;
  7942. C_AE, C_NB, C_NC, C_NO:
  7943. begin
  7944. { Will always branch }
  7945. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7946. if taicpu(hp1).opcode = A_Jcc then
  7947. begin
  7948. MakeUnconditional(taicpu(hp1));
  7949. { Any jumps/set that follow will now be dead code }
  7950. RemoveDeadCodeAfterJump(taicpu(hp1));
  7951. Break;
  7952. end
  7953. else
  7954. begin
  7955. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7956. taicpu(hp1).opcode := A_MOV;
  7957. taicpu(hp1).ops := 2;
  7958. taicpu(hp1).condition := C_None;
  7959. taicpu(hp1).opsize := S_B;
  7960. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7961. taicpu(hp1).loadconst(0, 1);
  7962. end;
  7963. end;
  7964. C_None:
  7965. InternalError(2020012201);
  7966. C_P, C_PE, C_NP, C_PO:
  7967. { We can't handle parity checks and they should never be generated
  7968. after a general-purpose CMP (it's used in some floating-point
  7969. comparisons that don't use CMP) }
  7970. InternalError(2020012202);
  7971. else
  7972. { Zero/Equality, Sign, their complements and all of the
  7973. signed comparisons do not need to be converted };
  7974. end;
  7975. hp2 := hp1;
  7976. end;
  7977. { Convert the instruction to a TEST }
  7978. taicpu(p).opcode := A_TEST;
  7979. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7980. Result := True;
  7981. Exit;
  7982. end
  7983. else
  7984. begin
  7985. TransferUsedRegs(TmpUsedRegs);
  7986. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7987. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  7988. begin
  7989. if (taicpu(p).oper[0]^.val = 1) and
  7990. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7991. begin
  7992. { Convert; To:
  7993. cmp $1,r/m cmp $0,r/m
  7994. jl @lbl jle @lbl
  7995. (Also do inverted conditions)
  7996. }
  7997. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7998. taicpu(p).oper[0]^.val := 0;
  7999. if taicpu(hp1).condition in [C_L, C_NGE] then
  8000. taicpu(hp1).condition := C_LE
  8001. else
  8002. taicpu(hp1).condition := C_NLE;
  8003. { If the instruction is now "cmp $0,%reg", convert it to a
  8004. TEST (and effectively do the work of the "cmp $0,%reg" in
  8005. the block above)
  8006. }
  8007. if (taicpu(p).oper[1]^.typ = top_reg) then
  8008. begin
  8009. taicpu(p).opcode := A_TEST;
  8010. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8011. end;
  8012. Result := True;
  8013. Exit;
  8014. end
  8015. else if (taicpu(p).oper[1]^.typ = top_reg)
  8016. {$ifdef x86_64}
  8017. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  8018. {$endif x86_64}
  8019. then
  8020. begin
  8021. { cmp register,$8000 neg register
  8022. je target --> jo target
  8023. .... only if register is deallocated before jump.}
  8024. case Taicpu(p).opsize of
  8025. S_B: v:=$80;
  8026. S_W: v:=$8000;
  8027. S_L: v:=qword($80000000);
  8028. else
  8029. internalerror(2013112905);
  8030. end;
  8031. if (taicpu(p).oper[0]^.val=v) and
  8032. (Taicpu(hp1).condition in [C_E,C_NE]) then
  8033. begin
  8034. TransferUsedRegs(TmpUsedRegs);
  8035. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  8036. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  8037. begin
  8038. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  8039. Taicpu(p).opcode:=A_NEG;
  8040. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  8041. Taicpu(p).clearop(1);
  8042. Taicpu(p).ops:=1;
  8043. if Taicpu(hp1).condition=C_E then
  8044. Taicpu(hp1).condition:=C_O
  8045. else
  8046. Taicpu(hp1).condition:=C_NO;
  8047. Result:=true;
  8048. exit;
  8049. end;
  8050. end;
  8051. end;
  8052. end;
  8053. end;
  8054. end;
  8055. if TrySwapMovCmp(p, hp1) then
  8056. begin
  8057. Result := True;
  8058. Exit;
  8059. end;
  8060. end;
  8061. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  8062. var
  8063. hp1: tai;
  8064. begin
  8065. {
  8066. remove the second (v)pxor from
  8067. pxor reg,reg
  8068. ...
  8069. pxor reg,reg
  8070. }
  8071. Result:=false;
  8072. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8073. MatchOpType(taicpu(p),top_reg,top_reg) and
  8074. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8075. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8076. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8077. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  8078. begin
  8079. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  8080. RemoveInstruction(hp1);
  8081. Result:=true;
  8082. Exit;
  8083. end
  8084. {
  8085. replace
  8086. pxor reg1,reg1
  8087. movapd/s reg1,reg2
  8088. dealloc reg1
  8089. by
  8090. pxor reg2,reg2
  8091. }
  8092. else if GetNextInstruction(p,hp1) and
  8093. { we mix single and double opperations here because we assume that the compiler
  8094. generates vmovapd only after double operations and vmovaps only after single operations }
  8095. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  8096. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8097. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  8098. (taicpu(p).oper[0]^.typ=top_reg) then
  8099. begin
  8100. TransferUsedRegs(TmpUsedRegs);
  8101. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8102. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  8103. begin
  8104. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  8105. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  8106. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  8107. RemoveInstruction(hp1);
  8108. result:=true;
  8109. end;
  8110. end;
  8111. end;
  8112. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  8113. var
  8114. hp1: tai;
  8115. begin
  8116. {
  8117. remove the second (v)pxor from
  8118. (v)pxor reg,reg
  8119. ...
  8120. (v)pxor reg,reg
  8121. }
  8122. Result:=false;
  8123. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  8124. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8125. begin
  8126. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  8127. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  8128. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  8129. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  8130. begin
  8131. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  8132. RemoveInstruction(hp1);
  8133. Result:=true;
  8134. Exit;
  8135. end;
  8136. {$ifdef x86_64}
  8137. {
  8138. replace
  8139. vpxor reg1,reg1,reg1
  8140. vmov reg,mem
  8141. by
  8142. movq $0,mem
  8143. }
  8144. if GetNextInstruction(p,hp1) and
  8145. MatchInstruction(hp1,A_VMOVSD,[]) and
  8146. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8147. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  8148. begin
  8149. TransferUsedRegs(TmpUsedRegs);
  8150. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8151. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8152. begin
  8153. taicpu(hp1).loadconst(0,0);
  8154. taicpu(hp1).opcode:=A_MOV;
  8155. taicpu(hp1).opsize:=S_Q;
  8156. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  8157. RemoveCurrentP(p);
  8158. result:=true;
  8159. Exit;
  8160. end;
  8161. end;
  8162. {$endif x86_64}
  8163. end
  8164. {
  8165. replace
  8166. vpxor reg1,reg1,reg2
  8167. by
  8168. vpxor reg2,reg2,reg2
  8169. to avoid unncessary data dependencies
  8170. }
  8171. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  8172. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  8173. begin
  8174. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  8175. { avoid unncessary data dependency }
  8176. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  8177. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  8178. result:=true;
  8179. exit;
  8180. end;
  8181. Result:=OptPass1VOP(p);
  8182. end;
  8183. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  8184. var
  8185. hp1 : tai;
  8186. begin
  8187. result:=false;
  8188. { replace
  8189. IMul const,%mreg1,%mreg2
  8190. Mov %reg2,%mreg3
  8191. dealloc %mreg3
  8192. by
  8193. Imul const,%mreg1,%mreg23
  8194. }
  8195. if (taicpu(p).ops=3) and
  8196. GetNextInstruction(p,hp1) and
  8197. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8198. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8199. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8200. begin
  8201. TransferUsedRegs(TmpUsedRegs);
  8202. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8203. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8204. begin
  8205. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8206. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  8207. RemoveInstruction(hp1);
  8208. result:=true;
  8209. end;
  8210. end;
  8211. end;
  8212. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  8213. var
  8214. hp1 : tai;
  8215. begin
  8216. result:=false;
  8217. { replace
  8218. IMul %reg0,%reg1,%reg2
  8219. Mov %reg2,%reg3
  8220. dealloc %reg2
  8221. by
  8222. Imul %reg0,%reg1,%reg3
  8223. }
  8224. if GetNextInstruction(p,hp1) and
  8225. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  8226. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  8227. (taicpu(hp1).oper[1]^.typ=top_reg) then
  8228. begin
  8229. TransferUsedRegs(TmpUsedRegs);
  8230. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8231. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  8232. begin
  8233. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  8234. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  8235. RemoveInstruction(hp1);
  8236. result:=true;
  8237. end;
  8238. end;
  8239. end;
  8240. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  8241. var
  8242. hp1: tai;
  8243. begin
  8244. Result:=false;
  8245. { get rid of
  8246. (v)cvtss2sd reg0,<reg1,>reg2
  8247. (v)cvtss2sd reg2,<reg2,>reg0
  8248. }
  8249. if GetNextInstruction(p,hp1) and
  8250. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  8251. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  8252. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  8253. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  8254. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  8255. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  8256. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8257. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  8258. )
  8259. ) then
  8260. begin
  8261. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  8262. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  8263. begin
  8264. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  8265. RemoveCurrentP(p);
  8266. RemoveInstruction(hp1);
  8267. end
  8268. else
  8269. begin
  8270. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  8271. if taicpu(hp1).opcode=A_CVTSD2SS then
  8272. begin
  8273. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  8274. taicpu(p).opcode:=A_MOVAPS;
  8275. end
  8276. else
  8277. begin
  8278. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  8279. taicpu(p).opcode:=A_VMOVAPS;
  8280. end;
  8281. taicpu(p).ops:=2;
  8282. RemoveInstruction(hp1);
  8283. end;
  8284. Result:=true;
  8285. Exit;
  8286. end;
  8287. end;
  8288. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  8289. var
  8290. hp1, hp2, hp3, hp4, hp5: tai;
  8291. ThisReg: TRegister;
  8292. begin
  8293. Result := False;
  8294. if not GetNextInstruction(p,hp1) then
  8295. Exit;
  8296. {
  8297. convert
  8298. j<c> .L1
  8299. mov 1,reg
  8300. jmp .L2
  8301. .L1
  8302. mov 0,reg
  8303. .L2
  8304. into
  8305. mov 0,reg
  8306. set<not(c)> reg
  8307. take care of alignment and that the mov 0,reg is not converted into a xor as this
  8308. would destroy the flag contents
  8309. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  8310. executed at the same time as a previous comparison.
  8311. set<not(c)> reg
  8312. movzx reg, reg
  8313. }
  8314. if MatchInstruction(hp1,A_MOV,[]) and
  8315. (taicpu(hp1).oper[0]^.typ = top_const) and
  8316. (
  8317. (
  8318. (taicpu(hp1).oper[1]^.typ = top_reg)
  8319. {$ifdef i386}
  8320. { Under i386, ESI, EDI, EBP and ESP
  8321. don't have an 8-bit representation }
  8322. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  8323. {$endif i386}
  8324. ) or (
  8325. {$ifdef i386}
  8326. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  8327. {$endif i386}
  8328. (taicpu(hp1).opsize = S_B)
  8329. )
  8330. ) and
  8331. GetNextInstruction(hp1,hp2) and
  8332. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  8333. GetNextInstruction(hp2,hp3) and
  8334. FindLabel(tasmlabel(taicpu(p).oper[0]^.ref^.symbol), hp3) and
  8335. GetNextInstruction(hp3,hp4) and
  8336. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  8337. (taicpu(hp4).oper[0]^.typ = top_const) and
  8338. (
  8339. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  8340. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  8341. ) and
  8342. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  8343. GetNextInstruction(hp4,hp5) and
  8344. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol), hp5) then
  8345. begin
  8346. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8347. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  8348. tai_label(hp3).labsym.DecRefs;
  8349. { If this isn't the only reference to the middle label, we can
  8350. still make a saving - only that the first jump and everything
  8351. that follows will remain. }
  8352. if (tai_label(hp3).labsym.getrefs = 0) then
  8353. begin
  8354. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8355. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  8356. else
  8357. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  8358. { remove jump, first label and second MOV (also catching any aligns) }
  8359. repeat
  8360. if not GetNextInstruction(hp2, hp3) then
  8361. InternalError(2021040810);
  8362. RemoveInstruction(hp2);
  8363. hp2 := hp3;
  8364. until hp2 = hp5;
  8365. { Don't decrement reference count before the removal loop
  8366. above, otherwise GetNextInstruction won't stop on the
  8367. the label }
  8368. tai_label(hp5).labsym.DecRefs;
  8369. end
  8370. else
  8371. begin
  8372. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  8373. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  8374. else
  8375. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  8376. end;
  8377. taicpu(p).opcode:=A_SETcc;
  8378. taicpu(p).opsize:=S_B;
  8379. taicpu(p).is_jmp:=False;
  8380. if taicpu(hp1).opsize=S_B then
  8381. begin
  8382. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  8383. if taicpu(hp1).oper[1]^.typ = top_reg then
  8384. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  8385. RemoveInstruction(hp1);
  8386. end
  8387. else
  8388. begin
  8389. { Will be a register because the size can't be S_B otherwise }
  8390. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  8391. taicpu(p).loadreg(0, ThisReg);
  8392. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  8393. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  8394. begin
  8395. case taicpu(hp1).opsize of
  8396. S_W:
  8397. taicpu(hp1).opsize := S_BW;
  8398. S_L:
  8399. taicpu(hp1).opsize := S_BL;
  8400. {$ifdef x86_64}
  8401. S_Q:
  8402. begin
  8403. taicpu(hp1).opsize := S_BL;
  8404. { Change the destination register to 32-bit }
  8405. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  8406. end;
  8407. {$endif x86_64}
  8408. else
  8409. InternalError(2021040820);
  8410. end;
  8411. taicpu(hp1).opcode := A_MOVZX;
  8412. taicpu(hp1).loadreg(0, ThisReg);
  8413. end
  8414. else
  8415. begin
  8416. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  8417. { hp1 is already a MOV instruction with the correct register }
  8418. taicpu(hp1).loadconst(0, 0);
  8419. { Inserting it right before p will guarantee that the flags are also tracked }
  8420. asml.Remove(hp1);
  8421. asml.InsertBefore(hp1, p);
  8422. end;
  8423. end;
  8424. Result:=true;
  8425. exit;
  8426. end
  8427. else if MatchInstruction(hp1, A_CLC, A_STC, []) then
  8428. Result := TryJccStcClcOpt(p, hp1)
  8429. else if (hp1.typ = ait_label) then
  8430. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  8431. end;
  8432. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  8433. var
  8434. hp1, hp2, hp3: tai;
  8435. SourceRef, TargetRef: TReference;
  8436. CurrentReg: TRegister;
  8437. begin
  8438. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  8439. if not UseAVX then
  8440. InternalError(2021100501);
  8441. Result := False;
  8442. { Look for the following to simplify:
  8443. vmovdqa/u x(mem1), %xmmreg
  8444. vmovdqa/u %xmmreg, y(mem2)
  8445. vmovdqa/u x+16(mem1), %xmmreg
  8446. vmovdqa/u %xmmreg, y+16(mem2)
  8447. Change to:
  8448. vmovdqa/u x(mem1), %ymmreg
  8449. vmovdqa/u %ymmreg, y(mem2)
  8450. vpxor %ymmreg, %ymmreg, %ymmreg
  8451. ( The VPXOR instruction is to zero the upper half, thus removing the
  8452. need to call the potentially expensive VZEROUPPER instruction. Other
  8453. peephole optimisations can remove VPXOR if it's unnecessary )
  8454. }
  8455. TransferUsedRegs(TmpUsedRegs);
  8456. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8457. { NOTE: In the optimisations below, if the references dictate that an
  8458. aligned move is possible (i.e. VMOVDQA), the existing instructions
  8459. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  8460. if (taicpu(p).opsize = S_XMM) and
  8461. MatchOpType(taicpu(p), top_ref, top_reg) and
  8462. GetNextInstruction(p, hp1) and
  8463. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8464. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  8465. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  8466. begin
  8467. SourceRef := taicpu(p).oper[0]^.ref^;
  8468. TargetRef := taicpu(hp1).oper[1]^.ref^;
  8469. if GetNextInstruction(hp1, hp2) and
  8470. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8471. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  8472. begin
  8473. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  8474. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8475. Inc(SourceRef.offset, 16);
  8476. { Reuse the register in the first block move }
  8477. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  8478. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  8479. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  8480. begin
  8481. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8482. Inc(TargetRef.offset, 16);
  8483. if GetNextInstruction(hp2, hp3) and
  8484. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  8485. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8486. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8487. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8488. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8489. begin
  8490. { Update the register tracking to the new size }
  8491. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  8492. { Remember that the offsets are 16 ahead }
  8493. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8494. if not (
  8495. ((SourceRef.offset mod 32) = 16) and
  8496. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8497. ) then
  8498. taicpu(p).opcode := A_VMOVDQU;
  8499. taicpu(p).opsize := S_YMM;
  8500. taicpu(p).oper[1]^.reg := CurrentReg;
  8501. if not (
  8502. ((TargetRef.offset mod 32) = 16) and
  8503. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8504. ) then
  8505. taicpu(hp1).opcode := A_VMOVDQU;
  8506. taicpu(hp1).opsize := S_YMM;
  8507. taicpu(hp1).oper[0]^.reg := CurrentReg;
  8508. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  8509. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8510. if (pi_uses_ymm in current_procinfo.flags) then
  8511. RemoveInstruction(hp2)
  8512. else
  8513. begin
  8514. taicpu(hp2).opcode := A_VPXOR;
  8515. taicpu(hp2).opsize := S_YMM;
  8516. taicpu(hp2).loadreg(0, CurrentReg);
  8517. taicpu(hp2).loadreg(1, CurrentReg);
  8518. taicpu(hp2).loadreg(2, CurrentReg);
  8519. taicpu(hp2).ops := 3;
  8520. end;
  8521. RemoveInstruction(hp3);
  8522. Result := True;
  8523. Exit;
  8524. end;
  8525. end
  8526. else
  8527. begin
  8528. { See if the next references are 16 less rather than 16 greater }
  8529. Dec(SourceRef.offset, 32); { -16 the other way }
  8530. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  8531. begin
  8532. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8533. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  8534. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  8535. GetNextInstruction(hp2, hp3) and
  8536. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  8537. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  8538. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  8539. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  8540. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  8541. begin
  8542. { Update the register tracking to the new size }
  8543. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  8544. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  8545. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  8546. if not(
  8547. ((SourceRef.offset mod 32) = 0) and
  8548. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  8549. ) then
  8550. taicpu(hp2).opcode := A_VMOVDQU;
  8551. taicpu(hp2).opsize := S_YMM;
  8552. taicpu(hp2).oper[1]^.reg := CurrentReg;
  8553. if not (
  8554. ((TargetRef.offset mod 32) = 0) and
  8555. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  8556. ) then
  8557. taicpu(hp3).opcode := A_VMOVDQU;
  8558. taicpu(hp3).opsize := S_YMM;
  8559. taicpu(hp3).oper[0]^.reg := CurrentReg;
  8560. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  8561. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  8562. if (pi_uses_ymm in current_procinfo.flags) then
  8563. RemoveInstruction(hp1)
  8564. else
  8565. begin
  8566. taicpu(hp1).opcode := A_VPXOR;
  8567. taicpu(hp1).opsize := S_YMM;
  8568. taicpu(hp1).loadreg(0, CurrentReg);
  8569. taicpu(hp1).loadreg(1, CurrentReg);
  8570. taicpu(hp1).loadreg(2, CurrentReg);
  8571. taicpu(hp1).ops := 3;
  8572. Asml.Remove(hp1);
  8573. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  8574. end;
  8575. RemoveCurrentP(p, hp2);
  8576. Result := True;
  8577. Exit;
  8578. end;
  8579. end;
  8580. end;
  8581. end;
  8582. end;
  8583. end;
  8584. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  8585. var
  8586. hp2, hp3, first_assignment: tai;
  8587. IncCount, OperIdx: Integer;
  8588. OrigLabel: TAsmLabel;
  8589. begin
  8590. Count := 0;
  8591. Result := False;
  8592. first_assignment := nil;
  8593. if (LoopCount >= 20) then
  8594. begin
  8595. { Guard against infinite loops }
  8596. Exit;
  8597. end;
  8598. if (taicpu(p).oper[0]^.typ <> top_ref) or
  8599. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  8600. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  8601. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  8602. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  8603. Exit;
  8604. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  8605. {
  8606. change
  8607. jmp .L1
  8608. ...
  8609. .L1:
  8610. mov ##, ## ( multiple movs possible )
  8611. jmp/ret
  8612. into
  8613. mov ##, ##
  8614. jmp/ret
  8615. }
  8616. if not Assigned(hp1) then
  8617. begin
  8618. hp1 := GetLabelWithSym(OrigLabel);
  8619. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  8620. Exit;
  8621. end;
  8622. hp2 := hp1;
  8623. while Assigned(hp2) do
  8624. begin
  8625. if Assigned(hp2) and (hp2.typ = ait_label) then
  8626. SkipLabels(hp2,hp2);
  8627. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  8628. Break;
  8629. case taicpu(hp2).opcode of
  8630. A_MOVSD:
  8631. begin
  8632. if taicpu(hp2).ops = 0 then
  8633. { Wrong MOVSD }
  8634. Break;
  8635. Inc(Count);
  8636. if Count >= 5 then
  8637. { Too many to be worthwhile }
  8638. Break;
  8639. GetNextInstruction(hp2, hp2);
  8640. Continue;
  8641. end;
  8642. A_MOV,
  8643. A_MOVD,
  8644. A_MOVQ,
  8645. A_MOVSX,
  8646. {$ifdef x86_64}
  8647. A_MOVSXD,
  8648. {$endif x86_64}
  8649. A_MOVZX,
  8650. A_MOVAPS,
  8651. A_MOVUPS,
  8652. A_MOVSS,
  8653. A_MOVAPD,
  8654. A_MOVUPD,
  8655. A_MOVDQA,
  8656. A_MOVDQU,
  8657. A_VMOVSS,
  8658. A_VMOVAPS,
  8659. A_VMOVUPS,
  8660. A_VMOVSD,
  8661. A_VMOVAPD,
  8662. A_VMOVUPD,
  8663. A_VMOVDQA,
  8664. A_VMOVDQU:
  8665. begin
  8666. Inc(Count);
  8667. if Count >= 5 then
  8668. { Too many to be worthwhile }
  8669. Break;
  8670. GetNextInstruction(hp2, hp2);
  8671. Continue;
  8672. end;
  8673. A_JMP:
  8674. begin
  8675. { Guard against infinite loops }
  8676. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  8677. Exit;
  8678. { Analyse this jump first in case it also duplicates assignments }
  8679. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  8680. begin
  8681. { Something did change! }
  8682. Result := True;
  8683. Inc(Count, IncCount);
  8684. if Count >= 5 then
  8685. begin
  8686. { Too many to be worthwhile }
  8687. Exit;
  8688. end;
  8689. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  8690. Break;
  8691. end;
  8692. Result := True;
  8693. Break;
  8694. end;
  8695. A_RET:
  8696. begin
  8697. Result := True;
  8698. Break;
  8699. end;
  8700. else
  8701. Break;
  8702. end;
  8703. end;
  8704. if Result then
  8705. begin
  8706. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  8707. if Count = 0 then
  8708. begin
  8709. Result := False;
  8710. Exit;
  8711. end;
  8712. TransferUsedRegs(TmpUsedRegs);
  8713. hp3 := p;
  8714. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  8715. while True do
  8716. begin
  8717. if Assigned(hp1) and (hp1.typ = ait_label) then
  8718. SkipLabels(hp1,hp1);
  8719. case hp1.typ of
  8720. ait_regalloc:
  8721. if tai_regalloc(hp1).ratype = ra_dealloc then
  8722. begin
  8723. { Duplicate the register deallocation... }
  8724. hp3:=tai(hp1.getcopy);
  8725. if first_assignment = nil then
  8726. first_assignment := hp3;
  8727. asml.InsertBefore(hp3, p);
  8728. { ... but also reallocate it after the jump }
  8729. hp3:=tai(hp1.getcopy);
  8730. tai_regalloc(hp3).ratype := ra_alloc;
  8731. asml.InsertAfter(hp3, p);
  8732. end;
  8733. ait_instruction:
  8734. case taicpu(hp1).opcode of
  8735. A_JMP:
  8736. begin
  8737. { Change the original jump to the new destination }
  8738. OrigLabel.decrefs;
  8739. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  8740. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  8741. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8742. if not Assigned(first_assignment) then
  8743. InternalError(2021040810)
  8744. else
  8745. p := first_assignment;
  8746. Exit;
  8747. end;
  8748. A_RET:
  8749. begin
  8750. { Now change the jump into a RET instruction }
  8751. ConvertJumpToRET(p, hp1);
  8752. { Set p to the first duplicated assignment so it can get optimised if needs be }
  8753. if not Assigned(first_assignment) then
  8754. InternalError(2021040811)
  8755. else
  8756. p := first_assignment;
  8757. Exit;
  8758. end;
  8759. else
  8760. begin
  8761. { Duplicate the MOV instruction }
  8762. hp3:=tai(hp1.getcopy);
  8763. if first_assignment = nil then
  8764. first_assignment := hp3;
  8765. asml.InsertBefore(hp3, p);
  8766. { Make sure the compiler knows about any final registers written here }
  8767. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  8768. with taicpu(hp3).oper[OperIdx]^ do
  8769. begin
  8770. case typ of
  8771. top_ref:
  8772. begin
  8773. if (ref^.base <> NR_NO) and
  8774. (getsupreg(ref^.base) <> RS_STACK_POINTER_REG) and
  8775. (
  8776. (getsupreg(ref^.base) <> RS_FRAME_POINTER_REG) or
  8777. (
  8778. { Allow the frame pointer if it's not being used by the procedure as such }
  8779. Assigned(current_procinfo) and
  8780. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8781. )
  8782. )
  8783. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  8784. then
  8785. begin
  8786. AllocRegBetween(ref^.base, hp3, p, TmpUsedRegs);
  8787. if not Assigned(first_assignment) then
  8788. IncludeRegInUsedRegs(ref^.base, UsedRegs);
  8789. end;
  8790. if (ref^.index <> NR_NO) and
  8791. (getsupreg(ref^.index) <> RS_STACK_POINTER_REG) and
  8792. (
  8793. (getsupreg(ref^.index) <> RS_FRAME_POINTER_REG) or
  8794. (
  8795. { Allow the frame pointer if it's not being used by the procedure as such }
  8796. Assigned(current_procinfo) and
  8797. (current_procinfo.framepointer <> NR_FRAME_POINTER_REG)
  8798. )
  8799. )
  8800. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  8801. (ref^.index <> ref^.base) then
  8802. begin
  8803. AllocRegBetween(ref^.index, hp3, p, TmpUsedRegs);
  8804. if not Assigned(first_assignment) then
  8805. IncludeRegInUsedRegs(ref^.index, UsedRegs);
  8806. end;
  8807. end;
  8808. top_reg:
  8809. begin
  8810. AllocRegBetween(reg, hp3, p, TmpUsedRegs);
  8811. if not Assigned(first_assignment) then
  8812. IncludeRegInUsedRegs(reg, UsedRegs);
  8813. end;
  8814. else
  8815. ;
  8816. end;
  8817. end;
  8818. end;
  8819. end;
  8820. else
  8821. InternalError(2021040720);
  8822. end;
  8823. if not GetNextInstruction(hp1, hp1, [ait_regalloc]) then
  8824. { Should have dropped out earlier }
  8825. InternalError(2021040710);
  8826. end;
  8827. end;
  8828. end;
  8829. const
  8830. WriteOp: array[0..3] of set of TInsChange = (
  8831. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8832. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8833. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8834. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8835. RegWriteFlags: array[0..7] of set of TInsChange = (
  8836. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8837. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8838. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8839. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8840. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8841. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8842. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8843. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8844. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8845. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8846. var
  8847. hp2: tai;
  8848. X: Integer;
  8849. begin
  8850. { If we have something like:
  8851. op ###,###
  8852. mov ###,###
  8853. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8854. interfere in regards to what they write to.
  8855. NOTE: p must be a 2-operand instruction
  8856. }
  8857. Result := False;
  8858. if (hp1.typ <> ait_instruction) or
  8859. taicpu(hp1).is_jmp or
  8860. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8861. Exit;
  8862. { NOP is a pipeline fence, likely marking the beginning of the function
  8863. epilogue, so drop out. Similarly, drop out if POP or RET are
  8864. encountered }
  8865. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8866. Exit;
  8867. if (taicpu(hp1).opcode = A_MOVSD) and
  8868. (taicpu(hp1).ops = 0) then
  8869. { Wrong MOVSD }
  8870. Exit;
  8871. { Check for writes to specific registers first }
  8872. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8873. for X := 0 to 7 do
  8874. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8875. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8876. Exit;
  8877. for X := 0 to taicpu(hp1).ops - 1 do
  8878. begin
  8879. { Check to see if this operand writes to something }
  8880. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8881. { And matches something in the CMP/TEST instruction }
  8882. (
  8883. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8884. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8885. (
  8886. { If it's a register, make sure the register written to doesn't
  8887. appear in the cmp instruction as part of a reference }
  8888. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8889. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8890. )
  8891. ) then
  8892. Exit;
  8893. end;
  8894. { Check p to make sure it doesn't write to something that affects hp1 }
  8895. { Check for writes to specific registers first }
  8896. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8897. for X := 0 to 7 do
  8898. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8899. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8900. Exit;
  8901. for X := 0 to taicpu(p).ops - 1 do
  8902. begin
  8903. { Check to see if this operand writes to something }
  8904. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8905. { And matches something in hp1 }
  8906. (taicpu(p).oper[X]^.typ = top_reg) and
  8907. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8908. Exit;
  8909. end;
  8910. { The instruction can be safely moved }
  8911. asml.Remove(hp1);
  8912. { Try to insert after the last instructions where the FLAGS register is not
  8913. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8914. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8915. asml.InsertBefore(hp1, hp2)
  8916. { Failing that, try to insert after the last instructions where the
  8917. FLAGS register is not yet in use }
  8918. else if GetLastInstruction(p, hp2) and
  8919. (
  8920. (hp2.typ <> ait_instruction) or
  8921. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8922. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8923. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8924. ) then
  8925. asml.InsertAfter(hp1, hp2)
  8926. else
  8927. { Note, if p.Previous is nil (even if it should logically never be the
  8928. case), FindRegAllocBackward immediately exits with False and so we
  8929. safely land here (we can't just pass p because FindRegAllocBackward
  8930. immediately exits on an instruction). [Kit] }
  8931. asml.InsertBefore(hp1, p);
  8932. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8933. { We can't trust UsedRegs because we're looking backwards, although we
  8934. know the registers are allocated after p at the very least, so manually
  8935. create tai_regalloc objects if needed }
  8936. for X := 0 to taicpu(hp1).ops - 1 do
  8937. case taicpu(hp1).oper[X]^.typ of
  8938. top_reg:
  8939. begin
  8940. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8941. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8942. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8943. end;
  8944. top_ref:
  8945. begin
  8946. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8947. begin
  8948. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8949. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8950. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8951. end;
  8952. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8953. begin
  8954. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8955. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8956. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8957. end;
  8958. end;
  8959. else
  8960. ;
  8961. end;
  8962. Result := True;
  8963. end;
  8964. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8965. var
  8966. hp2: tai;
  8967. X: Integer;
  8968. begin
  8969. { If we have something like:
  8970. cmp ###,%reg1
  8971. mov 0,%reg2
  8972. And no modified registers are shared, move the instruction to before
  8973. the comparison as this means it can be optimised without worrying
  8974. about the FLAGS register. (CMP/MOV is generated by
  8975. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8976. As long as the second instruction doesn't use the flags or one of the
  8977. registers used by CMP or TEST (also check any references that use the
  8978. registers), then it can be moved prior to the comparison.
  8979. }
  8980. Result := False;
  8981. if not TrySwapMovOp(p, hp1) then
  8982. Exit;
  8983. if taicpu(hp1).opcode = A_LEA then
  8984. { The flags will be overwritten by the CMP/TEST instruction }
  8985. ConvertLEA(taicpu(hp1));
  8986. Result := True;
  8987. { Can we move it one further back? }
  8988. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8989. { Check to see if CMP/TEST is a comparison against zero }
  8990. (
  8991. (
  8992. (taicpu(p).opcode = A_CMP) and
  8993. MatchOperand(taicpu(p).oper[0]^, 0)
  8994. ) or
  8995. (
  8996. (taicpu(p).opcode = A_TEST) and
  8997. (
  8998. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8999. MatchOperand(taicpu(p).oper[0]^, -1)
  9000. )
  9001. )
  9002. ) and
  9003. { These instructions set the zero flag if the result is zero }
  9004. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  9005. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  9006. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  9007. TrySwapMovOp(hp2, hp1);
  9008. end;
  9009. function TX86AsmOptimizer.OptPass1STCCLC(var p: tai): Boolean;
  9010. var
  9011. hp1, hp2, p_last, p_dist, hp1_dist: tai;
  9012. JumpLabel: TAsmLabel;
  9013. TmpBool: Boolean;
  9014. begin
  9015. Result := False;
  9016. { Look for:
  9017. stc/clc
  9018. j(c) .L1
  9019. ...
  9020. .L1:
  9021. set(n)cb %reg
  9022. (flags deallocated)
  9023. j(c) .L2
  9024. Change to:
  9025. mov $0/$1,%reg (depending on if the carry bit is cleared or not)
  9026. j(c) .L2
  9027. }
  9028. p_last := p;
  9029. while GetNextInstruction(p_last, hp1) and
  9030. (hp1.typ = ait_instruction) and
  9031. IsJumpToLabel(taicpu(hp1)) do
  9032. begin
  9033. if DoJumpOptimizations(hp1, TmpBool) then
  9034. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9035. Continue;
  9036. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  9037. if not Assigned(JumpLabel) then
  9038. InternalError(2024012801);
  9039. { Optimise the J(c); stc/clc optimisation first since this will
  9040. get missed if the main optimisation takes place }
  9041. if (taicpu(hp1).opcode = A_JCC) then
  9042. begin
  9043. if GetNextInstruction(hp1, hp2) and
  9044. MatchInstruction(hp2, A_CLC, A_STC, []) and
  9045. TryJccStcClcOpt(hp1, hp2) then
  9046. begin
  9047. Result := True;
  9048. Exit;
  9049. end;
  9050. hp2 := nil; { Suppress compiler warning }
  9051. if (taicpu(hp1).condition in [C_C, C_NC]) and
  9052. { Make sure the flags aren't used again }
  9053. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp1.Next)), hp2) then
  9054. begin
  9055. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9056. if ((taicpu(p).opcode = A_STC) xor (taicpu(hp1).condition = C_NC)) then
  9057. begin
  9058. if (taicpu(p).opcode = A_STC) then
  9059. DebugMsg(SPeepholeOptimization + 'STC; JC -> JMP (Deterministic jump) (StcJc2Jmp)', p)
  9060. else
  9061. DebugMsg(SPeepholeOptimization + 'CLC; JNC -> JMP (Deterministic jump) (ClcJnc2Jmp)', p);
  9062. MakeUnconditional(taicpu(hp1));
  9063. { Move the jump to after the flag deallocations }
  9064. Asml.Remove(hp1);
  9065. Asml.InsertAfter(hp1, hp2);
  9066. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9067. Result := True;
  9068. Exit;
  9069. end
  9070. else
  9071. begin
  9072. if (taicpu(p).opcode = A_STC) then
  9073. DebugMsg(SPeepholeOptimization + 'STC; JNC -> NOP (Deterministic jump) (StcJnc2Nop)', p)
  9074. else
  9075. DebugMsg(SPeepholeOptimization + 'CLC; JC -> NOP (Deterministic jump) (ClcJc2Nop)', p);
  9076. { In this case, the jump is deterministic in that it will never be taken }
  9077. JumpLabel.DecRefs;
  9078. RemoveInstruction(hp1);
  9079. RemoveCurrentP(p); { hp1 may not have been the immediate next instruction }
  9080. Result := True;
  9081. Exit;
  9082. end;
  9083. end;
  9084. end;
  9085. hp2 := nil; { Suppress compiler warning }
  9086. if
  9087. { Make sure the carry flag doesn't appear in the jump conditions }
  9088. not (taicpu(hp1).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9089. SetAndTest(getlabelwithsym(JumpLabel), hp2) and
  9090. GetNextInstruction(hp2, p_dist) and
  9091. MatchInstruction(p_dist, A_Jcc, A_SETcc, []) and
  9092. (taicpu(p_dist).condition in [C_C, C_NC]) then
  9093. begin
  9094. case taicpu(p_dist).opcode of
  9095. A_Jcc:
  9096. begin
  9097. if DoJumpOptimizations(p_dist, TmpBool) then
  9098. { Re-evaluate from p_last. Probably could be faster, but it's guaranteed to be correct }
  9099. Continue;
  9100. { clc + jc = False; clc + jnc = True; stc + jc = True; stc + jnc = False }
  9101. if ((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)) then
  9102. begin
  9103. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C -> JMP/Jcc (StcClcJ(c)2Jmp)', p);
  9104. JumpLabel.decrefs;
  9105. taicpu(hp1).loadsymbol(0, taicpu(p_dist).oper[0]^.ref^.symbol, 0);
  9106. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9107. Result := True;
  9108. Exit;
  9109. end
  9110. else if GetNextInstruction(p_dist, hp1_dist) and
  9111. (hp1_dist.typ = ait_label) then
  9112. begin
  9113. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP/Jcc; ... J(N)C; .Lbl -> JMP/Jcc .Lbl (StcClcJ(~c)Lbl2Jmp)', p);
  9114. JumpLabel.decrefs;
  9115. taicpu(hp1).loadsymbol(0, tai_label(hp1_dist).labsym, 0);
  9116. RemoveCurrentP(p); { hp1 may not be the immediate next instruction }
  9117. Result := True;
  9118. Exit;
  9119. end;
  9120. end;
  9121. A_SETcc:
  9122. if { Make sure the flags aren't used again }
  9123. SetAndTest(FindRegDealloc(NR_DEFAULTFLAGS, tai(p_dist.Next)), hp2) and
  9124. GetNextInstruction(hp2, hp1_dist) and
  9125. (hp1_dist.typ = ait_instruction) and
  9126. IsJumpToLabel(taicpu(hp1_dist)) and
  9127. not (taicpu(hp1_dist).condition in [C_AE, C_NB, C_NC, C_B, C_C, C_NAE, C_BE, C_NA]) and
  9128. { This works if hp1_dist or both are regular JMP instructions }
  9129. condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) and
  9130. (
  9131. (taicpu(p_dist).oper[0]^.typ <> top_reg) or
  9132. { Make sure the register isn't still in use, otherwise it
  9133. may get corrupted (fixes #40659) }
  9134. not RegUsedBetween(taicpu(p_dist).oper[0]^.reg, p, p_dist)
  9135. ) then
  9136. begin
  9137. taicpu(p).allocate_oper(2);
  9138. taicpu(p).ops := 2;
  9139. { clc + setc = 0; clc + setnc = 1; stc + setc = 1; stc + setnc = 0 }
  9140. taicpu(p).loadconst(0, TCGInt((taicpu(p).opcode = A_STC) xor (taicpu(p_dist).condition = C_NC)));
  9141. taicpu(p).loadoper(1, taicpu(p_dist).oper[0]^);
  9142. taicpu(p).opcode := A_MOV;
  9143. taicpu(p).opsize := S_B;
  9144. if (taicpu(p_dist).oper[0]^.typ = top_reg) then
  9145. AllocRegBetween(taicpu(p_dist).oper[0]^.reg, p, hp1, UsedRegs);
  9146. DebugMsg(SPeepholeOptimization + 'STC/CLC; JMP; ... SET(N)C; JMP -> MOV; JMP (StcClcSet(c)2Mov)', p);
  9147. JumpLabel.decrefs;
  9148. taicpu(hp1).loadsymbol(0, taicpu(hp1_dist).oper[0]^.ref^.symbol, 0);
  9149. { If a flag allocation is found, try to move it to after the MOV so "mov $0,%reg" gets optimised to "xor %reg,%reg" }
  9150. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) and
  9151. (tai_regalloc(hp2).ratype = ra_alloc) then
  9152. begin
  9153. Asml.Remove(hp2);
  9154. Asml.InsertAfter(hp2, p);
  9155. end;
  9156. Result := True;
  9157. Exit;
  9158. end;
  9159. else
  9160. ;
  9161. end;
  9162. end;
  9163. p_last := hp1;
  9164. end;
  9165. end;
  9166. function TX86AsmOptimizer.TryJccStcClcOpt(var p, hp1: tai): Boolean;
  9167. var
  9168. hp2, hp3: tai;
  9169. TempBool: Boolean;
  9170. begin
  9171. Result := False;
  9172. {
  9173. j(c) .L1
  9174. stc/clc
  9175. .L1:
  9176. jc/jnc .L2
  9177. (Flags deallocated)
  9178. Change to:
  9179. j)c) .L1
  9180. jmp .L2
  9181. .L1:
  9182. jc/jnc .L2
  9183. Then call DoJumpOptimizations to convert to:
  9184. j(nc) .L2
  9185. .L1: (may become a dead label)
  9186. jc/jnc .L2
  9187. }
  9188. if GetNextInstruction(hp1, hp2) and
  9189. (hp2.typ = ait_label) and
  9190. (tai_label(hp2).labsym = TAsmLabel(taicpu(p).oper[0]^.ref^.symbol)) and
  9191. GetNextInstruction(hp2, hp3) and
  9192. MatchInstruction(hp3, A_Jcc, []) and
  9193. (
  9194. (
  9195. (taicpu(hp3).condition = C_C) and
  9196. (taicpu(hp1).opcode = A_STC)
  9197. ) or (
  9198. (taicpu(hp3).condition = C_NC) and
  9199. (taicpu(hp1).opcode = A_CLC)
  9200. )
  9201. ) and
  9202. { Make sure the flags aren't used again }
  9203. Assigned(FindRegDealloc(NR_DEFAULTFLAGS, tai(hp3.Next))) then
  9204. begin
  9205. taicpu(hp1).allocate_oper(1);
  9206. taicpu(hp1).ops := 1;
  9207. taicpu(hp1).loadsymbol(0, TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol), 0);
  9208. taicpu(hp1).opcode := A_JMP;
  9209. taicpu(hp1).is_jmp := True;
  9210. TempBool := True; { Prevent compiler warnings }
  9211. if DoJumpOptimizations(p, TempBool) then
  9212. Result := True
  9213. else
  9214. Include(OptsToCheck, aoc_ForceNewIteration);
  9215. end;
  9216. end;
  9217. function TX86AsmOptimizer.OptPass2STCCLC(var p: tai): Boolean;
  9218. begin
  9219. { This generally only executes under -O3 and above }
  9220. Result := (aoc_DoPass2JccOpts in OptsToCheck) and OptPass1STCCLC(p);
  9221. end;
  9222. function TX86AsmOptimizer.OptPass2CMOVcc(var p: tai): Boolean;
  9223. var
  9224. hp1, hp2: tai;
  9225. FoundComparison: Boolean;
  9226. begin
  9227. { Run the pass 1 optimisations as well, since they may have some effect
  9228. after the CMOV blocks are created in OptPass2Jcc }
  9229. Result := False;
  9230. { Result := OptPass1CMOVcc(p);
  9231. if Result then
  9232. Exit;}
  9233. { Sometimes, the CMOV optimisations in OptPass2Jcc are a bit overzealous
  9234. and make a slightly inefficent result on branching-type blocks, notably
  9235. when setting a function result then jumping to the function epilogue.
  9236. In this case, change:
  9237. cmov(c) %reg1,%reg2
  9238. j(c) @lbl
  9239. (%reg2 deallocated)
  9240. To:
  9241. mov %reg11,%reg2
  9242. j(c) @lbl
  9243. Note, we can't use GetNextInstructionUsingReg to find the conditional
  9244. jump because if it's not present, we may end up with a jump that's
  9245. completely unrelated.
  9246. }
  9247. hp1 := p;
  9248. while GetNextInstruction(hp1, hp1) and
  9249. MatchInstruction(hp1, A_MOV, A_CMOVcc, []) do { loop };
  9250. if (hp1.typ = ait_instruction) and
  9251. (taicpu(hp1).opcode = A_Jcc) and
  9252. condition_in(taicpu(hp1).condition, taicpu(p).condition) then
  9253. begin
  9254. TransferUsedRegs(TmpUsedRegs);
  9255. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  9256. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) or
  9257. (
  9258. { See if we can find a more distant instruction that overwrites
  9259. the destination register }
  9260. (cs_opt_level3 in current_settings.optimizerswitches) and
  9261. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9262. RegLoadedWithNewValue(taicpu(p).oper[1]^.reg, hp2)
  9263. ) then
  9264. begin
  9265. if (taicpu(p).oper[0]^.typ = top_reg) then
  9266. begin
  9267. { Search backwards to see if the source register is set to a
  9268. constant }
  9269. FoundComparison := False;
  9270. hp1 := p;
  9271. while GetLastInstruction(hp1, hp1) and (hp1.typ = ait_instruction) do
  9272. begin
  9273. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp1) then
  9274. begin
  9275. FoundComparison := True;
  9276. Continue;
  9277. end;
  9278. { Once we find the CMP, TEST or similar instruction, we
  9279. have to stop if we find anything other than a MOV }
  9280. if FoundComparison and (taicpu(hp1).opcode <> A_MOV) then
  9281. Break;
  9282. if RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  9283. { Destination register was modified }
  9284. Break;
  9285. if (taicpu(hp1).opcode = A_MOV) and MatchOpType(taicpu(hp1), top_const, toP_reg)
  9286. and (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) then
  9287. begin
  9288. { Found a constant! }
  9289. taicpu(p).loadconst(0, taicpu(hp1).oper[0]^.val);
  9290. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9291. { The source register is no longer in use }
  9292. RemoveInstruction(hp1);
  9293. Break;
  9294. end;
  9295. if RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) then
  9296. { Some other instruction has modified the source register }
  9297. Break;
  9298. end;
  9299. end;
  9300. DebugMsg(SPeepholeOptimization + 'CMOVcc/Jcc -> MOV/Jcc since register is not used if not branching', p);
  9301. taicpu(p).opcode := A_MOV;
  9302. taicpu(p).condition := C_None;
  9303. { Rely on the post peephole stage to put the MOV before the
  9304. CMP/TEST instruction that appears prior }
  9305. Result := True;
  9306. Exit;
  9307. end;
  9308. end;
  9309. end;
  9310. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  9311. function IsXCHGAcceptable: Boolean; inline;
  9312. begin
  9313. { Always accept if optimising for size }
  9314. Result := (cs_opt_size in current_settings.optimizerswitches) or
  9315. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  9316. than 3, so it becomes a saving compared to three MOVs with two of
  9317. them able to execute simultaneously. [Kit] }
  9318. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  9319. end;
  9320. var
  9321. NewRef: TReference;
  9322. hp1, hp2, hp3, hp4: Tai;
  9323. {$ifndef x86_64}
  9324. OperIdx: Integer;
  9325. {$endif x86_64}
  9326. NewInstr : Taicpu;
  9327. NewAligh : Tai_align;
  9328. DestLabel: TAsmLabel;
  9329. TempTracking: TAllUsedRegs;
  9330. function TryMovArith2Lea(InputInstr: tai): Boolean;
  9331. var
  9332. NextInstr: tai;
  9333. begin
  9334. Result := False;
  9335. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  9336. if not GetNextInstruction(InputInstr, NextInstr) or
  9337. (
  9338. { The FLAGS register isn't always tracked properly, so do not
  9339. perform this optimisation if a conditional statement follows }
  9340. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  9341. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  9342. ) then
  9343. begin
  9344. reference_reset(NewRef, 1, []);
  9345. NewRef.base := taicpu(p).oper[0]^.reg;
  9346. NewRef.scalefactor := 1;
  9347. if taicpu(InputInstr).opcode = A_ADD then
  9348. begin
  9349. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  9350. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  9351. end
  9352. else
  9353. begin
  9354. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  9355. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  9356. end;
  9357. taicpu(p).opcode := A_LEA;
  9358. taicpu(p).loadref(0, NewRef);
  9359. { For the sake of debugging, have the line info match the
  9360. arithmetic instruction rather than the MOV instruction }
  9361. taicpu(p).fileinfo := taicpu(InputInstr).fileinfo;
  9362. RemoveInstruction(InputInstr);
  9363. Result := True;
  9364. end;
  9365. end;
  9366. begin
  9367. Result:=false;
  9368. { This optimisation adds an instruction, so only do it for speed }
  9369. if not (cs_opt_size in current_settings.optimizerswitches) and
  9370. MatchOpType(taicpu(p), top_const, top_reg) and
  9371. (taicpu(p).oper[0]^.val = 0) then
  9372. begin
  9373. { To avoid compiler warning }
  9374. DestLabel := nil;
  9375. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  9376. InternalError(2021040750);
  9377. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  9378. Exit;
  9379. case hp1.typ of
  9380. ait_label:
  9381. begin
  9382. { Change:
  9383. mov $0,%reg mov $0,%reg
  9384. @Lbl1: @Lbl1:
  9385. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  9386. je @Lbl2 jne @Lbl2
  9387. To: To:
  9388. mov $0,%reg mov $0,%reg
  9389. jmp @Lbl2 jmp @Lbl3
  9390. (align) (align)
  9391. @Lbl1: @Lbl1:
  9392. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  9393. je @Lbl2 je @Lbl2
  9394. @Lbl3: <-- Only if label exists
  9395. (Not if it's optimised for size)
  9396. }
  9397. if not GetNextInstruction(hp1, hp2) then
  9398. Exit;
  9399. if (hp2.typ = ait_instruction) and
  9400. (
  9401. { Register sizes must exactly match }
  9402. (
  9403. (taicpu(hp2).opcode = A_CMP) and
  9404. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9405. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9406. ) or (
  9407. (taicpu(hp2).opcode = A_TEST) and
  9408. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9409. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  9410. )
  9411. ) and GetNextInstruction(hp2, hp3) and
  9412. (hp3.typ = ait_instruction) and
  9413. (taicpu(hp3).opcode = A_JCC) and
  9414. (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
  9415. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  9416. begin
  9417. { Check condition of jump }
  9418. { Always true? }
  9419. if condition_in(C_E, taicpu(hp3).condition) then
  9420. begin
  9421. { Copy label symbol and obtain matching label entry for the
  9422. conditional jump, as this will be our destination}
  9423. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  9424. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  9425. Result := True;
  9426. end
  9427. { Always false? }
  9428. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  9429. begin
  9430. { This is only worth it if there's a jump to take }
  9431. case hp2.typ of
  9432. ait_instruction:
  9433. begin
  9434. if taicpu(hp2).opcode = A_JMP then
  9435. begin
  9436. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9437. { An unconditional jump follows the conditional jump which will always be false,
  9438. so use this jump's destination for the new jump }
  9439. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  9440. Result := True;
  9441. end
  9442. else if taicpu(hp2).opcode = A_JCC then
  9443. begin
  9444. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  9445. if condition_in(C_E, taicpu(hp2).condition) then
  9446. begin
  9447. { A second conditional jump follows the conditional jump which will always be false,
  9448. while the second jump is always True, so use this jump's destination for the new jump }
  9449. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  9450. Result := True;
  9451. end;
  9452. { Don't risk it if the jump isn't always true (Result remains False) }
  9453. end;
  9454. end;
  9455. else
  9456. { If anything else don't optimise };
  9457. end;
  9458. end;
  9459. if Result then
  9460. begin
  9461. { Just so we have something to insert as a paremeter}
  9462. reference_reset(NewRef, 1, []);
  9463. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  9464. { Now actually load the correct parameter (this also
  9465. increases the reference count) }
  9466. NewInstr.loadsymbol(0, DestLabel, 0);
  9467. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9468. begin
  9469. { Get instruction before original label (may not be p under -O3) }
  9470. if not GetLastInstruction(hp1, hp2) then
  9471. { Shouldn't fail here }
  9472. InternalError(2021040701);
  9473. end
  9474. else
  9475. hp2 := p;
  9476. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  9477. AsmL.InsertAfter(NewInstr, hp2);
  9478. { Add new alignment field }
  9479. (* AsmL.InsertAfter(
  9480. cai_align.create_max(
  9481. current_settings.alignment.jumpalign,
  9482. current_settings.alignment.jumpalignskipmax
  9483. ),
  9484. NewInstr
  9485. ); *)
  9486. end;
  9487. Exit;
  9488. end;
  9489. end;
  9490. else
  9491. ;
  9492. end;
  9493. end;
  9494. if not GetNextInstruction(p, hp1) then
  9495. Exit;
  9496. if MatchInstruction(hp1, A_CMP, A_TEST, []) then
  9497. begin
  9498. if (taicpu(hp1).opsize = taicpu(p).opsize) and DoMovCmpMemOpt(p, hp1) then
  9499. begin
  9500. Result := True;
  9501. Exit;
  9502. end;
  9503. { This optimisation is only effective on a second run of Pass 2,
  9504. hence -O3 or above.
  9505. Change:
  9506. mov %reg1,%reg2
  9507. cmp/test (contains %reg1)
  9508. mov x, %reg1
  9509. (another mov or a j(c))
  9510. To:
  9511. mov %reg1,%reg2
  9512. mov x, %reg1
  9513. cmp (%reg1 replaced with %reg2)
  9514. (another mov or a j(c))
  9515. The requirement of an additional MOV or a jump ensures there
  9516. isn't performance loss, since a j(c) will permit macro-fusion
  9517. with the cmp instruction, while another MOV likely means it's
  9518. not all being executed in a single cycle due to parallelisation.
  9519. }
  9520. if (cs_opt_level3 in current_settings.optimizerswitches) and
  9521. MatchOpType(taicpu(p), top_reg, top_reg) and
  9522. RegInInstruction(taicpu(p).oper[0]^.reg, taicpu(hp1)) and
  9523. GetNextInstruction(hp1, hp2) and
  9524. MatchInstruction(hp2, A_MOV, []) and
  9525. (taicpu(hp2).oper[1]^.typ = top_reg) and
  9526. { Registers don't have to be the same size in this case }
  9527. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  9528. GetNextInstruction(hp2, hp3) and
  9529. MatchInstruction(hp3, A_MOV, A_Jcc, []) and
  9530. { Make sure the operands in the camparison can be safely replaced }
  9531. (
  9532. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[0]^) or
  9533. ReplaceRegisterInOper(taicpu(hp1), 0, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9534. ) and
  9535. (
  9536. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(hp1).oper[1]^) or
  9537. ReplaceRegisterInOper(taicpu(hp1), 1, taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg)
  9538. ) then
  9539. begin
  9540. DebugMsg(SPeepholeOptimization + 'MOV/CMP/MOV -> MOV/MOV/CMP', p);
  9541. AsmL.Remove(hp2);
  9542. AsmL.InsertAfter(hp2, p);
  9543. Result := True;
  9544. Exit;
  9545. end;
  9546. end;
  9547. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  9548. begin
  9549. { Sometimes the MOVs that OptPass2JMP produces can be improved
  9550. further, but we can't just put this jump optimisation in pass 1
  9551. because it tends to perform worse when conditional jumps are
  9552. nearby (e.g. when converting CMOV instructions). [Kit] }
  9553. CopyUsedRegs(TempTracking);
  9554. UpdateUsedRegs(tai(p.Next));
  9555. if OptPass2JMP(hp1) then
  9556. begin
  9557. { Restore register state }
  9558. RestoreUsedRegs(TempTracking);
  9559. ReleaseUsedRegs(TempTracking);
  9560. { call OptPass1MOV once to potentially merge any MOVs that were created }
  9561. OptPass1MOV(p);
  9562. Result := True;
  9563. Exit;
  9564. end;
  9565. { If OptPass2JMP returned False, no optimisations were done to
  9566. the jump and there are no further optimisations that can be done
  9567. to the MOV instruction on this pass other than FuncMov2Func }
  9568. { Restore register state }
  9569. RestoreUsedRegs(TempTracking);
  9570. ReleaseUsedRegs(TempTracking);
  9571. Result := FuncMov2Func(p, hp1);
  9572. Exit;
  9573. end;
  9574. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9575. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  9576. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9577. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9578. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9579. begin
  9580. { Change:
  9581. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  9582. addl/q $x,%reg2 subl/q $x,%reg2
  9583. To:
  9584. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  9585. }
  9586. if (taicpu(hp1).oper[0]^.typ = top_const) and
  9587. { be lazy, checking separately for sub would be slightly better }
  9588. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  9589. begin
  9590. TransferUsedRegs(TmpUsedRegs);
  9591. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9592. if TryMovArith2Lea(hp1) then
  9593. begin
  9594. Result := True;
  9595. Exit;
  9596. end
  9597. end
  9598. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  9599. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  9600. { Same as above, but also adds or subtracts to %reg2 in between.
  9601. It's still valid as long as the flags aren't in use }
  9602. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  9603. MatchOpType(taicpu(hp2), top_const, top_reg) and
  9604. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9605. { be lazy, checking separately for sub would be slightly better }
  9606. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  9607. begin
  9608. TransferUsedRegs(TmpUsedRegs);
  9609. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9610. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9611. if TryMovArith2Lea(hp2) then
  9612. begin
  9613. Result := True;
  9614. Exit;
  9615. end;
  9616. end;
  9617. end;
  9618. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9619. {$ifdef x86_64}
  9620. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  9621. {$else x86_64}
  9622. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  9623. {$endif x86_64}
  9624. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9625. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  9626. { mov reg1, reg2 mov reg1, reg2
  9627. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  9628. begin
  9629. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  9630. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  9631. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  9632. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  9633. TransferUsedRegs(TmpUsedRegs);
  9634. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9635. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  9636. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  9637. then
  9638. begin
  9639. RemoveCurrentP(p, hp1);
  9640. Result:=true;
  9641. end;
  9642. Exit;
  9643. end;
  9644. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9645. IsXCHGAcceptable and
  9646. { XCHG doesn't support 8-bit registers }
  9647. (taicpu(p).opsize <> S_B) and
  9648. MatchInstruction(hp1, A_MOV, []) and
  9649. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9650. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  9651. GetNextInstruction(hp1, hp2) and
  9652. MatchInstruction(hp2, A_MOV, []) and
  9653. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  9654. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  9655. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  9656. begin
  9657. { mov %reg1,%reg2
  9658. mov %reg3,%reg1 -> xchg %reg3,%reg1
  9659. mov %reg2,%reg3
  9660. (%reg2 not used afterwards)
  9661. Note that xchg takes 3 cycles to execute, and generally mov's take
  9662. only one cycle apiece, but the first two mov's can be executed in
  9663. parallel, only taking 2 cycles overall. Older processors should
  9664. therefore only optimise for size. [Kit]
  9665. }
  9666. TransferUsedRegs(TmpUsedRegs);
  9667. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9668. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9669. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  9670. begin
  9671. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  9672. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  9673. taicpu(hp1).opcode := A_XCHG;
  9674. RemoveCurrentP(p, hp1);
  9675. RemoveInstruction(hp2);
  9676. Result := True;
  9677. Exit;
  9678. end;
  9679. end;
  9680. if MatchOpType(taicpu(p),top_reg,top_reg) and
  9681. MatchInstruction(hp1, A_SAR, []) then
  9682. begin
  9683. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  9684. begin
  9685. { the use of %edx also covers the opsize being S_L }
  9686. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  9687. begin
  9688. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  9689. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  9690. (taicpu(p).oper[1]^.reg = NR_EDX) then
  9691. begin
  9692. { Change:
  9693. movl %eax,%edx
  9694. sarl $31,%edx
  9695. To:
  9696. cltd
  9697. }
  9698. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  9699. RemoveInstruction(hp1);
  9700. taicpu(p).opcode := A_CDQ;
  9701. taicpu(p).opsize := S_NO;
  9702. taicpu(p).clearop(1);
  9703. taicpu(p).clearop(0);
  9704. taicpu(p).ops:=0;
  9705. Result := True;
  9706. Exit;
  9707. end
  9708. else if (cs_opt_size in current_settings.optimizerswitches) and
  9709. (taicpu(p).oper[0]^.reg = NR_EDX) and
  9710. (taicpu(p).oper[1]^.reg = NR_EAX) then
  9711. begin
  9712. { Change:
  9713. movl %edx,%eax
  9714. sarl $31,%edx
  9715. To:
  9716. movl %edx,%eax
  9717. cltd
  9718. Note that this creates a dependency between the two instructions,
  9719. so only perform if optimising for size.
  9720. }
  9721. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  9722. taicpu(hp1).opcode := A_CDQ;
  9723. taicpu(hp1).opsize := S_NO;
  9724. taicpu(hp1).clearop(1);
  9725. taicpu(hp1).clearop(0);
  9726. taicpu(hp1).ops:=0;
  9727. Include(OptsToCheck, aoc_ForceNewIteration);
  9728. Exit;
  9729. end;
  9730. {$ifndef x86_64}
  9731. end
  9732. { Don't bother if CMOV is supported, because a more optimal
  9733. sequence would have been generated for the Abs() intrinsic }
  9734. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  9735. { the use of %eax also covers the opsize being S_L }
  9736. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  9737. (taicpu(p).oper[0]^.reg = NR_EAX) and
  9738. (taicpu(p).oper[1]^.reg = NR_EDX) and
  9739. GetNextInstruction(hp1, hp2) and
  9740. MatchInstruction(hp2, A_XOR, [S_L]) and
  9741. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  9742. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  9743. GetNextInstruction(hp2, hp3) and
  9744. MatchInstruction(hp3, A_SUB, [S_L]) and
  9745. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  9746. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  9747. begin
  9748. { Change:
  9749. movl %eax,%edx
  9750. sarl $31,%eax
  9751. xorl %eax,%edx
  9752. subl %eax,%edx
  9753. (Instruction that uses %edx)
  9754. (%eax deallocated)
  9755. (%edx deallocated)
  9756. To:
  9757. cltd
  9758. xorl %edx,%eax <-- Note the registers have swapped
  9759. subl %edx,%eax
  9760. (Instruction that uses %eax) <-- %eax rather than %edx
  9761. }
  9762. TransferUsedRegs(TmpUsedRegs);
  9763. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9764. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9765. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9766. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  9767. begin
  9768. if GetNextInstruction(hp3, hp4) and
  9769. not RegModifiedByInstruction(NR_EDX, hp4) and
  9770. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  9771. begin
  9772. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  9773. taicpu(p).opcode := A_CDQ;
  9774. taicpu(p).clearop(1);
  9775. taicpu(p).clearop(0);
  9776. taicpu(p).ops:=0;
  9777. RemoveInstruction(hp1);
  9778. taicpu(hp2).loadreg(0, NR_EDX);
  9779. taicpu(hp2).loadreg(1, NR_EAX);
  9780. taicpu(hp3).loadreg(0, NR_EDX);
  9781. taicpu(hp3).loadreg(1, NR_EAX);
  9782. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  9783. { Convert references in the following instruction (hp4) from %edx to %eax }
  9784. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  9785. with taicpu(hp4).oper[OperIdx]^ do
  9786. case typ of
  9787. top_reg:
  9788. if getsupreg(reg) = RS_EDX then
  9789. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9790. top_ref:
  9791. begin
  9792. if getsupreg(reg) = RS_EDX then
  9793. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9794. if getsupreg(reg) = RS_EDX then
  9795. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  9796. end;
  9797. else
  9798. ;
  9799. end;
  9800. Result := True;
  9801. Exit;
  9802. end;
  9803. end;
  9804. {$else x86_64}
  9805. end;
  9806. end
  9807. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  9808. { the use of %rdx also covers the opsize being S_Q }
  9809. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  9810. begin
  9811. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  9812. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  9813. (taicpu(p).oper[1]^.reg = NR_RDX) then
  9814. begin
  9815. { Change:
  9816. movq %rax,%rdx
  9817. sarq $63,%rdx
  9818. To:
  9819. cqto
  9820. }
  9821. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  9822. RemoveInstruction(hp1);
  9823. taicpu(p).opcode := A_CQO;
  9824. taicpu(p).opsize := S_NO;
  9825. taicpu(p).clearop(1);
  9826. taicpu(p).clearop(0);
  9827. taicpu(p).ops:=0;
  9828. Result := True;
  9829. Exit;
  9830. end
  9831. else if (cs_opt_size in current_settings.optimizerswitches) and
  9832. (taicpu(p).oper[0]^.reg = NR_RDX) and
  9833. (taicpu(p).oper[1]^.reg = NR_RAX) then
  9834. begin
  9835. { Change:
  9836. movq %rdx,%rax
  9837. sarq $63,%rdx
  9838. To:
  9839. movq %rdx,%rax
  9840. cqto
  9841. Note that this creates a dependency between the two instructions,
  9842. so only perform if optimising for size.
  9843. }
  9844. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  9845. taicpu(hp1).opcode := A_CQO;
  9846. taicpu(hp1).opsize := S_NO;
  9847. taicpu(hp1).clearop(1);
  9848. taicpu(hp1).clearop(0);
  9849. taicpu(hp1).ops:=0;
  9850. Include(OptsToCheck, aoc_ForceNewIteration);
  9851. Exit;
  9852. {$endif x86_64}
  9853. end;
  9854. end;
  9855. end;
  9856. if MatchInstruction(hp1, A_MOV, []) and
  9857. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9858. { Though "GetNextInstruction" could be factored out, along with
  9859. the instructions that depend on hp2, it is an expensive call that
  9860. should be delayed for as long as possible, hence we do cheaper
  9861. checks first that are likely to be False. [Kit] }
  9862. begin
  9863. if (
  9864. (
  9865. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  9866. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  9867. (
  9868. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9869. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  9870. )
  9871. ) or
  9872. (
  9873. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  9874. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  9875. (
  9876. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9877. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  9878. )
  9879. )
  9880. ) and
  9881. GetNextInstruction(hp1, hp2) and
  9882. MatchInstruction(hp2, A_SAR, []) and
  9883. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  9884. begin
  9885. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  9886. begin
  9887. { Change:
  9888. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  9889. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  9890. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  9891. To:
  9892. movl r/m,%eax <- Note the change in register
  9893. cltd
  9894. }
  9895. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  9896. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  9897. taicpu(p).loadreg(1, NR_EAX);
  9898. taicpu(hp1).opcode := A_CDQ;
  9899. taicpu(hp1).clearop(1);
  9900. taicpu(hp1).clearop(0);
  9901. taicpu(hp1).ops:=0;
  9902. RemoveInstruction(hp2);
  9903. Include(OptsToCheck, aoc_ForceNewIteration);
  9904. (*
  9905. {$ifdef x86_64}
  9906. end
  9907. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  9908. { This code sequence does not get generated - however it might become useful
  9909. if and when 128-bit signed integer types make an appearance, so the code
  9910. is kept here for when it is eventually needed. [Kit] }
  9911. (
  9912. (
  9913. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  9914. (
  9915. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9916. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  9917. )
  9918. ) or
  9919. (
  9920. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  9921. (
  9922. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  9923. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  9924. )
  9925. )
  9926. ) and
  9927. GetNextInstruction(hp1, hp2) and
  9928. MatchInstruction(hp2, A_SAR, [S_Q]) and
  9929. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  9930. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  9931. begin
  9932. { Change:
  9933. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  9934. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  9935. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  9936. To:
  9937. movq r/m,%rax <- Note the change in register
  9938. cqto
  9939. }
  9940. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  9941. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  9942. taicpu(p).loadreg(1, NR_RAX);
  9943. taicpu(hp1).opcode := A_CQO;
  9944. taicpu(hp1).clearop(1);
  9945. taicpu(hp1).clearop(0);
  9946. taicpu(hp1).ops:=0;
  9947. RemoveInstruction(hp2);
  9948. Include(OptsToCheck, aoc_ForceNewIteration);
  9949. {$endif x86_64}
  9950. *)
  9951. end;
  9952. end;
  9953. {$ifdef x86_64}
  9954. end;
  9955. if (taicpu(p).opsize = S_L) and
  9956. (taicpu(p).oper[1]^.typ = top_reg) and
  9957. (
  9958. MatchInstruction(hp1, A_MOV,[]) and
  9959. (taicpu(hp1).opsize = S_L) and
  9960. (taicpu(hp1).oper[1]^.typ = top_reg)
  9961. ) and (
  9962. GetNextInstruction(hp1, hp2) and
  9963. (tai(hp2).typ=ait_instruction) and
  9964. (taicpu(hp2).opsize = S_Q) and
  9965. (
  9966. (
  9967. MatchInstruction(hp2, A_ADD,[]) and
  9968. (taicpu(hp2).opsize = S_Q) and
  9969. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  9970. (
  9971. (
  9972. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9973. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9974. ) or (
  9975. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9976. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9977. )
  9978. )
  9979. ) or (
  9980. MatchInstruction(hp2, A_LEA,[]) and
  9981. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  9982. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  9983. (
  9984. (
  9985. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  9986. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9987. ) or (
  9988. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  9989. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  9990. )
  9991. ) and (
  9992. (
  9993. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  9994. ) or (
  9995. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  9996. )
  9997. )
  9998. )
  9999. )
  10000. ) and (
  10001. GetNextInstruction(hp2, hp3) and
  10002. MatchInstruction(hp3, A_SHR,[]) and
  10003. (taicpu(hp3).opsize = S_Q) and
  10004. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  10005. (taicpu(hp3).oper[0]^.val = 1) and
  10006. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  10007. ) then
  10008. begin
  10009. { Change movl x, reg1d movl x, reg1d
  10010. movl y, reg2d movl y, reg2d
  10011. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  10012. shrq $1, reg1q shrq $1, reg1q
  10013. ( reg1d and reg2d can be switched around in the first two instructions )
  10014. To movl x, reg1d
  10015. addl y, reg1d
  10016. rcrl $1, reg1d
  10017. This corresponds to the common expression (x + y) shr 1, where
  10018. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  10019. smaller code, but won't account for x + y causing an overflow). [Kit]
  10020. }
  10021. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  10022. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10023. begin
  10024. { Change first MOV command to have the same register as the final output }
  10025. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10026. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp1, UsedRegs);
  10027. Result := True;
  10028. end
  10029. else
  10030. begin
  10031. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  10032. Include(OptsToCheck, aoc_ForceNewIteration);
  10033. end;
  10034. { Change second MOV command to an ADD command. This is easier than
  10035. converting the existing command because it means we don't have to
  10036. touch 'y', which might be a complicated reference, and also the
  10037. fact that the third command might either be ADD or LEA. [Kit] }
  10038. taicpu(hp1).opcode := A_ADD;
  10039. { Delete old ADD/LEA instruction }
  10040. RemoveInstruction(hp2);
  10041. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  10042. taicpu(hp3).opcode := A_RCR;
  10043. taicpu(hp3).changeopsize(S_L);
  10044. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  10045. { Don't need to Exit yet as p is still a MOV and hp1 hasn't been
  10046. called, so FuncMov2Func below is safe to call }
  10047. {$endif x86_64}
  10048. end;
  10049. if FuncMov2Func(p, hp1) then
  10050. begin
  10051. Result := True;
  10052. Exit;
  10053. end;
  10054. end;
  10055. {$push}
  10056. {$q-}{$r-}
  10057. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  10058. var
  10059. ThisReg: TRegister;
  10060. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  10061. TargetSubReg: TSubRegister;
  10062. hp1, hp2: tai;
  10063. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  10064. { Store list of found instructions so we don't have to call
  10065. GetNextInstructionUsingReg multiple times }
  10066. InstrList: array of taicpu;
  10067. InstrMax, Index: Integer;
  10068. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  10069. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  10070. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  10071. WorkingValue: TCgInt;
  10072. PreMessage: string;
  10073. { Data flow analysis }
  10074. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  10075. BitwiseOnly, OrXorUsed,
  10076. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  10077. function CheckOverflowConditions: Boolean;
  10078. begin
  10079. Result := True;
  10080. if (TestValSignedMax > SignedUpperLimit) then
  10081. UpperSignedOverflow := True;
  10082. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  10083. LowerSignedOverflow := True;
  10084. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  10085. LowerUnsignedOverflow := True;
  10086. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  10087. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  10088. begin
  10089. { Absolute overflow }
  10090. Result := False;
  10091. Exit;
  10092. end;
  10093. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  10094. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  10095. ShiftDownOverflow := True;
  10096. if (TestValMin < 0) or (TestValMax < 0) then
  10097. begin
  10098. LowerUnsignedOverflow := True;
  10099. UpperUnsignedOverflow := True;
  10100. end;
  10101. end;
  10102. function AdjustInitialLoadAndSize: Boolean;
  10103. begin
  10104. Result := False;
  10105. if not p_removed then
  10106. begin
  10107. if TargetSize = MinSize then
  10108. begin
  10109. { Convert the input MOVZX to a MOV }
  10110. if (taicpu(p).oper[0]^.typ = top_reg) and
  10111. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10112. begin
  10113. { Or remove it completely! }
  10114. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  10115. RemoveCurrentP(p);
  10116. p_removed := True;
  10117. end
  10118. else
  10119. begin
  10120. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  10121. taicpu(p).opcode := A_MOV;
  10122. taicpu(p).oper[1]^.reg := ThisReg;
  10123. taicpu(p).opsize := TargetSize;
  10124. end;
  10125. Result := True;
  10126. end
  10127. else if TargetSize <> MaxSize then
  10128. begin
  10129. case MaxSize of
  10130. S_L:
  10131. if TargetSize = S_W then
  10132. begin
  10133. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  10134. taicpu(p).opsize := S_BW;
  10135. taicpu(p).oper[1]^.reg := ThisReg;
  10136. Result := True;
  10137. end
  10138. else
  10139. InternalError(2020112341);
  10140. S_W:
  10141. if TargetSize = S_L then
  10142. begin
  10143. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  10144. taicpu(p).opsize := S_BL;
  10145. taicpu(p).oper[1]^.reg := ThisReg;
  10146. Result := True;
  10147. end
  10148. else
  10149. InternalError(2020112342);
  10150. else
  10151. ;
  10152. end;
  10153. end
  10154. else if not hp1_removed and not RegInUse then
  10155. begin
  10156. { If we have something like:
  10157. movzbl (oper),%regd
  10158. add x, %regd
  10159. movzbl %regb, %regd
  10160. We can reduce the register size to the input of the final
  10161. movzbl instruction. Overflows won't have any effect.
  10162. }
  10163. if (taicpu(p).opsize in [S_BW, S_BL]) and
  10164. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10165. begin
  10166. TargetSize := S_B;
  10167. setsubreg(ThisReg, R_SUBL);
  10168. Result := True;
  10169. end
  10170. else if (taicpu(p).opsize = S_WL) and
  10171. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  10172. begin
  10173. TargetSize := S_W;
  10174. setsubreg(ThisReg, R_SUBW);
  10175. Result := True;
  10176. end;
  10177. if Result then
  10178. begin
  10179. { Convert the input MOVZX to a MOV }
  10180. if (taicpu(p).oper[0]^.typ = top_reg) and
  10181. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  10182. begin
  10183. { Or remove it completely! }
  10184. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  10185. RemoveCurrentP(p);
  10186. p_removed := True;
  10187. end
  10188. else
  10189. begin
  10190. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  10191. taicpu(p).opcode := A_MOV;
  10192. taicpu(p).oper[1]^.reg := ThisReg;
  10193. taicpu(p).opsize := TargetSize;
  10194. end;
  10195. end;
  10196. end;
  10197. end;
  10198. end;
  10199. procedure AdjustFinalLoad;
  10200. begin
  10201. if not LowerUnsignedOverflow then
  10202. begin
  10203. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  10204. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  10205. begin
  10206. { Convert the output MOVZX to a MOV }
  10207. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10208. begin
  10209. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  10210. if (MinSize = S_B) or
  10211. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  10212. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  10213. begin
  10214. { Remove it completely! }
  10215. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  10216. { Be careful; if p = hp1 and p was also removed, p
  10217. will become a dangling pointer }
  10218. if p = hp1 then
  10219. begin
  10220. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10221. p_removed := True;
  10222. end
  10223. else
  10224. RemoveInstruction(hp1);
  10225. hp1_removed := True;
  10226. end;
  10227. end
  10228. else
  10229. begin
  10230. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  10231. taicpu(hp1).opcode := A_MOV;
  10232. taicpu(hp1).oper[0]^.reg := ThisReg;
  10233. taicpu(hp1).opsize := TargetSize;
  10234. end;
  10235. end
  10236. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  10237. begin
  10238. { Need to change the size of the output }
  10239. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  10240. taicpu(hp1).oper[0]^.reg := ThisReg;
  10241. taicpu(hp1).opsize := S_BL;
  10242. end;
  10243. end;
  10244. end;
  10245. function CompressInstructions: Boolean;
  10246. var
  10247. LocalIndex: Integer;
  10248. begin
  10249. Result := False;
  10250. { The objective here is to try to find a combination that
  10251. removes one of the MOV/Z instructions. }
  10252. if (
  10253. (taicpu(p).oper[0]^.typ <> top_reg) or
  10254. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  10255. ) and
  10256. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10257. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10258. begin
  10259. { Make a preference to remove the second MOVZX instruction }
  10260. case taicpu(hp1).opsize of
  10261. S_BL, S_WL:
  10262. begin
  10263. TargetSize := S_L;
  10264. TargetSubReg := R_SUBD;
  10265. end;
  10266. S_BW:
  10267. begin
  10268. TargetSize := S_W;
  10269. TargetSubReg := R_SUBW;
  10270. end;
  10271. else
  10272. InternalError(2020112302);
  10273. end;
  10274. end
  10275. else
  10276. begin
  10277. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10278. begin
  10279. { Exceeded lower bound but not upper bound }
  10280. TargetSize := MaxSize;
  10281. end
  10282. else if not LowerUnsignedOverflow then
  10283. begin
  10284. { Size didn't exceed lower bound }
  10285. TargetSize := MinSize;
  10286. end
  10287. else
  10288. Exit;
  10289. end;
  10290. case TargetSize of
  10291. S_B:
  10292. TargetSubReg := R_SUBL;
  10293. S_W:
  10294. TargetSubReg := R_SUBW;
  10295. S_L:
  10296. TargetSubReg := R_SUBD;
  10297. else
  10298. InternalError(2020112350);
  10299. end;
  10300. { Update the register to its new size }
  10301. setsubreg(ThisReg, TargetSubReg);
  10302. RegInUse := False;
  10303. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  10304. begin
  10305. { Check to see if the active register is used afterwards;
  10306. if not, we can change it and make a saving. }
  10307. TransferUsedRegs(TmpUsedRegs);
  10308. { The target register may be marked as in use to cross
  10309. a jump to a distant label, so exclude it }
  10310. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  10311. hp2 := p;
  10312. repeat
  10313. { Explicitly check for the excluded register (don't include the first
  10314. instruction as it may be reading from here }
  10315. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  10316. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  10317. begin
  10318. RegInUse := True;
  10319. Break;
  10320. end;
  10321. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  10322. if not GetNextInstruction(hp2, hp2) then
  10323. InternalError(2020112340);
  10324. until (hp2 = hp1);
  10325. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10326. { We might still be able to get away with this }
  10327. RegInUse := not
  10328. (
  10329. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  10330. (hp2.typ = ait_instruction) and
  10331. (
  10332. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10333. instruction that doesn't actually contain ThisReg }
  10334. (cs_opt_level3 in current_settings.optimizerswitches) or
  10335. RegInInstruction(ThisReg, hp2)
  10336. ) and
  10337. RegLoadedWithNewValue(ThisReg, hp2)
  10338. );
  10339. if not RegInUse then
  10340. begin
  10341. { Force the register size to the same as this instruction so it can be removed}
  10342. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  10343. begin
  10344. TargetSize := S_L;
  10345. TargetSubReg := R_SUBD;
  10346. end
  10347. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  10348. begin
  10349. TargetSize := S_W;
  10350. TargetSubReg := R_SUBW;
  10351. end;
  10352. ThisReg := taicpu(hp1).oper[1]^.reg;
  10353. setsubreg(ThisReg, TargetSubReg);
  10354. RegChanged := True;
  10355. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  10356. TransferUsedRegs(TmpUsedRegs);
  10357. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  10358. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  10359. if p = hp1 then
  10360. begin
  10361. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  10362. p_removed := True;
  10363. end
  10364. else
  10365. RemoveInstruction(hp1);
  10366. hp1_removed := True;
  10367. { Instruction will become "mov %reg,%reg" }
  10368. if not p_removed and (taicpu(p).opcode = A_MOV) and
  10369. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  10370. begin
  10371. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  10372. RemoveCurrentP(p);
  10373. p_removed := True;
  10374. end
  10375. else
  10376. taicpu(p).oper[1]^.reg := ThisReg;
  10377. Result := True;
  10378. end
  10379. else
  10380. begin
  10381. if TargetSize <> MaxSize then
  10382. begin
  10383. { Since the register is in use, we have to force it to
  10384. MaxSize otherwise part of it may become undefined later on }
  10385. TargetSize := MaxSize;
  10386. case TargetSize of
  10387. S_B:
  10388. TargetSubReg := R_SUBL;
  10389. S_W:
  10390. TargetSubReg := R_SUBW;
  10391. S_L:
  10392. TargetSubReg := R_SUBD;
  10393. else
  10394. InternalError(2020112351);
  10395. end;
  10396. setsubreg(ThisReg, TargetSubReg);
  10397. end;
  10398. AdjustFinalLoad;
  10399. end;
  10400. end
  10401. else
  10402. AdjustFinalLoad;
  10403. Result := AdjustInitialLoadAndSize or Result;
  10404. { Now go through every instruction we found and change the
  10405. size. If TargetSize = MaxSize, then almost no changes are
  10406. needed and Result can remain False if it hasn't been set
  10407. yet.
  10408. If RegChanged is True, then the register requires changing
  10409. and so the point about TargetSize = MaxSize doesn't apply. }
  10410. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  10411. begin
  10412. for LocalIndex := 0 to InstrMax do
  10413. begin
  10414. { If p_removed is true, then the original MOV/Z was removed
  10415. and removing the AND instruction may not be safe if it
  10416. appears first }
  10417. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  10418. InternalError(2020112310);
  10419. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  10420. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  10421. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  10422. InstrList[LocalIndex].opsize := TargetSize;
  10423. end;
  10424. Result := True;
  10425. end;
  10426. end;
  10427. begin
  10428. Result := False;
  10429. p_removed := False;
  10430. hp1_removed := False;
  10431. ThisReg := taicpu(p).oper[1]^.reg;
  10432. { Check for:
  10433. movs/z ###,%ecx (or %cx or %rcx)
  10434. ...
  10435. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10436. (dealloc %ecx)
  10437. Change to:
  10438. mov ###,%cl (if ### = %cl, then remove completely)
  10439. ...
  10440. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  10441. }
  10442. if (getsupreg(ThisReg) = RS_ECX) and
  10443. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  10444. (hp1.typ = ait_instruction) and
  10445. (
  10446. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10447. instruction that doesn't actually contain ECX }
  10448. (cs_opt_level3 in current_settings.optimizerswitches) or
  10449. RegInInstruction(NR_ECX, hp1) or
  10450. (
  10451. { It's common for the shift/rotate's read/write register to be
  10452. initialised in between, so under -O2 and under, search ahead
  10453. one more instruction
  10454. }
  10455. GetNextInstruction(hp1, hp1) and
  10456. (hp1.typ = ait_instruction) and
  10457. RegInInstruction(NR_ECX, hp1)
  10458. )
  10459. ) and
  10460. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  10461. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  10462. begin
  10463. TransferUsedRegs(TmpUsedRegs);
  10464. hp2 := p;
  10465. repeat
  10466. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10467. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10468. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  10469. begin
  10470. case taicpu(p).opsize of
  10471. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10472. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  10473. begin
  10474. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  10475. RemoveCurrentP(p);
  10476. end
  10477. else
  10478. begin
  10479. taicpu(p).opcode := A_MOV;
  10480. taicpu(p).opsize := S_B;
  10481. taicpu(p).oper[1]^.reg := NR_CL;
  10482. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  10483. end;
  10484. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10485. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  10486. begin
  10487. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  10488. RemoveCurrentP(p);
  10489. end
  10490. else
  10491. begin
  10492. taicpu(p).opcode := A_MOV;
  10493. taicpu(p).opsize := S_W;
  10494. taicpu(p).oper[1]^.reg := NR_CX;
  10495. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  10496. end;
  10497. {$ifdef x86_64}
  10498. S_LQ:
  10499. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  10500. begin
  10501. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  10502. RemoveCurrentP(p);
  10503. end
  10504. else
  10505. begin
  10506. taicpu(p).opcode := A_MOV;
  10507. taicpu(p).opsize := S_L;
  10508. taicpu(p).oper[1]^.reg := NR_ECX;
  10509. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  10510. end;
  10511. {$endif x86_64}
  10512. else
  10513. InternalError(2021120401);
  10514. end;
  10515. Result := True;
  10516. Exit;
  10517. end;
  10518. end;
  10519. { This is anything but quick! }
  10520. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  10521. Exit;
  10522. SetLength(InstrList, 0);
  10523. InstrMax := -1;
  10524. case taicpu(p).opsize of
  10525. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10526. begin
  10527. {$if defined(i386) or defined(i8086)}
  10528. { If the target size is 8-bit, make sure we can actually encode it }
  10529. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  10530. Exit;
  10531. {$endif i386 or i8086}
  10532. LowerLimit := $FF;
  10533. SignedLowerLimit := $7F;
  10534. SignedLowerLimitBottom := -128;
  10535. MinSize := S_B;
  10536. if taicpu(p).opsize = S_BW then
  10537. begin
  10538. MaxSize := S_W;
  10539. UpperLimit := $FFFF;
  10540. SignedUpperLimit := $7FFF;
  10541. SignedUpperLimitBottom := -32768;
  10542. end
  10543. else
  10544. begin
  10545. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  10546. MaxSize := S_L;
  10547. UpperLimit := $FFFFFFFF;
  10548. SignedUpperLimit := $7FFFFFFF;
  10549. SignedUpperLimitBottom := -2147483648;
  10550. end;
  10551. end;
  10552. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10553. begin
  10554. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  10555. LowerLimit := $FFFF;
  10556. SignedLowerLimit := $7FFF;
  10557. SignedLowerLimitBottom := -32768;
  10558. UpperLimit := $FFFFFFFF;
  10559. SignedUpperLimit := $7FFFFFFF;
  10560. SignedUpperLimitBottom := -2147483648;
  10561. MinSize := S_W;
  10562. MaxSize := S_L;
  10563. end;
  10564. {$ifdef x86_64}
  10565. S_LQ:
  10566. begin
  10567. { Both the lower and upper limits are set to 32-bit. If a limit
  10568. is breached, then optimisation is impossible }
  10569. LowerLimit := $FFFFFFFF;
  10570. SignedLowerLimit := $7FFFFFFF;
  10571. SignedLowerLimitBottom := -2147483648;
  10572. UpperLimit := $FFFFFFFF;
  10573. SignedUpperLimit := $7FFFFFFF;
  10574. SignedUpperLimitBottom := -2147483648;
  10575. MinSize := S_L;
  10576. MaxSize := S_L;
  10577. end;
  10578. {$endif x86_64}
  10579. else
  10580. InternalError(2020112301);
  10581. end;
  10582. TestValMin := 0;
  10583. TestValMax := LowerLimit;
  10584. TestValSignedMax := SignedLowerLimit;
  10585. TryShiftDownLimit := LowerLimit;
  10586. TryShiftDown := S_NO;
  10587. ShiftDownOverflow := False;
  10588. RegChanged := False;
  10589. BitwiseOnly := True;
  10590. OrXorUsed := False;
  10591. UpperSignedOverflow := False;
  10592. LowerSignedOverflow := False;
  10593. UpperUnsignedOverflow := False;
  10594. LowerUnsignedOverflow := False;
  10595. hp1 := p;
  10596. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  10597. (hp1.typ = ait_instruction) and
  10598. (
  10599. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  10600. instruction that doesn't actually contain ThisReg }
  10601. (cs_opt_level3 in current_settings.optimizerswitches) or
  10602. { This allows this Movx optimisation to work through the SETcc instructions
  10603. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10604. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10605. skip over these SETcc instructions). }
  10606. (taicpu(hp1).opcode = A_SETcc) or
  10607. RegInInstruction(ThisReg, hp1)
  10608. ) do
  10609. begin
  10610. case taicpu(hp1).opcode of
  10611. A_INC,A_DEC:
  10612. begin
  10613. { Has to be an exact match on the register }
  10614. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  10615. Break;
  10616. if taicpu(hp1).opcode = A_INC then
  10617. begin
  10618. Inc(TestValMin);
  10619. Inc(TestValMax);
  10620. Inc(TestValSignedMax);
  10621. end
  10622. else
  10623. begin
  10624. Dec(TestValMin);
  10625. Dec(TestValMax);
  10626. Dec(TestValSignedMax);
  10627. end;
  10628. end;
  10629. A_TEST, A_CMP:
  10630. begin
  10631. if (
  10632. { Too high a risk of non-linear behaviour that breaks DFA
  10633. here, unless it's cmp $0,%reg, which is equivalent to
  10634. test %reg,%reg }
  10635. OrXorUsed and
  10636. (taicpu(hp1).opcode = A_CMP) and
  10637. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  10638. ) or
  10639. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10640. { Has to be an exact match on the register }
  10641. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10642. (
  10643. { Permit "test %reg,%reg" }
  10644. (taicpu(hp1).opcode = A_TEST) and
  10645. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10646. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  10647. ) or
  10648. (taicpu(hp1).oper[0]^.typ <> top_const) or
  10649. { Make sure the comparison value is not smaller than the
  10650. smallest allowed signed value for the minimum size (e.g.
  10651. -128 for 8-bit) }
  10652. not (
  10653. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  10654. { Is it in the negative range? }
  10655. (
  10656. (taicpu(hp1).oper[0]^.val < 0) and
  10657. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  10658. )
  10659. ) then
  10660. Break;
  10661. { Check to see if the active register is used afterwards }
  10662. TransferUsedRegs(TmpUsedRegs);
  10663. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  10664. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  10665. begin
  10666. { Make sure the comparison or any previous instructions
  10667. hasn't pushed the test values outside of the range of
  10668. MinSize }
  10669. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  10670. begin
  10671. { Exceeded lower bound but not upper bound }
  10672. Exit;
  10673. end
  10674. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  10675. begin
  10676. { Size didn't exceed lower bound }
  10677. TargetSize := MinSize;
  10678. end
  10679. else
  10680. Break;
  10681. case TargetSize of
  10682. S_B:
  10683. TargetSubReg := R_SUBL;
  10684. S_W:
  10685. TargetSubReg := R_SUBW;
  10686. S_L:
  10687. TargetSubReg := R_SUBD;
  10688. else
  10689. InternalError(2021051002);
  10690. end;
  10691. if TargetSize <> MaxSize then
  10692. begin
  10693. { Update the register to its new size }
  10694. setsubreg(ThisReg, TargetSubReg);
  10695. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  10696. taicpu(hp1).oper[1]^.reg := ThisReg;
  10697. taicpu(hp1).opsize := TargetSize;
  10698. { Convert the input MOVZX to a MOV if necessary }
  10699. AdjustInitialLoadAndSize;
  10700. if (InstrMax >= 0) then
  10701. begin
  10702. for Index := 0 to InstrMax do
  10703. begin
  10704. { If p_removed is true, then the original MOV/Z was removed
  10705. and removing the AND instruction may not be safe if it
  10706. appears first }
  10707. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  10708. InternalError(2020112311);
  10709. if InstrList[Index].oper[0]^.typ = top_reg then
  10710. InstrList[Index].oper[0]^.reg := ThisReg;
  10711. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  10712. InstrList[Index].opsize := MinSize;
  10713. end;
  10714. end;
  10715. Result := True;
  10716. end;
  10717. Exit;
  10718. end;
  10719. end;
  10720. A_SETcc:
  10721. begin
  10722. { This allows this Movx optimisation to work through the SETcc instructions
  10723. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  10724. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  10725. skip over these SETcc instructions). }
  10726. if (cs_opt_level3 in current_settings.optimizerswitches) or
  10727. { Of course, break out if the current register is used }
  10728. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  10729. Break
  10730. else
  10731. { We must use Continue so the instruction doesn't get added
  10732. to InstrList }
  10733. Continue;
  10734. end;
  10735. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  10736. begin
  10737. if
  10738. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  10739. { Has to be an exact match on the register }
  10740. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  10741. (
  10742. (
  10743. (taicpu(hp1).oper[0]^.typ = top_const) and
  10744. (
  10745. (
  10746. (taicpu(hp1).opcode = A_SHL) and
  10747. (
  10748. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  10749. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  10750. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  10751. )
  10752. ) or (
  10753. (taicpu(hp1).opcode <> A_SHL) and
  10754. (
  10755. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10756. { Is it in the negative range? }
  10757. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  10758. )
  10759. )
  10760. )
  10761. ) or (
  10762. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  10763. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  10764. )
  10765. ) then
  10766. Break;
  10767. { Only process OR and XOR if there are only bitwise operations,
  10768. since otherwise they can too easily fool the data flow
  10769. analysis (they can cause non-linear behaviour) }
  10770. case taicpu(hp1).opcode of
  10771. A_ADD:
  10772. begin
  10773. if OrXorUsed then
  10774. { Too high a risk of non-linear behaviour that breaks DFA here }
  10775. Break
  10776. else
  10777. BitwiseOnly := False;
  10778. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10779. begin
  10780. TestValMin := TestValMin * 2;
  10781. TestValMax := TestValMax * 2;
  10782. TestValSignedMax := TestValSignedMax * 2;
  10783. end
  10784. else
  10785. begin
  10786. WorkingValue := taicpu(hp1).oper[0]^.val;
  10787. TestValMin := TestValMin + WorkingValue;
  10788. TestValMax := TestValMax + WorkingValue;
  10789. TestValSignedMax := TestValSignedMax + WorkingValue;
  10790. end;
  10791. end;
  10792. A_SUB:
  10793. begin
  10794. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10795. begin
  10796. TestValMin := 0;
  10797. TestValMax := 0;
  10798. TestValSignedMax := 0;
  10799. end
  10800. else
  10801. begin
  10802. if OrXorUsed then
  10803. { Too high a risk of non-linear behaviour that breaks DFA here }
  10804. Break
  10805. else
  10806. BitwiseOnly := False;
  10807. WorkingValue := taicpu(hp1).oper[0]^.val;
  10808. TestValMin := TestValMin - WorkingValue;
  10809. TestValMax := TestValMax - WorkingValue;
  10810. TestValSignedMax := TestValSignedMax - WorkingValue;
  10811. end;
  10812. end;
  10813. A_AND:
  10814. if (taicpu(hp1).oper[0]^.typ = top_const) then
  10815. begin
  10816. { we might be able to go smaller if AND appears first }
  10817. if InstrMax = -1 then
  10818. case MinSize of
  10819. S_B:
  10820. ;
  10821. S_W:
  10822. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10823. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10824. begin
  10825. TryShiftDown := S_B;
  10826. TryShiftDownLimit := $FF;
  10827. end;
  10828. S_L:
  10829. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  10830. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  10831. begin
  10832. TryShiftDown := S_B;
  10833. TryShiftDownLimit := $FF;
  10834. end
  10835. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  10836. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  10837. begin
  10838. TryShiftDown := S_W;
  10839. TryShiftDownLimit := $FFFF;
  10840. end;
  10841. else
  10842. InternalError(2020112320);
  10843. end;
  10844. WorkingValue := taicpu(hp1).oper[0]^.val;
  10845. TestValMin := TestValMin and WorkingValue;
  10846. TestValMax := TestValMax and WorkingValue;
  10847. TestValSignedMax := TestValSignedMax and WorkingValue;
  10848. end;
  10849. A_OR:
  10850. begin
  10851. if not BitwiseOnly then
  10852. Break;
  10853. OrXorUsed := True;
  10854. WorkingValue := taicpu(hp1).oper[0]^.val;
  10855. TestValMin := TestValMin or WorkingValue;
  10856. TestValMax := TestValMax or WorkingValue;
  10857. TestValSignedMax := TestValSignedMax or WorkingValue;
  10858. end;
  10859. A_XOR:
  10860. begin
  10861. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10862. begin
  10863. TestValMin := 0;
  10864. TestValMax := 0;
  10865. TestValSignedMax := 0;
  10866. end
  10867. else
  10868. begin
  10869. if not BitwiseOnly then
  10870. Break;
  10871. OrXorUsed := True;
  10872. WorkingValue := taicpu(hp1).oper[0]^.val;
  10873. TestValMin := TestValMin xor WorkingValue;
  10874. TestValMax := TestValMax xor WorkingValue;
  10875. TestValSignedMax := TestValSignedMax xor WorkingValue;
  10876. end;
  10877. end;
  10878. A_SHL:
  10879. begin
  10880. BitwiseOnly := False;
  10881. WorkingValue := taicpu(hp1).oper[0]^.val;
  10882. TestValMin := TestValMin shl WorkingValue;
  10883. TestValMax := TestValMax shl WorkingValue;
  10884. TestValSignedMax := TestValSignedMax shl WorkingValue;
  10885. end;
  10886. A_SHR,
  10887. { The first instruction was MOVZX, so the value won't be negative }
  10888. A_SAR:
  10889. begin
  10890. if InstrMax <> -1 then
  10891. BitwiseOnly := False
  10892. else
  10893. { we might be able to go smaller if SHR appears first }
  10894. case MinSize of
  10895. S_B:
  10896. ;
  10897. S_W:
  10898. if (taicpu(hp1).oper[0]^.val >= 8) then
  10899. begin
  10900. TryShiftDown := S_B;
  10901. TryShiftDownLimit := $FF;
  10902. TryShiftDownSignedLimit := $7F;
  10903. TryShiftDownSignedLimitLower := -128;
  10904. end;
  10905. S_L:
  10906. if (taicpu(hp1).oper[0]^.val >= 24) then
  10907. begin
  10908. TryShiftDown := S_B;
  10909. TryShiftDownLimit := $FF;
  10910. TryShiftDownSignedLimit := $7F;
  10911. TryShiftDownSignedLimitLower := -128;
  10912. end
  10913. else if (taicpu(hp1).oper[0]^.val >= 16) then
  10914. begin
  10915. TryShiftDown := S_W;
  10916. TryShiftDownLimit := $FFFF;
  10917. TryShiftDownSignedLimit := $7FFF;
  10918. TryShiftDownSignedLimitLower := -32768;
  10919. end;
  10920. else
  10921. InternalError(2020112321);
  10922. end;
  10923. WorkingValue := taicpu(hp1).oper[0]^.val;
  10924. if taicpu(hp1).opcode = A_SAR then
  10925. begin
  10926. TestValMin := SarInt64(TestValMin, WorkingValue);
  10927. TestValMax := SarInt64(TestValMax, WorkingValue);
  10928. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  10929. end
  10930. else
  10931. begin
  10932. TestValMin := TestValMin shr WorkingValue;
  10933. TestValMax := TestValMax shr WorkingValue;
  10934. TestValSignedMax := TestValSignedMax shr WorkingValue;
  10935. end;
  10936. end;
  10937. else
  10938. InternalError(2020112303);
  10939. end;
  10940. end;
  10941. (*
  10942. A_IMUL:
  10943. case taicpu(hp1).ops of
  10944. 2:
  10945. begin
  10946. if not MatchOpType(hp1, top_reg, top_reg) or
  10947. { Has to be an exact match on the register }
  10948. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  10949. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  10950. Break;
  10951. TestValMin := TestValMin * TestValMin;
  10952. TestValMax := TestValMax * TestValMax;
  10953. TestValSignedMax := TestValSignedMax * TestValMax;
  10954. end;
  10955. 3:
  10956. begin
  10957. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10958. { Has to be an exact match on the register }
  10959. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10960. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10961. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10962. { Is it in the negative range? }
  10963. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10964. Break;
  10965. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  10966. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  10967. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  10968. end;
  10969. else
  10970. Break;
  10971. end;
  10972. A_IDIV:
  10973. case taicpu(hp1).ops of
  10974. 3:
  10975. begin
  10976. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  10977. { Has to be an exact match on the register }
  10978. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  10979. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  10980. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  10981. { Is it in the negative range? }
  10982. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  10983. Break;
  10984. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  10985. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  10986. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  10987. end;
  10988. else
  10989. Break;
  10990. end;
  10991. *)
  10992. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10993. begin
  10994. { If there are no instructions in between, then we might be able to make a saving }
  10995. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  10996. Break;
  10997. { We have something like:
  10998. movzbw %dl,%dx
  10999. ...
  11000. movswl %dx,%edx
  11001. Change the latter to a zero-extension then enter the
  11002. A_MOVZX case branch.
  11003. }
  11004. {$ifdef x86_64}
  11005. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11006. begin
  11007. { this becomes a zero extension from 32-bit to 64-bit, but
  11008. the upper 32 bits are already zero, so just delete the
  11009. instruction }
  11010. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  11011. RemoveInstruction(hp1);
  11012. Result := True;
  11013. Exit;
  11014. end
  11015. else
  11016. {$endif x86_64}
  11017. begin
  11018. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  11019. taicpu(hp1).opcode := A_MOVZX;
  11020. {$ifdef x86_64}
  11021. case taicpu(hp1).opsize of
  11022. S_BQ:
  11023. begin
  11024. taicpu(hp1).opsize := S_BL;
  11025. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11026. end;
  11027. S_WQ:
  11028. begin
  11029. taicpu(hp1).opsize := S_WL;
  11030. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11031. end;
  11032. S_LQ:
  11033. begin
  11034. taicpu(hp1).opcode := A_MOV;
  11035. taicpu(hp1).opsize := S_L;
  11036. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11037. { In this instance, we need to break out because the
  11038. instruction is no longer MOVZX or MOVSXD }
  11039. Result := True;
  11040. Exit;
  11041. end;
  11042. else
  11043. ;
  11044. end;
  11045. {$endif x86_64}
  11046. Result := CompressInstructions;
  11047. Exit;
  11048. end;
  11049. end;
  11050. A_MOVZX:
  11051. begin
  11052. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  11053. Break;
  11054. if (InstrMax = -1) then
  11055. begin
  11056. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  11057. begin
  11058. { Optimise around i40003 }
  11059. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  11060. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  11061. {$ifndef x86_64}
  11062. and (
  11063. (taicpu(p).oper[0]^.typ <> top_reg) or
  11064. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  11065. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  11066. )
  11067. {$endif not x86_64}
  11068. then
  11069. begin
  11070. if (taicpu(p).oper[0]^.typ = top_reg) then
  11071. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  11072. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  11073. taicpu(p).opsize := S_BL;
  11074. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  11075. RemoveInstruction(hp1);
  11076. Result := True;
  11077. Exit;
  11078. end;
  11079. end
  11080. else
  11081. begin
  11082. { Will return false if the second parameter isn't ThisReg
  11083. (can happen on -O2 and under) }
  11084. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  11085. begin
  11086. { The two MOVZX instructions are adjacent, so remove the first one }
  11087. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  11088. RemoveCurrentP(p);
  11089. Result := True;
  11090. Exit;
  11091. end;
  11092. Break;
  11093. end;
  11094. end;
  11095. Result := CompressInstructions;
  11096. Exit;
  11097. end;
  11098. else
  11099. { This includes ADC, SBB and IDIV }
  11100. Break;
  11101. end;
  11102. if not CheckOverflowConditions then
  11103. Break;
  11104. { Contains highest index (so instruction count - 1) }
  11105. Inc(InstrMax);
  11106. if InstrMax > High(InstrList) then
  11107. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11108. InstrList[InstrMax] := taicpu(hp1);
  11109. end;
  11110. end;
  11111. {$pop}
  11112. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  11113. var
  11114. hp1 : tai;
  11115. begin
  11116. Result:=false;
  11117. if (taicpu(p).ops >= 2) and
  11118. ((taicpu(p).oper[0]^.typ = top_const) or
  11119. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  11120. (taicpu(p).oper[1]^.typ = top_reg) and
  11121. ((taicpu(p).ops = 2) or
  11122. ((taicpu(p).oper[2]^.typ = top_reg) and
  11123. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  11124. GetLastInstruction(p,hp1) and
  11125. MatchInstruction(hp1,A_MOV,[]) and
  11126. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11127. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11128. begin
  11129. TransferUsedRegs(TmpUsedRegs);
  11130. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  11131. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  11132. { change
  11133. mov reg1,reg2
  11134. imul y,reg2 to imul y,reg1,reg2 }
  11135. begin
  11136. taicpu(p).ops := 3;
  11137. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  11138. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  11139. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  11140. RemoveInstruction(hp1);
  11141. result:=true;
  11142. end;
  11143. end;
  11144. end;
  11145. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  11146. var
  11147. ThisLabel: TAsmLabel;
  11148. begin
  11149. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  11150. ThisLabel.decrefs;
  11151. taicpu(p).condition := C_None;
  11152. taicpu(p).opcode := A_RET;
  11153. taicpu(p).is_jmp := false;
  11154. taicpu(p).ops := taicpu(ret_p).ops;
  11155. case taicpu(ret_p).ops of
  11156. 0:
  11157. taicpu(p).clearop(0);
  11158. 1:
  11159. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  11160. else
  11161. internalerror(2016041301);
  11162. end;
  11163. { If the original label is now dead, it might turn out that the label
  11164. immediately follows p. As a result, everything beyond it, which will
  11165. be just some final register configuration and a RET instruction, is
  11166. now dead code. [Kit] }
  11167. { NOTE: This is much faster than introducing a OptPass2RET routine and
  11168. running RemoveDeadCodeAfterJump for each RET instruction, because
  11169. this optimisation rarely happens and most RETs appear at the end of
  11170. routines where there is nothing that can be stripped. [Kit] }
  11171. if not ThisLabel.is_used then
  11172. RemoveDeadCodeAfterJump(p);
  11173. end;
  11174. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  11175. var
  11176. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  11177. Unconditional, PotentialModified: Boolean;
  11178. OperPtr: POper;
  11179. NewRef: TReference;
  11180. InstrList: array of taicpu;
  11181. InstrMax, Index: Integer;
  11182. const
  11183. {$ifdef DEBUG_AOPTCPU}
  11184. SNoFlags: shortstring = ' so the flags aren''t modified';
  11185. {$else DEBUG_AOPTCPU}
  11186. SNoFlags = '';
  11187. {$endif DEBUG_AOPTCPU}
  11188. begin
  11189. Result:=false;
  11190. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  11191. begin
  11192. if MatchInstruction(hp1, A_TEST, [S_B]) and
  11193. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11194. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11195. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11196. GetNextInstruction(hp1, hp2) and
  11197. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  11198. { Change from: To:
  11199. set(C) %reg j(~C) label
  11200. test %reg,%reg/cmp $0,%reg
  11201. je label
  11202. set(C) %reg j(C) label
  11203. test %reg,%reg/cmp $0,%reg
  11204. jne label
  11205. (Also do something similar with sete/setne instead of je/jne)
  11206. }
  11207. begin
  11208. { Before we do anything else, we need to check the instructions
  11209. in between SETcc and TEST to make sure they don't modify the
  11210. FLAGS register - if -O2 or under, there won't be any
  11211. instructions between SET and TEST }
  11212. TransferUsedRegs(TmpUsedRegs);
  11213. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11214. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11215. begin
  11216. next := p;
  11217. SetLength(InstrList, 0);
  11218. InstrMax := -1;
  11219. PotentialModified := False;
  11220. { Make a note of every instruction that modifies the FLAGS
  11221. register }
  11222. while GetNextInstruction(next, next) and (next <> hp1) do
  11223. begin
  11224. if next.typ <> ait_instruction then
  11225. { GetNextInstructionUsingReg should have returned False }
  11226. InternalError(2021051701);
  11227. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  11228. begin
  11229. case taicpu(next).opcode of
  11230. A_SETcc,
  11231. A_CMOVcc,
  11232. A_Jcc:
  11233. begin
  11234. if PotentialModified then
  11235. { Not safe because the flags were modified earlier }
  11236. Exit
  11237. else
  11238. { Condition is the same as the initial SETcc, so this is safe
  11239. (don't add to instruction list though) }
  11240. Continue;
  11241. end;
  11242. A_ADD:
  11243. begin
  11244. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11245. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11246. (taicpu(next).oper[1]^.typ <> top_reg) or
  11247. { Must write to a register }
  11248. (taicpu(next).oper[0]^.typ = top_ref) then
  11249. { Require a constant or a register }
  11250. Exit;
  11251. PotentialModified := True;
  11252. end;
  11253. A_SUB:
  11254. begin
  11255. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11256. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11257. (taicpu(next).oper[1]^.typ <> top_reg) or
  11258. { Must write to a register }
  11259. (taicpu(next).oper[0]^.typ <> top_const) or
  11260. (taicpu(next).oper[0]^.val = $80000000) then
  11261. { Can't subtract a register with LEA - also
  11262. check that the value isn't -2^31, as this
  11263. can't be negated }
  11264. Exit;
  11265. PotentialModified := True;
  11266. end;
  11267. A_SAL,
  11268. A_SHL:
  11269. begin
  11270. if { LEA doesn't support 8-bit in general and 16-bit on x86-64 operands }
  11271. (taicpu(next).opsize in [S_B{$ifdef x86_64},S_W{$endif x86_64}]) or
  11272. (taicpu(next).oper[1]^.typ <> top_reg) or
  11273. { Must write to a register }
  11274. (taicpu(next).oper[0]^.typ <> top_const) or
  11275. (taicpu(next).oper[0]^.val < 0) or
  11276. (taicpu(next).oper[0]^.val > 3) then
  11277. Exit;
  11278. PotentialModified := True;
  11279. end;
  11280. A_IMUL:
  11281. begin
  11282. if (taicpu(next).ops <> 3) or
  11283. (taicpu(next).oper[1]^.typ <> top_reg) or
  11284. { Must write to a register }
  11285. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  11286. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  11287. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  11288. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  11289. Exit
  11290. else
  11291. PotentialModified := True;
  11292. end;
  11293. else
  11294. { Don't know how to change this, so abort }
  11295. Exit;
  11296. end;
  11297. { Contains highest index (so instruction count - 1) }
  11298. Inc(InstrMax);
  11299. if InstrMax > High(InstrList) then
  11300. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  11301. InstrList[InstrMax] := taicpu(next);
  11302. end;
  11303. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  11304. end;
  11305. if not Assigned(next) or (next <> hp1) then
  11306. { It should be equal to hp1 }
  11307. InternalError(2021051702);
  11308. { Cycle through each instruction and check to see if we can
  11309. change them to versions that don't modify the flags }
  11310. if (InstrMax >= 0) then
  11311. begin
  11312. for Index := 0 to InstrMax do
  11313. case InstrList[Index].opcode of
  11314. A_ADD:
  11315. begin
  11316. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  11317. InstrList[Index].opcode := A_LEA;
  11318. reference_reset(NewRef, 1, []);
  11319. NewRef.base := InstrList[Index].oper[1]^.reg;
  11320. if InstrList[Index].oper[0]^.typ = top_reg then
  11321. begin
  11322. NewRef.index := InstrList[Index].oper[0]^.reg;
  11323. NewRef.scalefactor := 1;
  11324. end
  11325. else
  11326. NewRef.offset := InstrList[Index].oper[0]^.val;
  11327. InstrList[Index].loadref(0, NewRef);
  11328. end;
  11329. A_SUB:
  11330. begin
  11331. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  11332. InstrList[Index].opcode := A_LEA;
  11333. reference_reset(NewRef, 1, []);
  11334. NewRef.base := InstrList[Index].oper[1]^.reg;
  11335. NewRef.offset := -InstrList[Index].oper[0]^.val;
  11336. InstrList[Index].loadref(0, NewRef);
  11337. end;
  11338. A_SHL,
  11339. A_SAL:
  11340. begin
  11341. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  11342. InstrList[Index].opcode := A_LEA;
  11343. reference_reset(NewRef, 1, []);
  11344. NewRef.index := InstrList[Index].oper[1]^.reg;
  11345. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  11346. InstrList[Index].loadref(0, NewRef);
  11347. end;
  11348. A_IMUL:
  11349. begin
  11350. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  11351. InstrList[Index].opcode := A_LEA;
  11352. reference_reset(NewRef, 1, []);
  11353. NewRef.index := InstrList[Index].oper[1]^.reg;
  11354. case InstrList[Index].oper[0]^.val of
  11355. 2, 4, 8:
  11356. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  11357. else {3, 5 and 9}
  11358. begin
  11359. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  11360. NewRef.base := InstrList[Index].oper[1]^.reg;
  11361. end;
  11362. end;
  11363. InstrList[Index].loadref(0, NewRef);
  11364. end;
  11365. else
  11366. InternalError(2021051710);
  11367. end;
  11368. end;
  11369. { Mark the FLAGS register as used across this whole block }
  11370. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  11371. end;
  11372. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11373. JumpC := taicpu(hp2).condition;
  11374. Unconditional := False;
  11375. if conditions_equal(JumpC, C_E) then
  11376. SetC := inverse_cond(taicpu(p).condition)
  11377. else if conditions_equal(JumpC, C_NE) then
  11378. SetC := taicpu(p).condition
  11379. else
  11380. { We've got something weird here (and inefficent) }
  11381. begin
  11382. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  11383. SetC := C_NONE;
  11384. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  11385. if condition_in(C_AE, JumpC) then
  11386. Unconditional := True
  11387. else
  11388. { Not sure what to do with this jump - drop out }
  11389. Exit;
  11390. end;
  11391. RemoveInstruction(hp1);
  11392. if Unconditional then
  11393. MakeUnconditional(taicpu(hp2))
  11394. else
  11395. begin
  11396. if SetC = C_NONE then
  11397. InternalError(2018061402);
  11398. taicpu(hp2).SetCondition(SetC);
  11399. end;
  11400. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  11401. TmpUsedRegs }
  11402. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  11403. begin
  11404. RemoveCurrentp(p, hp2);
  11405. if taicpu(hp2).opcode = A_SETcc then
  11406. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  11407. else
  11408. begin
  11409. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  11410. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11411. Include(OptsToCheck, aoc_DoPass2JccOpts);
  11412. end;
  11413. end
  11414. else
  11415. if taicpu(hp2).opcode = A_SETcc then
  11416. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  11417. else
  11418. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  11419. Result := True;
  11420. end
  11421. else if
  11422. { Make sure the instructions are adjacent }
  11423. (
  11424. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11425. GetNextInstruction(p, hp1)
  11426. ) and
  11427. MatchInstruction(hp1, A_MOV, [S_B]) and
  11428. { Writing to memory is allowed }
  11429. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  11430. begin
  11431. {
  11432. Watch out for sequences such as:
  11433. set(c)b %regb
  11434. movb %regb,(ref)
  11435. movb $0,1(ref)
  11436. movb $0,2(ref)
  11437. movb $0,3(ref)
  11438. Much more efficient to turn it into:
  11439. movl $0,%regl
  11440. set(c)b %regb
  11441. movl %regl,(ref)
  11442. Or:
  11443. set(c)b %regb
  11444. movzbl %regb,%regl
  11445. movl %regl,(ref)
  11446. }
  11447. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  11448. GetNextInstruction(hp1, hp2) and
  11449. MatchInstruction(hp2, A_MOV, [S_B]) and
  11450. (taicpu(hp2).oper[1]^.typ = top_ref) and
  11451. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  11452. begin
  11453. { Don't do anything else except set Result to True }
  11454. end
  11455. else
  11456. begin
  11457. if taicpu(p).oper[0]^.typ = top_reg then
  11458. begin
  11459. TransferUsedRegs(TmpUsedRegs);
  11460. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11461. end;
  11462. { If it's not a register, it's a memory address }
  11463. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  11464. begin
  11465. { Even if the register is still in use, we can minimise the
  11466. pipeline stall by changing the MOV into another SETcc. }
  11467. taicpu(hp1).opcode := A_SETcc;
  11468. taicpu(hp1).condition := taicpu(p).condition;
  11469. if taicpu(hp1).oper[1]^.typ = top_ref then
  11470. begin
  11471. { Swapping the operand pointers like this is probably a
  11472. bit naughty, but it is far faster than using loadoper
  11473. to transfer the reference from oper[1] to oper[0] if
  11474. you take into account the extra procedure calls and
  11475. the memory allocation and deallocation required }
  11476. OperPtr := taicpu(hp1).oper[1];
  11477. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  11478. taicpu(hp1).oper[0] := OperPtr;
  11479. end
  11480. else
  11481. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  11482. taicpu(hp1).clearop(1);
  11483. taicpu(hp1).ops := 1;
  11484. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  11485. end
  11486. else
  11487. begin
  11488. if taicpu(hp1).oper[1]^.typ = top_reg then
  11489. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  11490. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  11491. RemoveInstruction(hp1);
  11492. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  11493. end
  11494. end;
  11495. Result := True;
  11496. end;
  11497. end;
  11498. end;
  11499. function TX86AsmOptimizer.TryCmpCMovOpts(var p, hp1: tai): Boolean;
  11500. var
  11501. hp2, pCond, pFirstMOV, pLastMOV, pCMOV: tai;
  11502. TargetReg: TRegister;
  11503. condition, inverted_condition: TAsmCond;
  11504. FoundMOV: Boolean;
  11505. begin
  11506. Result := False;
  11507. { In some situations, the CMOV optimisations in OptPass2Jcc can't
  11508. create the most optimial instructions possible due to limited
  11509. register availability, and there are situations where two
  11510. complementary "simple" CMOV blocks are created which, after the fact
  11511. can be merged into a "double" block. For example:
  11512. movw $257,%ax
  11513. movw $2,%r8w
  11514. xorl r9d,%r9d
  11515. testw $16,18(%rcx)
  11516. cmovew %ax,%dx
  11517. cmovew %r8w,%bx
  11518. cmovel %r9d,%r14d
  11519. movw $1283,%ax
  11520. movw $4,%r8w
  11521. movl $9,%r9d
  11522. cmovnew %ax,%dx
  11523. cmovnew %r8w,%bx
  11524. cmovnel %r9d,%r14d
  11525. The CMOVNE instructions at the end can be removed, and the
  11526. destination registers copied into the MOV instructions directly
  11527. above them, before finally being moved to before the first CMOVE
  11528. instructions, to produce:
  11529. movw $257,%ax
  11530. movw $2,%r8w
  11531. xorl r9d,%r9d
  11532. testw $16,18(%rcx)
  11533. movw $1283,%dx
  11534. movw $4,%bx
  11535. movl $9,%r14d
  11536. cmovew %ax,%dx
  11537. cmovew %r8w,%bx
  11538. cmovel %r9d,%r14d
  11539. Which can then be later optimised to:
  11540. movw $257,%ax
  11541. movw $2,%r8w
  11542. xorl r9d,%r9d
  11543. movw $1283,%dx
  11544. movw $4,%bx
  11545. movl $9,%r14d
  11546. testw $16,18(%rcx)
  11547. cmovew %ax,%dx
  11548. cmovew %r8w,%bx
  11549. cmovel %r9d,%r14d
  11550. }
  11551. TargetReg := taicpu(hp1).oper[1]^.reg;
  11552. condition := taicpu(hp1).condition;
  11553. inverted_condition := inverse_cond(condition);
  11554. pFirstMov := nil;
  11555. pLastMov := nil;
  11556. pCMOV := nil;
  11557. if (p.typ = ait_instruction) then
  11558. pCond := p
  11559. else if not GetNextInstruction(p, pCond) then
  11560. InternalError(2024012501);
  11561. if not MatchInstruction(pCond, A_CMP, A_TEST, []) then
  11562. { We should get the CMP or TEST instructeion }
  11563. InternalError(2024012502);
  11564. if (
  11565. (taicpu(hp1).oper[0]^.typ = top_reg) or
  11566. IsRefSafe(taicpu(hp1).oper[0]^.ref)
  11567. ) then
  11568. begin
  11569. { We have to tread carefully here, hence why we're not using
  11570. GetNextInstructionUsingReg... we can only accept MOV and other
  11571. CMOV instructions. Anything else and we must drop out}
  11572. hp2 := hp1;
  11573. while GetNextInstruction(hp2, hp2) and (hp2 <> BlockEnd) do
  11574. begin
  11575. if (hp2.typ <> ait_instruction) then
  11576. Exit;
  11577. case taicpu(hp2).opcode of
  11578. A_MOV:
  11579. begin
  11580. if not Assigned(pFirstMov) then
  11581. pFirstMov := hp2;
  11582. pLastMOV := hp2;
  11583. if not MatchOpType(taicpu(hp2), top_const, top_reg) then
  11584. { Something different - drop out }
  11585. Exit;
  11586. { Otherwise, leave it for now }
  11587. end;
  11588. A_CMOVcc:
  11589. begin
  11590. if taicpu(hp2).condition = inverted_condition then
  11591. begin
  11592. { We found what we're looking for }
  11593. if taicpu(hp2).oper[1]^.reg = TargetReg then
  11594. begin
  11595. if (taicpu(hp2).oper[0]^.typ = top_reg) or
  11596. IsRefSafe(taicpu(hp2).oper[0]^.ref) then
  11597. begin
  11598. pCMOV := hp2;
  11599. Break;
  11600. end
  11601. else
  11602. { Unsafe reference - drop out }
  11603. Exit;
  11604. end;
  11605. end
  11606. else if taicpu(hp2).condition <> condition then
  11607. { Something weird - drop out }
  11608. Exit;
  11609. end;
  11610. else
  11611. { Invalid }
  11612. Exit;
  11613. end;
  11614. end;
  11615. if not Assigned(pCMOV) then
  11616. { No complementary CMOV found }
  11617. Exit;
  11618. if not Assigned(pFirstMov) or (taicpu(pCMOV).oper[0]^.typ = top_ref) then
  11619. begin
  11620. { Don't need to do anything special or search for a matching MOV }
  11621. Asml.Remove(pCMOV);
  11622. if RegInInstruction(TargetReg, pCond) then
  11623. { Make sure we don't overwrite the register if it's being used in the condition }
  11624. Asml.InsertAfter(pCMOV, pCond)
  11625. else
  11626. Asml.InsertBefore(pCMOV, pCond);
  11627. taicpu(pCMOV).opcode := A_MOV;
  11628. taicpu(pCMOV).condition := C_None;
  11629. { Don't need to worry about allocating new registers in these cases }
  11630. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 2', pCMOV);
  11631. Result := True;
  11632. Exit;
  11633. end
  11634. else
  11635. begin
  11636. DebugMsg(SPeepholeOptimization + 'CMovCMov2MovCMov 1', hp1);
  11637. FoundMOV := False;
  11638. { Search for the MOV that sets the target register }
  11639. hp2 := pFirstMov;
  11640. repeat
  11641. if (taicpu(hp2).opcode = A_MOV) and
  11642. (taicpu(hp2).oper[1]^.typ = top_reg) and
  11643. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(pCMOV).oper[0]^.reg) then
  11644. begin
  11645. { Change the destination }
  11646. taicpu(hp2).loadreg(1, newreg(R_INTREGISTER, getsupreg(TargetReg), getsubreg(taicpu(hp2).oper[1]^.reg)));
  11647. if not FoundMOV then
  11648. begin
  11649. FoundMOV := True;
  11650. { Make sure the register is allocated }
  11651. AllocRegBetween(TargetReg, p, hp2, UsedRegs);
  11652. end;
  11653. hp1 := tai(hp2.Previous);
  11654. Asml.Remove(hp2);
  11655. if RegInInstruction(TargetReg, pCond) then
  11656. { Make sure we don't overwrite the register if it's being used in the condition }
  11657. Asml.InsertAfter(hp2, pCond)
  11658. else
  11659. Asml.InsertBefore(hp2, pCond);
  11660. if (hp2 = pLastMov) then
  11661. { If the MOV instruction is the last one, "hp2 = pLastMOV" won't trigger }
  11662. Break;
  11663. hp2 := hp1;
  11664. end;
  11665. until (hp2 = pLastMOV) or not GetNextInstruction(hp2, hp2) or (hp2 = BlockEnd) or (hp2.typ <> ait_instruction);
  11666. if FoundMOV then
  11667. { Delete the CMOV }
  11668. RemoveInstruction(pCMOV)
  11669. else
  11670. begin
  11671. { If no MOV was found, we have to actually move and transmute the CMOV }
  11672. Asml.Remove(pCMOV);
  11673. if RegInInstruction(TargetReg, pCond) then
  11674. { Make sure we don't overwrite the register if it's being used in the condition }
  11675. Asml.InsertAfter(pCMOV, pCond)
  11676. else
  11677. Asml.InsertBefore(pCMOV, pCond);
  11678. taicpu(pCMOV).opcode := A_MOV;
  11679. taicpu(pCMOV).condition := C_None;
  11680. end;
  11681. Result := True;
  11682. Exit;
  11683. end;
  11684. end;
  11685. end;
  11686. function TX86AsmOptimizer.OptPass2Cmp(var p: tai): Boolean;
  11687. var
  11688. hp1, hp2, pCond: tai;
  11689. begin
  11690. Result := False;
  11691. { Search ahead for CMOV instructions }
  11692. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11693. begin
  11694. hp1 := p;
  11695. hp2 := p;
  11696. pCond := nil; { To prevent compiler warnings }
  11697. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11698. DEFAULTFLAGS }
  11699. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11700. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11701. pCond := p;
  11702. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11703. begin
  11704. if (hp1.typ <> ait_instruction) then
  11705. { Break out on markers and labels etc. }
  11706. Break;
  11707. case taicpu(hp1).opcode of
  11708. A_MOV:
  11709. { Ignore regular MOVs unless they are obviously not related
  11710. to a CMOV block }
  11711. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11712. Break;
  11713. A_CMOVcc:
  11714. if TryCmpCMovOpts(pCond, hp1) then
  11715. begin
  11716. hp1 := hp2;
  11717. { p itself isn't changed, and we're still inside a
  11718. while loop to catch subsequent CMOVs, so just flag
  11719. a new iteration }
  11720. Include(OptsToCheck, aoc_ForceNewIteration);
  11721. Continue;
  11722. end;
  11723. else
  11724. { Drop out if we find anything else }
  11725. Break;
  11726. end;
  11727. hp2 := hp1;
  11728. end;
  11729. end;
  11730. end;
  11731. function TX86AsmOptimizer.OptPass2Test(var p: tai): Boolean;
  11732. var
  11733. hp1, hp2, pCond: tai;
  11734. SourceReg, TargetReg: TRegister;
  11735. begin
  11736. Result := False;
  11737. { In some situations, we end up with an inefficient arrangement of
  11738. instructions in the form of:
  11739. or %reg1,%reg2
  11740. (%reg1 deallocated)
  11741. test %reg2,%reg2
  11742. mov x,%reg2
  11743. we may be able to swap and rearrange the registers to produce:
  11744. or %reg2,%reg1
  11745. mov x,%reg2
  11746. test %reg1,%reg1
  11747. (%reg1 deallocated)
  11748. }
  11749. if (cs_opt_level3 in current_settings.optimizerswitches) and
  11750. (taicpu(p).oper[1]^.typ = top_reg) and
  11751. (
  11752. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) or
  11753. MatchOperand(taicpu(p).oper[0]^, -1)
  11754. ) and
  11755. GetNextInstruction(p, hp1) and
  11756. MatchInstruction(hp1, A_MOV, []) and
  11757. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11758. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  11759. begin
  11760. TargetReg := taicpu(p).oper[1]^.reg;
  11761. { Now look backwards to find a simple commutative operation: ADD,
  11762. IMUL (2-register version), OR, AND or XOR - whose destination
  11763. register is the same as TEST }
  11764. hp2 := p;
  11765. while GetLastInstruction(hp2, hp2) and (hp2.typ = ait_instruction) do
  11766. if RegInInstruction(TargetReg, hp2) then
  11767. begin
  11768. if MatchInstruction(hp2, [A_ADD, A_IMUL, A_OR, A_AND, A_XOR], [taicpu(p).opsize]) and
  11769. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11770. (taicpu(hp2).oper[1]^.reg = TargetReg) and
  11771. (taicpu(hp2).oper[0]^.reg <> TargetReg) then
  11772. begin
  11773. SourceReg := taicpu(hp2).oper[0]^.reg;
  11774. if
  11775. { Make sure the MOV doesn't use the other register }
  11776. not RegInOp(SourceReg, taicpu(hp1).oper[0]^) and
  11777. { And make sure the source register is not used afterwards }
  11778. not RegInUsedRegs(SourceReg, UsedRegs) then
  11779. begin
  11780. DebugMsg(SPeepholeOptimization + 'OpTest2OpTest (register swap) done', hp2);
  11781. taicpu(hp2).oper[0]^.reg := TargetReg;
  11782. taicpu(hp2).oper[1]^.reg := SourceReg;
  11783. if taicpu(p).oper[0]^.typ = top_reg then
  11784. taicpu(p).oper[0]^.reg := SourceReg;
  11785. taicpu(p).oper[1]^.reg := SourceReg;
  11786. IncludeRegInUsedRegs(SourceReg, UsedRegs);
  11787. AllocRegBetween(SourceReg, hp2, p, UsedRegs);
  11788. Include(OptsToCheck, aoc_ForceNewIteration);
  11789. { We can still check the following optimisations since
  11790. the instruction is still a TEST }
  11791. end;
  11792. end;
  11793. Break;
  11794. end;
  11795. end;
  11796. { Search ahead3 for CMOV instructions }
  11797. if (cs_opt_level2 in current_settings.optimizerswitches) then
  11798. begin
  11799. hp1 := p;
  11800. hp2 := p;
  11801. pCond := nil; { To prevent compiler warnings }
  11802. { For TryCmpCMOVOpts, try to insert MOVs before the allocation of
  11803. DEFAULTFLAGS }
  11804. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, p), pCond) or
  11805. (tai_regalloc(pCond).ratype = ra_dealloc) then
  11806. pCond := p;
  11807. while GetNextInstruction(hp1, hp1) and (hp1 <> BlockEnd) do
  11808. begin
  11809. if (hp1.typ <> ait_instruction) then
  11810. { Break out on markers and labels etc. }
  11811. Break;
  11812. case taicpu(hp1).opcode of
  11813. A_MOV:
  11814. { Ignore regular MOVs unless they are obviously not related
  11815. to a CMOV block }
  11816. if taicpu(hp1).oper[1]^.typ <> top_reg then
  11817. Break;
  11818. A_CMOVcc:
  11819. if TryCmpCMovOpts(pCond, hp1) then
  11820. begin
  11821. hp1 := hp2;
  11822. { p itself isn't changed, and we're still inside a
  11823. while loop to catch subsequent CMOVs, so just flag
  11824. a new iteration }
  11825. Include(OptsToCheck, aoc_ForceNewIteration);
  11826. Continue;
  11827. end;
  11828. else
  11829. { Drop out if we find anything else }
  11830. Break;
  11831. end;
  11832. hp2 := hp1;
  11833. end;
  11834. end;
  11835. end;
  11836. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  11837. var
  11838. hp1: tai;
  11839. Count: Integer;
  11840. OrigLabel: TAsmLabel;
  11841. begin
  11842. result := False;
  11843. { Sometimes, the optimisations below can permit this }
  11844. RemoveDeadCodeAfterJump(p);
  11845. 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
  11846. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  11847. begin
  11848. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  11849. { Also a side-effect of optimisations }
  11850. if CollapseZeroDistJump(p, OrigLabel) then
  11851. begin
  11852. Result := True;
  11853. Exit;
  11854. end;
  11855. hp1 := GetLabelWithSym(OrigLabel);
  11856. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  11857. begin
  11858. if taicpu(hp1).opcode = A_RET then
  11859. begin
  11860. {
  11861. change
  11862. jmp .L1
  11863. ...
  11864. .L1:
  11865. ret
  11866. into
  11867. ret
  11868. }
  11869. begin
  11870. ConvertJumpToRET(p, hp1);
  11871. result:=true;
  11872. end;
  11873. end
  11874. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  11875. not (cs_opt_size in current_settings.optimizerswitches) and
  11876. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  11877. begin
  11878. Result := True;
  11879. Exit;
  11880. end;
  11881. end;
  11882. end;
  11883. end;
  11884. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai; var RefModified: Boolean) : boolean;
  11885. begin
  11886. Result := assigned(p) and
  11887. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  11888. (taicpu(p).oper[1]^.typ = top_reg) and
  11889. (
  11890. (taicpu(p).oper[0]^.typ = top_reg) or
  11891. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  11892. it is not expected that this can cause a seg. violation }
  11893. (
  11894. (taicpu(p).oper[0]^.typ = top_ref) and
  11895. { TODO: Can we detect which references become constants at this
  11896. stage so we don't have to do a blanket ban? }
  11897. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  11898. (
  11899. IsRefSafe(taicpu(p).oper[0]^.ref) or
  11900. (
  11901. { Don't use the reference in the condition if one of its registers got modified by a previous MOV }
  11902. not RefModified and
  11903. { If the reference also appears in the condition, then we know it's safe, otherwise
  11904. any kind of access violation would have occurred already }
  11905. Assigned(cond_p) and
  11906. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  11907. (cond_p.typ = ait_instruction) and
  11908. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  11909. { Just consider 2-operand comparison instructions for now to be safe }
  11910. (taicpu(cond_p).ops = 2) and
  11911. (
  11912. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  11913. (
  11914. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  11915. { Don't risk identical registers but different offsets, as we may have constructs
  11916. such as buffer streams with things like length fields that indicate whether
  11917. any more data follows. And there are probably some contrived examples where
  11918. writing to offsets behind the one being read also lead to access violations }
  11919. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  11920. (
  11921. { Check that we're not modifying a register that appears in the reference }
  11922. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  11923. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  11924. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  11925. )
  11926. )
  11927. )
  11928. )
  11929. )
  11930. )
  11931. );
  11932. end;
  11933. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  11934. begin
  11935. { Update integer registers, ignoring deallocations }
  11936. repeat
  11937. while assigned(p) and
  11938. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  11939. (p.typ = ait_label) or
  11940. ((p.typ = ait_marker) and
  11941. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  11942. p := tai(p.next);
  11943. while assigned(p) and
  11944. (p.typ=ait_RegAlloc) Do
  11945. begin
  11946. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  11947. begin
  11948. case tai_regalloc(p).ratype of
  11949. ra_alloc :
  11950. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  11951. else
  11952. ;
  11953. end;
  11954. end;
  11955. p := tai(p.next);
  11956. end;
  11957. until not(assigned(p)) or
  11958. (not(p.typ in SkipInstr) and
  11959. not((p.typ = ait_label) and
  11960. labelCanBeSkipped(tai_label(p))));
  11961. end;
  11962. {$ifndef 8086}
  11963. function TCMOVTracking.InitialiseBlock(BlockStart, OneBeforeBlock: tai; out BlockStop: tai; out EndJump: tai): Boolean;
  11964. begin
  11965. Result := False;
  11966. EndJump := nil;
  11967. BlockStop := nil;
  11968. while (BlockStart <> fOptimizer.BlockEnd) and
  11969. { stop on labels }
  11970. (BlockStart.typ <> ait_label) do
  11971. begin
  11972. { Keep track of all integer registers that are used }
  11973. fOptimizer.UpdateIntRegsNoDealloc(RegisterTracking, tai(OneBeforeBlock.Next));
  11974. if BlockStart.typ = ait_instruction then
  11975. begin
  11976. if (taicpu(BlockStart).opcode = A_JMP) then
  11977. begin
  11978. if not IsJumpToLabel(taicpu(BlockStart)) or
  11979. (JumpTargetOp(taicpu(BlockStart))^.ref^.index <> NR_NO) then
  11980. Exit;
  11981. EndJump := BlockStart;
  11982. Break;
  11983. end
  11984. { Check to see if we have a valid MOV instruction instead }
  11985. else if (taicpu(BlockStart).opcode <> A_MOV) or
  11986. (taicpu(BlockStart).oper[1]^.typ <> top_reg) or
  11987. not (taicpu(BlockStart).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11988. begin
  11989. Exit;
  11990. end
  11991. else
  11992. { This will be a valid MOV }
  11993. fAllocationRange := BlockStart;
  11994. end;
  11995. OneBeforeBlock := BlockStart;
  11996. fOptimizer.GetNextInstruction(BlockStart, BlockStart);
  11997. end;
  11998. if (BlockStart = fOptimizer.BlockEnd) then
  11999. Exit;
  12000. BlockStop := BlockStart;
  12001. Result := True;
  12002. end;
  12003. function TCMOVTracking.AnalyseMOVBlock(BlockStart, BlockStop, SearchStart: tai): LongInt;
  12004. var
  12005. hp1: tai;
  12006. RefModified: Boolean;
  12007. begin
  12008. Result := 0;
  12009. hp1 := BlockStart;
  12010. RefModified := False; { As long as the condition is inverted, this can be reset }
  12011. while assigned(hp1) and
  12012. (hp1 <> BlockStop) do
  12013. begin
  12014. case hp1.typ of
  12015. ait_instruction:
  12016. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  12017. begin
  12018. if fOptimizer.CanBeCMOV(hp1, fCondition, RefModified) then
  12019. begin
  12020. Inc(Result);
  12021. if { Make sure the sizes match too so we're reading and writing the same number of bytes }
  12022. Assigned(fCondition) and
  12023. { Will have 2 operands }
  12024. (
  12025. (
  12026. (taicpu(fCondition).oper[0]^.typ = top_ref) and
  12027. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[0]^.ref^)
  12028. ) or
  12029. (
  12030. (taicpu(fCondition).oper[1]^.typ = top_ref) and
  12031. fOptimizer.RegInRef(taicpu(hp1).oper[1]^.reg, taicpu(fCondition).oper[1]^.ref^)
  12032. )
  12033. ) then
  12034. { It is no longer safe to use the reference in the condition.
  12035. this prevents problems such as:
  12036. mov (%reg),%reg
  12037. mov (%reg),...
  12038. When the comparison is cmp (%reg),0 and guarding against a null pointer deallocation
  12039. (fixes #40165)
  12040. Note: "mov (%reg1),%reg2; mov (%reg2),..." won't be optimised this way since
  12041. at least one of (%reg1) and (%reg2) won't be in the condition and is hence unsafe.
  12042. }
  12043. RefModified := True;
  12044. end
  12045. else if not (cs_opt_size in current_settings.optimizerswitches) and
  12046. { CMOV with constants grows the code size }
  12047. TryCMOVConst(hp1, SearchStart, BlockStop, Result) then
  12048. begin
  12049. { Register was reserved by TryCMOVConst and
  12050. stored on ConstRegs }
  12051. end
  12052. else
  12053. begin
  12054. Result := -1;
  12055. Exit;
  12056. end;
  12057. end
  12058. else
  12059. begin
  12060. Result := -1;
  12061. Exit;
  12062. end;
  12063. else
  12064. { Most likely an align };
  12065. end;
  12066. fOptimizer.GetNextInstruction(hp1, hp1);
  12067. end;
  12068. end;
  12069. constructor TCMOVTracking.Init(Optimizer: TX86AsmOptimizer; var p_initialjump, p_initialmov: tai; var AFirstLabel: TAsmLabel);
  12070. { For the tsBranching type, increase the weighting score to account for the new conditional jump
  12071. (this is done as a separate stage because the double types are extensions of the branching type,
  12072. but we can't discount the conditional jump until the last step) }
  12073. procedure EvaluateBranchingType;
  12074. begin
  12075. Inc(CMOVScore);
  12076. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) then
  12077. { Too many instructions to be worthwhile }
  12078. fState := tsInvalid;
  12079. end;
  12080. var
  12081. hp1: tai;
  12082. Count: Integer;
  12083. begin
  12084. { Table of valid CMOV block types
  12085. Block type 2nd Jump Mid-label 2nd MOVs 3rd Jump End-label
  12086. ---------- --------- --------- --------- --------- ---------
  12087. tsSimple X Yes X X X
  12088. tsDetour = 1st X X X X
  12089. tsBranching <> Mid Yes X X X
  12090. tsDouble End-label Yes * Yes X Yes
  12091. tsDoubleBranchSame <> Mid Yes * Yes = 2nd X
  12092. tsDoubleBranchDifferent <> Mid Yes * Yes <> 2nd X
  12093. tsDoubleSecondBranching End-label Yes * Yes <> 2nd Yes
  12094. * Only one reference allowed
  12095. }
  12096. hp1 := nil; { To prevent compiler warnings }
  12097. Optimizer.CopyUsedRegs(RegisterTracking);
  12098. fOptimizer := Optimizer;
  12099. fLabel := AFirstLabel;
  12100. CMOVScore := 0;
  12101. ConstCount := 0;
  12102. { Initialise RegWrites, ConstRegs, ConstVals, ConstSizes, ConstWriteSizes and ConstMovs }
  12103. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  12104. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  12105. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  12106. FillChar(ConstSizes[0], MAX_CMOV_REGISTERS * SizeOf(TSubRegister), 0);
  12107. FillChar(ConstWriteSizes[0], first_int_imreg * SizeOf(TOpSize), 0);
  12108. FillChar(ConstMovs[0], MAX_CMOV_REGISTERS * SizeOf(taicpu), 0);
  12109. fInsertionPoint := p_initialjump;
  12110. fCondition := nil;
  12111. fInitialJump := p_initialjump;
  12112. fFirstMovBlock := p_initialmov;
  12113. fFirstMovBlockStop := nil;
  12114. fSecondJump := nil;
  12115. fSecondMovBlock := nil;
  12116. fSecondMovBlockStop := nil;
  12117. fMidLabel := nil;
  12118. fSecondJump := nil;
  12119. fSecondMovBlock := nil;
  12120. fEndLabel := nil;
  12121. fAllocationRange := nil;
  12122. { Assume it all goes horribly wrong! }
  12123. fState := tsInvalid;
  12124. { Look backwards at the comparisons to get an accurate picture of register usage and a better position for any MOV const,reg insertions }
  12125. if Optimizer.GetLastInstruction(p_initialjump, fCondition) and
  12126. MatchInstruction(fCondition, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  12127. begin
  12128. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  12129. for Count := 0 to 1 do
  12130. with taicpu(fCondition).oper[Count]^ do
  12131. case typ of
  12132. top_reg:
  12133. if getregtype(reg) = R_INTREGISTER then
  12134. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12135. top_ref:
  12136. begin
  12137. if
  12138. {$ifdef x86_64}
  12139. (ref^.base <> NR_RIP) and
  12140. {$endif x86_64}
  12141. (ref^.base <> NR_NO) then
  12142. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12143. if (ref^.index <> NR_NO) then
  12144. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12145. end
  12146. else
  12147. ;
  12148. end;
  12149. { When inserting instructions before hp_prev, try to insert them
  12150. before the allocation of the FLAGS register }
  12151. if not SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(fCondition.Previous)), fInsertionPoint) or
  12152. (tai_regalloc(fInsertionPoint).ratype = ra_dealloc) then
  12153. { If not found, set it equal to the condition so it's something sensible }
  12154. fInsertionPoint := fCondition;
  12155. { When dealing with a comparison against zero, take note of the
  12156. instruction before it to see if we can move instructions further
  12157. back in order to benefit PostPeepholeOptTestOr.
  12158. }
  12159. if (
  12160. (
  12161. (taicpu(fCondition).opcode = A_CMP) and
  12162. MatchOperand(taicpu(fCondition).oper[0]^, 0)
  12163. ) or
  12164. (
  12165. (taicpu(fCondition).opcode = A_TEST) and
  12166. (
  12167. Optimizer.OpsEqual(taicpu(fCondition).oper[0]^, taicpu(fCondition).oper[1]^) or
  12168. MatchOperand(taicpu(fCondition).oper[0]^, -1)
  12169. )
  12170. )
  12171. ) and
  12172. Optimizer.GetLastInstruction(fCondition, hp1) then
  12173. begin
  12174. { These instructions set the zero flag if the result is zero }
  12175. if MatchInstruction(hp1, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  12176. begin
  12177. fInsertionPoint := hp1;
  12178. { Also mark all the registers in this previous instruction
  12179. as 'in use', even if they've just been deallocated }
  12180. for Count := 0 to 1 do
  12181. with taicpu(hp1).oper[Count]^ do
  12182. case typ of
  12183. top_reg:
  12184. if getregtype(reg) = R_INTREGISTER then
  12185. Optimizer.IncludeRegInUsedRegs(reg, RegisterTracking);
  12186. top_ref:
  12187. begin
  12188. if
  12189. {$ifdef x86_64}
  12190. (ref^.base <> NR_RIP) and
  12191. {$endif x86_64}
  12192. (ref^.base <> NR_NO) then
  12193. Optimizer.IncludeRegInUsedRegs(ref^.base, RegisterTracking);
  12194. if (ref^.index <> NR_NO) then
  12195. Optimizer.IncludeRegInUsedRegs(ref^.index, RegisterTracking);
  12196. end
  12197. else
  12198. ;
  12199. end;
  12200. end;
  12201. end;
  12202. end
  12203. else
  12204. fCondition := nil;
  12205. { When inserting instructions, try to insert them before the allocation of the FLAGS register }
  12206. if SetAndTest(Optimizer.FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p_initialjump.Previous)), hp1) and
  12207. (tai_regalloc(hp1).ratype <> ra_dealloc) then
  12208. { If not found, set it equal to p so it's something sensible }
  12209. fInsertionPoint := hp1;
  12210. hp1 := p_initialmov;
  12211. if not InitialiseBlock(p_initialmov, p_initialjump, fFirstMovBlockStop, fSecondJump) then
  12212. Exit;
  12213. hp1 := fFirstMovBlockStop; { Will either be on a label or a jump }
  12214. if (hp1.typ <> ait_label) then { should be on a jump }
  12215. begin
  12216. if not Optimizer.GetNextInstruction(hp1, fMidLabel) or not (fMidLabel.typ = ait_label) then
  12217. { Need a label afterwards }
  12218. Exit;
  12219. end
  12220. else
  12221. fMidLabel := hp1;
  12222. if tai_label(fMidLabel).labsym <> AFirstLabel then
  12223. { Not the correct label }
  12224. fMidLabel := nil;
  12225. if not Assigned(fSecondJump) and not Assigned(fMidLabel) then
  12226. { If there's neither a 2nd jump nor correct label, then it's invalid
  12227. (see above table) }
  12228. Exit;
  12229. { Analyse the first block of MOVs more closely }
  12230. CMOVScore := AnalyseMOVBlock(fFirstMovBlock, fFirstMovBlockStop, fInsertionPoint);
  12231. if Assigned(fSecondJump) then
  12232. begin
  12233. if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = AFirstLabel) then
  12234. begin
  12235. fState := tsDetour
  12236. end
  12237. else
  12238. begin
  12239. { Need the correct mid-label for this one }
  12240. if not Assigned(fMidLabel) then
  12241. Exit;
  12242. fState := tsBranching;
  12243. end;
  12244. end
  12245. else
  12246. { No jump. but mid-label is present }
  12247. fState := tsSimple;
  12248. if (CMOVScore > MAX_CMOV_INSTRUCTIONS) or (CMOVScore <= 0) then
  12249. begin
  12250. { Invalid or too many instructions to be worthwhile }
  12251. fState := tsInvalid;
  12252. Exit;
  12253. end;
  12254. { check further for
  12255. jCC xxx
  12256. <several movs 1>
  12257. jmp yyy
  12258. xxx:
  12259. <several movs 2>
  12260. yyy:
  12261. etc.
  12262. }
  12263. if (fState = tsBranching) and
  12264. { Estimate for required savings for extra jump }
  12265. (CMOVScore <= MAX_CMOV_INSTRUCTIONS - 1) and
  12266. { Only one reference is allowed for double blocks }
  12267. (AFirstLabel.getrefs = 1) then
  12268. begin
  12269. Optimizer.GetNextInstruction(fMidLabel, hp1);
  12270. fSecondMovBlock := hp1;
  12271. if not InitialiseBlock(fSecondMovBlock, fMidLabel, fSecondMovBlockStop, fThirdJump) then
  12272. begin
  12273. EvaluateBranchingType;
  12274. Exit;
  12275. end;
  12276. hp1 := fSecondMovBlockStop; { Will either be on a label or a jump }
  12277. if (hp1.typ <> ait_label) then { should be on a jump }
  12278. begin
  12279. if not Optimizer.GetNextInstruction(hp1, fEndLabel) or not (fEndLabel.typ = ait_label) then
  12280. begin
  12281. { Need a label afterwards }
  12282. EvaluateBranchingType;
  12283. Exit;
  12284. end;
  12285. end
  12286. else
  12287. fEndLabel := hp1;
  12288. if tai_label(fEndLabel).labsym <> JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol then
  12289. { Second jump doesn't go to the end }
  12290. fEndLabel := nil;
  12291. if not Assigned(fThirdJump) and not Assigned(fEndLabel) then
  12292. begin
  12293. { If there's neither a 3rd jump nor correct end label, then it's
  12294. not a invalid double block, but is a valid single branching
  12295. block (see above table) }
  12296. EvaluateBranchingType;
  12297. Exit;
  12298. end;
  12299. Count := AnalyseMOVBlock(fSecondMovBlock, fSecondMovBlockStop, fMidLabel);
  12300. if (Count > MAX_CMOV_INSTRUCTIONS) or (Count <= 0) then
  12301. { Invalid or too many instructions to be worthwhile }
  12302. Exit;
  12303. Inc(CMOVScore, Count);
  12304. if Assigned(fThirdJump) then
  12305. begin
  12306. if not Assigned(fSecondJump) then
  12307. fState := tsDoubleSecondBranching
  12308. else if (JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol = JumpTargetOp(taicpu(fThirdJump))^.ref^.symbol) then
  12309. fState := tsDoubleBranchSame
  12310. else
  12311. fState := tsDoubleBranchDifferent;
  12312. end
  12313. else
  12314. fState := tsDouble;
  12315. end;
  12316. if fState = tsBranching then
  12317. EvaluateBranchingType;
  12318. end;
  12319. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  12320. new register to store the constant }
  12321. function TCMOVTracking.TryCMOVConst(p, start, stop: tai; var Count: LongInt): Boolean;
  12322. var
  12323. RegSize: TSubRegister;
  12324. CurrentVal: TCGInt;
  12325. ANewReg: TRegister;
  12326. X: ShortInt;
  12327. begin
  12328. Result := False;
  12329. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12330. Exit;
  12331. if ConstCount >= MAX_CMOV_REGISTERS then
  12332. { Arrays are full }
  12333. Exit;
  12334. { Remember that CMOV can't encode 8-bit registers }
  12335. case taicpu(p).opsize of
  12336. S_W:
  12337. RegSize := R_SUBW;
  12338. S_L:
  12339. RegSize := R_SUBD;
  12340. {$ifdef x86_64}
  12341. S_Q:
  12342. RegSize := R_SUBQ;
  12343. {$endif x86_64}
  12344. else
  12345. InternalError(2021100401);
  12346. end;
  12347. { See if the value has already been reserved for another CMOV instruction }
  12348. CurrentVal := taicpu(p).oper[0]^.val;
  12349. for X := 0 to ConstCount - 1 do
  12350. if ConstVals[X] = CurrentVal then
  12351. begin
  12352. ConstRegs[ConstCount] := ConstRegs[X];
  12353. ConstSizes[ConstCount] := RegSize;
  12354. ConstVals[ConstCount] := CurrentVal;
  12355. Inc(ConstCount);
  12356. Inc(Count);
  12357. Result := True;
  12358. Exit;
  12359. end;
  12360. ANewReg := fOptimizer.GetIntRegisterBetween(R_SUBWHOLE, RegisterTracking, start, stop, True);
  12361. if ANewReg = NR_NO then
  12362. { No free registers }
  12363. Exit;
  12364. { Reserve the register so subsequent TryCMOVConst calls don't all end
  12365. up vying for the same register }
  12366. fOptimizer.IncludeRegInUsedRegs(ANewReg, RegisterTracking);
  12367. ConstRegs[ConstCount] := ANewReg;
  12368. ConstSizes[ConstCount] := RegSize;
  12369. ConstVals[ConstCount] := CurrentVal;
  12370. Inc(ConstCount);
  12371. Inc(Count);
  12372. Result := True;
  12373. end;
  12374. destructor TCMOVTracking.Done;
  12375. begin
  12376. TAOptObj.ReleaseUsedRegs(RegisterTracking);
  12377. end;
  12378. procedure TCMOVTracking.Process(out new_p: tai);
  12379. var
  12380. Count, Writes: LongInt;
  12381. RegMatch: Boolean;
  12382. hp1, hp_new: tai;
  12383. inverted_condition, condition: TAsmCond;
  12384. begin
  12385. if (fState in [tsInvalid, tsProcessed]) then
  12386. InternalError(2023110701);
  12387. { Repurpose RegisterTracking to mark registers that we've defined }
  12388. RegisterTracking[R_INTREGISTER].Clear;
  12389. Count := 0;
  12390. Writes := 0;
  12391. condition := taicpu(fInitialJump).condition;
  12392. inverted_condition := inverse_cond(condition);
  12393. { Exclude tsDoubleBranchDifferent from this check, as the second block
  12394. doesn't get CMOVs in this case }
  12395. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleSecondBranching]) then
  12396. begin
  12397. { Include the jump in the flag tracking }
  12398. if Assigned(fThirdJump) then
  12399. begin
  12400. if (fState = tsDoubleBranchSame) then
  12401. begin
  12402. { Will be an unconditional jump, so track to the instruction before it }
  12403. if not fOptimizer.GetLastInstruction(fThirdJump, hp1) then
  12404. InternalError(2023110710);
  12405. end
  12406. else
  12407. hp1 := fThirdJump;
  12408. end
  12409. else
  12410. hp1 := fSecondMovBlockStop;
  12411. end
  12412. else
  12413. begin
  12414. { Include a conditional jump in the flag tracking }
  12415. if Assigned(fSecondJump) then
  12416. begin
  12417. if (fState = tsDetour) then
  12418. begin
  12419. { Will be an unconditional jump, so track to the instruction before it }
  12420. if not fOptimizer.GetLastInstruction(fSecondJump, hp1) then
  12421. InternalError(2023110711);
  12422. end
  12423. else
  12424. hp1 := fSecondJump;
  12425. end
  12426. else
  12427. hp1 := fFirstMovBlockStop;
  12428. end;
  12429. fOptimizer.AllocRegBetween(NR_DEFAULTFLAGS, fInitialJump, hp1, fOptimizer.UsedRegs);
  12430. { Process the second set of MOVs first, because if a destination
  12431. register is shared between the first and second MOV sets, it is more
  12432. efficient to turn the first one into a MOV instruction and place it
  12433. before the CMP if possible, but we won't know which registers are
  12434. shared until we've processed at least one list, so we might as well
  12435. make it the second one since that won't be modified again. }
  12436. if (fState in [tsDouble, tsDoubleBranchSame, tsDoubleBranchDifferent, tsDoubleSecondBranching]) then
  12437. begin
  12438. hp1 := fSecondMovBlock;
  12439. repeat
  12440. if not Assigned(hp1) then
  12441. InternalError(2018062902);
  12442. if (hp1.typ = ait_instruction) then
  12443. begin
  12444. { Extra safeguard }
  12445. if (taicpu(hp1).opcode <> A_MOV) then
  12446. InternalError(2018062903);
  12447. { Note: tsDoubleBranchDifferent is essentially identical to
  12448. tsBranching and the 2nd block is best left largely
  12449. untouched, but we need to evaluate which registers the MOVs
  12450. write to in order to track what would be complementary CMOV
  12451. pairs that can be further optimised. [Kit] }
  12452. if fState <> tsDoubleBranchDifferent then
  12453. begin
  12454. if taicpu(hp1).oper[0]^.typ = top_const then
  12455. begin
  12456. RegMatch := False;
  12457. for Count := 0 to ConstCount - 1 do
  12458. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12459. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12460. begin
  12461. RegMatch := True;
  12462. { If it's in RegisterTracking, then this register
  12463. is being used more than once and hence has
  12464. already had its value defined (it gets added to
  12465. UsedRegs through AllocRegBetween below) }
  12466. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12467. begin
  12468. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12469. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12470. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12471. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12472. ConstMovs[Count] := hp_new;
  12473. end
  12474. else
  12475. { We just need an instruction between hp_prev and hp1
  12476. where we know the register is marked as in use }
  12477. hp_new := fSecondMovBlock;
  12478. { Keep track of largest write for this register so it can be optimised later }
  12479. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12480. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12481. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12482. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12483. Break;
  12484. end;
  12485. if not RegMatch then
  12486. InternalError(2021100411);
  12487. end;
  12488. taicpu(hp1).opcode := A_CMOVcc;
  12489. taicpu(hp1).condition := condition;
  12490. end;
  12491. { Store these writes to search for duplicates later on }
  12492. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12493. Inc(Writes);
  12494. end;
  12495. fOptimizer.GetNextInstruction(hp1, hp1);
  12496. until (hp1 = fSecondMovBlockStop);
  12497. end;
  12498. { Now do the first set of MOVs }
  12499. hp1 := fFirstMovBlock;
  12500. repeat
  12501. if not Assigned(hp1) then
  12502. InternalError(2018062904);
  12503. if (hp1.typ = ait_instruction) then
  12504. begin
  12505. RegMatch := False;
  12506. { Extra safeguard }
  12507. if (taicpu(hp1).opcode <> A_MOV) then
  12508. InternalError(2018062905);
  12509. { Search through the RegWrites list to see if there are any
  12510. opposing CMOV pairs that write to the same register }
  12511. for Count := 0 to Writes - 1 do
  12512. if (RegWrites[Count] = taicpu(hp1).oper[1]^.reg) then
  12513. begin
  12514. { We have a match. Keep this as a MOV }
  12515. { Move ahead in preparation }
  12516. fOptimizer.GetNextInstruction(hp1, hp1);
  12517. RegMatch := True;
  12518. Break;
  12519. end;
  12520. if RegMatch then
  12521. Continue;
  12522. if taicpu(hp1).oper[0]^.typ = top_const then
  12523. begin
  12524. for Count := 0 to ConstCount - 1 do
  12525. if (ConstVals[Count] = taicpu(hp1).oper[0]^.val) and
  12526. (getsubreg(taicpu(hp1).oper[1]^.reg) = ConstSizes[Count]) then
  12527. begin
  12528. RegMatch := True;
  12529. { If it's in RegisterTracking, then this register is
  12530. being used more than once and hence has already had
  12531. its value defined (it gets added to UsedRegs through
  12532. AllocRegBetween below) }
  12533. if not RegisterTracking[R_INTREGISTER].IsUsed(ConstRegs[Count]) then
  12534. begin
  12535. hp_new := taicpu.op_const_reg(A_MOV, subreg2opsize(R_SUBWHOLE), taicpu(hp1).oper[0]^.val, ConstRegs[Count]);
  12536. taicpu(hp_new).fileinfo := taicpu(fInitialJump).fileinfo;
  12537. fOptimizer.asml.InsertBefore(hp_new, fInsertionPoint);
  12538. fOptimizer.IncludeRegInUsedRegs(ConstRegs[Count], RegisterTracking);
  12539. ConstMovs[Count] := hp_new;
  12540. end
  12541. else
  12542. { We just need an instruction between hp_prev and hp1
  12543. where we know the register is marked as in use }
  12544. hp_new := fFirstMovBlock;
  12545. { Keep track of largest write for this register so it can be optimised later }
  12546. if (getsubreg(taicpu(hp1).oper[1]^.reg) > ConstWriteSizes[getsupreg(ConstRegs[Count])]) then
  12547. ConstWriteSizes[getsupreg(ConstRegs[Count])] := getsubreg(taicpu(hp1).oper[1]^.reg);
  12548. fOptimizer.AllocRegBetween(ConstRegs[Count], hp_new, hp1, fOptimizer.UsedRegs);
  12549. taicpu(hp1).loadreg(0, newreg(R_INTREGISTER, getsupreg(ConstRegs[Count]), ConstSizes[Count]));
  12550. Break;
  12551. end;
  12552. if not RegMatch then
  12553. InternalError(2021100412);
  12554. end;
  12555. taicpu(hp1).opcode := A_CMOVcc;
  12556. taicpu(hp1).condition := inverted_condition;
  12557. if (fState = tsDoubleBranchDifferent) then
  12558. begin
  12559. { Store these writes to search for duplicates later on }
  12560. RegWrites[Writes] := taicpu(hp1).oper[1]^.reg;
  12561. Inc(Writes);
  12562. end;
  12563. end;
  12564. fOptimizer.GetNextInstruction(hp1, hp1);
  12565. until (hp1 = fFirstMovBlockStop);
  12566. { Update initialisation MOVs to the smallest possible size }
  12567. for Count := 0 to ConstCount - 1 do
  12568. if Assigned(ConstMovs[Count]) then
  12569. begin
  12570. taicpu(ConstMovs[Count]).opsize := subreg2opsize(ConstWriteSizes[Word(ConstRegs[Count])]);
  12571. setsubreg(taicpu(ConstMovs[Count]).oper[1]^.reg, ConstWriteSizes[Word(ConstRegs[Count])]);
  12572. end;
  12573. case fState of
  12574. tsSimple:
  12575. begin
  12576. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Simple type)', fInitialJump);
  12577. { No branch to delete }
  12578. end;
  12579. tsDetour:
  12580. begin
  12581. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Detour type)', fInitialJump);
  12582. { Preserve jump }
  12583. end;
  12584. tsBranching, tsDoubleBranchDifferent:
  12585. begin
  12586. if (fState = tsBranching) then
  12587. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Branching type)', fInitialJump)
  12588. else
  12589. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (different) type)', fInitialJump);
  12590. taicpu(fSecondJump).opcode := A_JCC;
  12591. taicpu(fSecondJump).condition := inverted_condition;
  12592. end;
  12593. tsDouble, tsDoubleBranchSame:
  12594. begin
  12595. if (fState = tsDouble) then
  12596. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double type)', fInitialJump)
  12597. else
  12598. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double branching (same) type)', fInitialJump);
  12599. { Delete second jump }
  12600. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12601. fOptimizer.RemoveInstruction(fSecondJump);
  12602. end;
  12603. tsDoubleSecondBranching:
  12604. begin
  12605. fOptimizer.DebugMsg(SPeepholeOptimization + 'CMOV Block (Double, second branching type)', fInitialJump);
  12606. { Delete second jump, preserve third jump as conditional }
  12607. JumpTargetOp(taicpu(fSecondJump))^.ref^.symbol.decrefs;
  12608. fOptimizer.RemoveInstruction(fSecondJump);
  12609. taicpu(fThirdJump).opcode := A_JCC;
  12610. taicpu(fThirdJump).condition := condition;
  12611. end;
  12612. else
  12613. InternalError(2023110720);
  12614. end;
  12615. { Now we can safely decrement the reference count }
  12616. tasmlabel(fLabel).decrefs;
  12617. fOptimizer.UpdateUsedRegs(tai(fInitialJump.next));
  12618. { Remove the original jump }
  12619. fOptimizer.RemoveInstruction(fInitialJump); { Note, the choice to not use RemoveCurrentp is deliberate }
  12620. new_p := fFirstMovBlock; { Appears immediately after the initial jump }
  12621. fState := tsProcessed;
  12622. end;
  12623. {$endif 8086}
  12624. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  12625. var
  12626. hp1,hp2: tai;
  12627. carryadd_opcode : TAsmOp;
  12628. symbol: TAsmSymbol;
  12629. increg, tmpreg: TRegister;
  12630. {$ifndef i8086}
  12631. CMOVTracking: PCMOVTracking;
  12632. hp3,hp4,hp5: tai;
  12633. {$endif i8086}
  12634. TempBool: Boolean;
  12635. begin
  12636. if (aoc_DoPass2JccOpts in OptsToCheck) and
  12637. DoJumpOptimizations(p, TempBool) then
  12638. Exit(True);
  12639. result:=false;
  12640. if GetNextInstruction(p,hp1) then
  12641. begin
  12642. if (hp1.typ=ait_label) then
  12643. begin
  12644. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  12645. Exit;
  12646. end
  12647. else if (hp1.typ<>ait_instruction) then
  12648. Exit;
  12649. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  12650. if (
  12651. (
  12652. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  12653. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  12654. (Taicpu(hp1).oper[0]^.val=1)
  12655. ) or
  12656. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  12657. ) and
  12658. GetNextInstruction(hp1,hp2) and
  12659. FindLabel(TAsmLabel(symbol), hp2) then
  12660. { jb @@1 cmc
  12661. inc/dec operand --> adc/sbb operand,0
  12662. @@1:
  12663. ... and ...
  12664. jnb @@1
  12665. inc/dec operand --> adc/sbb operand,0
  12666. @@1: }
  12667. begin
  12668. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  12669. begin
  12670. case taicpu(hp1).opcode of
  12671. A_INC,
  12672. A_ADD:
  12673. carryadd_opcode:=A_ADC;
  12674. A_DEC,
  12675. A_SUB:
  12676. carryadd_opcode:=A_SBB;
  12677. else
  12678. InternalError(2021011001);
  12679. end;
  12680. Taicpu(p).clearop(0);
  12681. Taicpu(p).ops:=0;
  12682. Taicpu(p).is_jmp:=false;
  12683. Taicpu(p).opcode:=A_CMC;
  12684. Taicpu(p).condition:=C_NONE;
  12685. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  12686. Taicpu(hp1).ops:=2;
  12687. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12688. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12689. else
  12690. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12691. Taicpu(hp1).loadconst(0,0);
  12692. Taicpu(hp1).opcode:=carryadd_opcode;
  12693. result:=true;
  12694. exit;
  12695. end
  12696. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  12697. begin
  12698. case taicpu(hp1).opcode of
  12699. A_INC,
  12700. A_ADD:
  12701. carryadd_opcode:=A_ADC;
  12702. A_DEC,
  12703. A_SUB:
  12704. carryadd_opcode:=A_SBB;
  12705. else
  12706. InternalError(2021011002);
  12707. end;
  12708. Taicpu(hp1).ops:=2;
  12709. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  12710. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  12711. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  12712. else
  12713. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  12714. Taicpu(hp1).loadconst(0,0);
  12715. Taicpu(hp1).opcode:=carryadd_opcode;
  12716. RemoveCurrentP(p, hp1);
  12717. result:=true;
  12718. exit;
  12719. end
  12720. {
  12721. jcc @@1 setcc tmpreg
  12722. inc/dec/add/sub operand -> (movzx tmpreg)
  12723. @@1: add/sub tmpreg,operand
  12724. While this increases code size slightly, it makes the code much faster if the
  12725. jump is unpredictable
  12726. }
  12727. else if not(cs_opt_size in current_settings.optimizerswitches) then
  12728. begin
  12729. { search for an available register which is volatile }
  12730. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  12731. if increg <> NR_NO then
  12732. begin
  12733. { We don't need to check if tmpreg is in hp1 or not, because
  12734. it will be marked as in use at p (if not, this is
  12735. indictive of a compiler bug). }
  12736. TAsmLabel(symbol).decrefs;
  12737. Taicpu(p).clearop(0);
  12738. Taicpu(p).ops:=1;
  12739. Taicpu(p).is_jmp:=false;
  12740. Taicpu(p).opcode:=A_SETcc;
  12741. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  12742. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  12743. Taicpu(p).loadreg(0,increg);
  12744. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  12745. begin
  12746. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  12747. R_SUBW:
  12748. begin
  12749. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  12750. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  12751. end;
  12752. R_SUBD:
  12753. begin
  12754. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12755. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12756. end;
  12757. {$ifdef x86_64}
  12758. R_SUBQ:
  12759. begin
  12760. { MOVZX doesn't have a 64-bit variant, because
  12761. the 32-bit version implicitly zeroes the
  12762. upper 32-bits of the destination register }
  12763. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  12764. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  12765. setsubreg(tmpreg, R_SUBQ);
  12766. end;
  12767. {$endif x86_64}
  12768. else
  12769. Internalerror(2020030601);
  12770. end;
  12771. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  12772. asml.InsertAfter(hp2,p);
  12773. end
  12774. else
  12775. tmpreg := increg;
  12776. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  12777. begin
  12778. Taicpu(hp1).ops:=2;
  12779. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  12780. end;
  12781. Taicpu(hp1).loadreg(0,tmpreg);
  12782. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  12783. Result := True;
  12784. { p is no longer a Jcc instruction, so exit }
  12785. Exit;
  12786. end;
  12787. end;
  12788. end;
  12789. { Detect the following:
  12790. jmp<cond> @Lbl1
  12791. jmp @Lbl2
  12792. ...
  12793. @Lbl1:
  12794. ret
  12795. Change to:
  12796. jmp<inv_cond> @Lbl2
  12797. ret
  12798. }
  12799. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12800. begin
  12801. hp2:=getlabelwithsym(TAsmLabel(symbol));
  12802. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  12803. MatchInstruction(hp2,A_RET,[S_NO]) then
  12804. begin
  12805. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  12806. { Change label address to that of the unconditional jump }
  12807. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  12808. TAsmLabel(symbol).DecRefs;
  12809. taicpu(hp1).opcode := A_RET;
  12810. taicpu(hp1).is_jmp := false;
  12811. taicpu(hp1).ops := taicpu(hp2).ops;
  12812. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  12813. case taicpu(hp2).ops of
  12814. 0:
  12815. taicpu(hp1).clearop(0);
  12816. 1:
  12817. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  12818. else
  12819. internalerror(2016041302);
  12820. end;
  12821. end;
  12822. {$ifndef i8086}
  12823. end
  12824. {
  12825. convert
  12826. j<c> .L1
  12827. mov 1,reg
  12828. jmp .L2
  12829. .L1
  12830. mov 0,reg
  12831. .L2
  12832. into
  12833. mov 0,reg
  12834. set<not(c)> reg
  12835. take care of alignment and that the mov 0,reg is not converted into a xor as this
  12836. would destroy the flag contents
  12837. }
  12838. else if MatchInstruction(hp1,A_MOV,[]) and
  12839. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12840. {$ifdef i386}
  12841. (
  12842. { Under i386, ESI, EDI, EBP and ESP
  12843. don't have an 8-bit representation }
  12844. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  12845. ) and
  12846. {$endif i386}
  12847. (taicpu(hp1).oper[0]^.val=1) and
  12848. GetNextInstruction(hp1,hp2) and
  12849. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  12850. GetNextInstruction(hp2,hp3) and
  12851. (hp3.typ=ait_label) and
  12852. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  12853. (tai_label(hp3).labsym.getrefs=1) and
  12854. GetNextInstruction(hp3,hp4) and
  12855. MatchInstruction(hp4,A_MOV,[]) and
  12856. MatchOpType(taicpu(hp4),top_const,top_reg) and
  12857. (taicpu(hp4).oper[0]^.val=0) and
  12858. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  12859. GetNextInstruction(hp4,hp5) and
  12860. (hp5.typ=ait_label) and
  12861. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  12862. (tai_label(hp5).labsym.getrefs=1) then
  12863. begin
  12864. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  12865. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  12866. { remove last label }
  12867. RemoveInstruction(hp5);
  12868. { remove second label }
  12869. RemoveInstruction(hp3);
  12870. { remove jmp }
  12871. RemoveInstruction(hp2);
  12872. if taicpu(hp1).opsize=S_B then
  12873. RemoveInstruction(hp1)
  12874. else
  12875. taicpu(hp1).loadconst(0,0);
  12876. taicpu(hp4).opcode:=A_SETcc;
  12877. taicpu(hp4).opsize:=S_B;
  12878. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  12879. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  12880. taicpu(hp4).opercnt:=1;
  12881. taicpu(hp4).ops:=1;
  12882. taicpu(hp4).freeop(1);
  12883. RemoveCurrentP(p);
  12884. Result:=true;
  12885. exit;
  12886. end
  12887. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  12888. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  12889. begin
  12890. { check for
  12891. jCC xxx
  12892. <several movs>
  12893. xxx:
  12894. Also spot:
  12895. Jcc xxx
  12896. <several movs>
  12897. jmp xxx
  12898. Change to:
  12899. <several cmovs with inverted condition>
  12900. jmp xxx (only for the 2nd case)
  12901. }
  12902. CMOVTracking := New(PCMOVTracking, Init(Self, p, hp1, TAsmLabel(symbol)));
  12903. if CMOVTracking^.State <> tsInvalid then
  12904. begin
  12905. CMovTracking^.Process(p);
  12906. Result := True;
  12907. end;
  12908. CMOVTracking^.Done;
  12909. {$endif i8086}
  12910. end;
  12911. end;
  12912. end;
  12913. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  12914. var
  12915. hp1,hp2,hp3: tai;
  12916. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  12917. NewSize: TOpSize;
  12918. NewRegSize: TSubRegister;
  12919. Limit: TCgInt;
  12920. SwapOper: POper;
  12921. begin
  12922. result:=false;
  12923. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  12924. GetNextInstruction(p,hp1) and
  12925. (hp1.typ = ait_instruction);
  12926. if reg_and_hp1_is_instr and
  12927. (
  12928. (taicpu(hp1).opcode <> A_LEA) or
  12929. { If the LEA instruction can be converted into an arithmetic instruction,
  12930. it may be possible to then fold it. }
  12931. (
  12932. { If the flags register is in use, don't change the instruction
  12933. to an ADD otherwise this will scramble the flags. [Kit] }
  12934. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12935. ConvertLEA(taicpu(hp1))
  12936. )
  12937. ) and
  12938. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  12939. GetNextInstruction(hp1,hp2) and
  12940. MatchInstruction(hp2,A_MOV,[]) and
  12941. (taicpu(hp2).oper[0]^.typ = top_reg) and
  12942. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  12943. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  12944. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  12945. {$ifdef i386}
  12946. { not all registers have byte size sub registers on i386 }
  12947. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  12948. {$endif i386}
  12949. (((taicpu(hp1).ops=2) and
  12950. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  12951. ((taicpu(hp1).ops=1) and
  12952. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  12953. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  12954. begin
  12955. { change movsX/movzX reg/ref, reg2
  12956. add/sub/or/... reg3/$const, reg2
  12957. mov reg2 reg/ref
  12958. to add/sub/or/... reg3/$const, reg/ref }
  12959. { by example:
  12960. movswl %si,%eax movswl %si,%eax p
  12961. decl %eax addl %edx,%eax hp1
  12962. movw %ax,%si movw %ax,%si hp2
  12963. ->
  12964. movswl %si,%eax movswl %si,%eax p
  12965. decw %eax addw %edx,%eax hp1
  12966. movw %ax,%si movw %ax,%si hp2
  12967. }
  12968. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  12969. {
  12970. ->
  12971. movswl %si,%eax movswl %si,%eax p
  12972. decw %si addw %dx,%si hp1
  12973. movw %ax,%si movw %ax,%si hp2
  12974. }
  12975. case taicpu(hp1).ops of
  12976. 1:
  12977. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  12978. 2:
  12979. begin
  12980. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  12981. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  12982. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  12983. end;
  12984. else
  12985. internalerror(2008042702);
  12986. end;
  12987. {
  12988. ->
  12989. decw %si addw %dx,%si p
  12990. }
  12991. DebugMsg(SPeepholeOptimization + 'var3',p);
  12992. RemoveCurrentP(p, hp1);
  12993. RemoveInstruction(hp2);
  12994. Result := True;
  12995. Exit;
  12996. end;
  12997. if reg_and_hp1_is_instr and
  12998. (taicpu(hp1).opcode = A_MOV) and
  12999. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13000. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  13001. {$ifdef x86_64}
  13002. { check for implicit extension to 64 bit }
  13003. or
  13004. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13005. (taicpu(hp1).opsize=S_Q) and
  13006. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  13007. )
  13008. {$endif x86_64}
  13009. )
  13010. then
  13011. begin
  13012. { change
  13013. movx %reg1,%reg2
  13014. mov %reg2,%reg3
  13015. dealloc %reg2
  13016. into
  13017. movx %reg,%reg3
  13018. }
  13019. TransferUsedRegs(TmpUsedRegs);
  13020. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13021. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  13022. begin
  13023. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  13024. {$ifdef x86_64}
  13025. if (taicpu(p).opsize in [S_BL,S_WL]) and
  13026. (taicpu(hp1).opsize=S_Q) then
  13027. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  13028. else
  13029. {$endif x86_64}
  13030. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  13031. RemoveInstruction(hp1);
  13032. Result := True;
  13033. Exit;
  13034. end;
  13035. end;
  13036. if reg_and_hp1_is_instr and
  13037. ((taicpu(hp1).opcode=A_MOV) or
  13038. (taicpu(hp1).opcode=A_ADD) or
  13039. (taicpu(hp1).opcode=A_SUB) or
  13040. (taicpu(hp1).opcode=A_CMP) or
  13041. (taicpu(hp1).opcode=A_OR) or
  13042. (taicpu(hp1).opcode=A_XOR) or
  13043. (taicpu(hp1).opcode=A_AND)
  13044. ) and
  13045. (taicpu(hp1).oper[1]^.typ = top_reg) then
  13046. begin
  13047. AndTest := (taicpu(hp1).opcode=A_AND) and
  13048. GetNextInstruction(hp1, hp2) and
  13049. (hp2.typ = ait_instruction) and
  13050. (
  13051. (
  13052. (taicpu(hp2).opcode=A_TEST) and
  13053. (
  13054. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  13055. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  13056. (
  13057. { If the AND and TEST instructions share a constant, this is also valid }
  13058. (taicpu(hp1).oper[0]^.typ = top_const) and
  13059. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  13060. )
  13061. ) and
  13062. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13063. ) or
  13064. (
  13065. (taicpu(hp2).opcode=A_CMP) and
  13066. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  13067. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  13068. )
  13069. );
  13070. { change
  13071. movx (oper),%reg2
  13072. and $x,%reg2
  13073. test %reg2,%reg2
  13074. dealloc %reg2
  13075. into
  13076. op %reg1,%reg3
  13077. if the second op accesses only the bits stored in reg1
  13078. }
  13079. if ((taicpu(p).oper[0]^.typ=top_reg) or
  13080. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  13081. (taicpu(hp1).oper[0]^.typ = top_const) and
  13082. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13083. AndTest then
  13084. begin
  13085. { Check if the AND constant is in range }
  13086. case taicpu(p).opsize of
  13087. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13088. begin
  13089. NewSize := S_B;
  13090. Limit := $FF;
  13091. end;
  13092. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13093. begin
  13094. NewSize := S_W;
  13095. Limit := $FFFF;
  13096. end;
  13097. {$ifdef x86_64}
  13098. S_LQ:
  13099. begin
  13100. NewSize := S_L;
  13101. Limit := $FFFFFFFF;
  13102. end;
  13103. {$endif x86_64}
  13104. else
  13105. InternalError(2021120303);
  13106. end;
  13107. if (
  13108. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  13109. { Check for negative operands }
  13110. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  13111. ) and
  13112. GetNextInstruction(hp2,hp3) and
  13113. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  13114. (taicpu(hp3).condition in [C_E,C_NE]) then
  13115. begin
  13116. TransferUsedRegs(TmpUsedRegs);
  13117. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13118. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13119. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  13120. begin
  13121. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  13122. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13123. taicpu(hp1).opcode := A_TEST;
  13124. taicpu(hp1).opsize := NewSize;
  13125. RemoveInstruction(hp2);
  13126. RemoveCurrentP(p, hp1);
  13127. Result:=true;
  13128. exit;
  13129. end;
  13130. end;
  13131. end;
  13132. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  13133. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  13134. (taicpu(hp1).opsize=S_B)) or
  13135. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  13136. (taicpu(hp1).opsize=S_W))
  13137. {$ifdef x86_64}
  13138. or ((taicpu(p).opsize=S_LQ) and
  13139. (taicpu(hp1).opsize=S_L))
  13140. {$endif x86_64}
  13141. ) and
  13142. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  13143. begin
  13144. { change
  13145. movx %reg1,%reg2
  13146. op %reg2,%reg3
  13147. dealloc %reg2
  13148. into
  13149. op %reg1,%reg3
  13150. if the second op accesses only the bits stored in reg1
  13151. }
  13152. TransferUsedRegs(TmpUsedRegs);
  13153. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13154. if AndTest then
  13155. begin
  13156. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13157. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13158. end
  13159. else
  13160. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13161. if not RegUsed then
  13162. begin
  13163. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  13164. if taicpu(p).oper[0]^.typ=top_reg then
  13165. begin
  13166. case taicpu(hp1).opsize of
  13167. S_B:
  13168. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  13169. S_W:
  13170. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  13171. S_L:
  13172. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  13173. else
  13174. Internalerror(2020102301);
  13175. end;
  13176. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  13177. end
  13178. else
  13179. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  13180. RemoveCurrentP(p);
  13181. if AndTest then
  13182. RemoveInstruction(hp2);
  13183. result:=true;
  13184. exit;
  13185. end;
  13186. end
  13187. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13188. (
  13189. { Bitwise operations only }
  13190. (taicpu(hp1).opcode=A_AND) or
  13191. (taicpu(hp1).opcode=A_TEST) or
  13192. (
  13193. (taicpu(hp1).oper[0]^.typ = top_const) and
  13194. (
  13195. (taicpu(hp1).opcode=A_OR) or
  13196. (taicpu(hp1).opcode=A_XOR)
  13197. )
  13198. )
  13199. ) and
  13200. (
  13201. (taicpu(hp1).oper[0]^.typ = top_const) or
  13202. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  13203. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  13204. ) then
  13205. begin
  13206. { change
  13207. movx %reg2,%reg2
  13208. op const,%reg2
  13209. into
  13210. op const,%reg2 (smaller version)
  13211. movx %reg2,%reg2
  13212. also change
  13213. movx %reg1,%reg2
  13214. and/test (oper),%reg2
  13215. dealloc %reg2
  13216. into
  13217. and/test (oper),%reg1
  13218. }
  13219. case taicpu(p).opsize of
  13220. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13221. begin
  13222. NewSize := S_B;
  13223. NewRegSize := R_SUBL;
  13224. Limit := $FF;
  13225. end;
  13226. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13227. begin
  13228. NewSize := S_W;
  13229. NewRegSize := R_SUBW;
  13230. Limit := $FFFF;
  13231. end;
  13232. {$ifdef x86_64}
  13233. S_LQ:
  13234. begin
  13235. NewSize := S_L;
  13236. NewRegSize := R_SUBD;
  13237. Limit := $FFFFFFFF;
  13238. end;
  13239. {$endif x86_64}
  13240. else
  13241. Internalerror(2021120302);
  13242. end;
  13243. TransferUsedRegs(TmpUsedRegs);
  13244. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13245. if AndTest then
  13246. begin
  13247. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  13248. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  13249. end
  13250. else
  13251. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  13252. if
  13253. (
  13254. (taicpu(p).opcode = A_MOVZX) and
  13255. (
  13256. (taicpu(hp1).opcode=A_AND) or
  13257. (taicpu(hp1).opcode=A_TEST)
  13258. ) and
  13259. not (
  13260. { If both are references, then the final instruction will have
  13261. both operands as references, which is not allowed }
  13262. (taicpu(p).oper[0]^.typ = top_ref) and
  13263. (taicpu(hp1).oper[0]^.typ = top_ref)
  13264. ) and
  13265. not RegUsed
  13266. ) or
  13267. (
  13268. (
  13269. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  13270. not RegUsed
  13271. ) and
  13272. (taicpu(p).oper[0]^.typ = top_reg) and
  13273. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13274. (taicpu(hp1).oper[0]^.typ = top_const) and
  13275. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  13276. ) then
  13277. begin
  13278. {$if defined(i386) or defined(i8086)}
  13279. { If the target size is 8-bit, make sure we can actually encode it }
  13280. 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
  13281. Exit;
  13282. {$endif i386 or i8086}
  13283. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  13284. taicpu(hp1).opsize := NewSize;
  13285. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  13286. if AndTest then
  13287. begin
  13288. RemoveInstruction(hp2);
  13289. if not RegUsed then
  13290. begin
  13291. taicpu(hp1).opcode := A_TEST;
  13292. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  13293. begin
  13294. { Make sure the reference is the second operand }
  13295. SwapOper := taicpu(hp1).oper[0];
  13296. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  13297. taicpu(hp1).oper[1] := SwapOper;
  13298. end;
  13299. end;
  13300. end;
  13301. case taicpu(hp1).oper[0]^.typ of
  13302. top_reg:
  13303. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  13304. top_const:
  13305. { For the AND/TEST case }
  13306. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  13307. else
  13308. ;
  13309. end;
  13310. if RegUsed then
  13311. begin
  13312. AsmL.Remove(p);
  13313. AsmL.InsertAfter(p, hp1);
  13314. p := hp1;
  13315. end
  13316. else
  13317. RemoveCurrentP(p, hp1);
  13318. result:=true;
  13319. exit;
  13320. end;
  13321. end;
  13322. end;
  13323. if reg_and_hp1_is_instr and
  13324. (taicpu(p).oper[0]^.typ = top_reg) and
  13325. (
  13326. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  13327. ) and
  13328. (taicpu(hp1).oper[0]^.typ = top_const) and
  13329. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13330. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13331. { Minimum shift value allowed is the bit difference between the sizes }
  13332. (taicpu(hp1).oper[0]^.val >=
  13333. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13334. 8 * (
  13335. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  13336. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13337. )
  13338. ) then
  13339. begin
  13340. { For:
  13341. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  13342. shl/sal ##, %reg1
  13343. Remove the movsx/movzx instruction if the shift overwrites the
  13344. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  13345. }
  13346. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  13347. RemoveCurrentP(p, hp1);
  13348. Result := True;
  13349. Exit;
  13350. end
  13351. else if reg_and_hp1_is_instr and
  13352. (taicpu(p).oper[0]^.typ = top_reg) and
  13353. (
  13354. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  13355. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  13356. ) and
  13357. (taicpu(hp1).oper[0]^.typ = top_const) and
  13358. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13359. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13360. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  13361. (taicpu(hp1).oper[0]^.val <
  13362. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  13363. 8 * (
  13364. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  13365. )
  13366. ) then
  13367. begin
  13368. { For:
  13369. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  13370. sar ##, %reg1 shr ##, %reg1
  13371. Move the shift to before the movx instruction if the shift value
  13372. is not too large.
  13373. }
  13374. asml.Remove(hp1);
  13375. asml.InsertBefore(hp1, p);
  13376. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  13377. case taicpu(p).opsize of
  13378. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  13379. taicpu(hp1).opsize := S_B;
  13380. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  13381. taicpu(hp1).opsize := S_W;
  13382. {$ifdef x86_64}
  13383. S_LQ:
  13384. taicpu(hp1).opsize := S_L;
  13385. {$endif}
  13386. else
  13387. InternalError(2020112401);
  13388. end;
  13389. if (taicpu(hp1).opcode = A_SHR) then
  13390. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  13391. else
  13392. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  13393. Result := True;
  13394. end;
  13395. if reg_and_hp1_is_instr and
  13396. (taicpu(p).oper[0]^.typ = top_reg) and
  13397. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  13398. (
  13399. (taicpu(hp1).opcode = taicpu(p).opcode)
  13400. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  13401. {$ifdef x86_64}
  13402. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  13403. {$endif x86_64}
  13404. ) then
  13405. begin
  13406. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13407. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  13408. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13409. begin
  13410. {
  13411. For example:
  13412. movzbw %al,%ax
  13413. movzwl %ax,%eax
  13414. Compress into:
  13415. movzbl %al,%eax
  13416. }
  13417. RegUsed := False;
  13418. case taicpu(p).opsize of
  13419. S_BW:
  13420. case taicpu(hp1).opsize of
  13421. S_WL:
  13422. begin
  13423. taicpu(p).opsize := S_BL;
  13424. RegUsed := True;
  13425. end;
  13426. {$ifdef x86_64}
  13427. S_WQ:
  13428. begin
  13429. if taicpu(p).opcode = A_MOVZX then
  13430. begin
  13431. taicpu(p).opsize := S_BL;
  13432. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13433. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13434. end
  13435. else
  13436. taicpu(p).opsize := S_BQ;
  13437. RegUsed := True;
  13438. end;
  13439. {$endif x86_64}
  13440. else
  13441. ;
  13442. end;
  13443. {$ifdef x86_64}
  13444. S_BL:
  13445. case taicpu(hp1).opsize of
  13446. S_LQ:
  13447. begin
  13448. if taicpu(p).opcode = A_MOVZX then
  13449. begin
  13450. taicpu(p).opsize := S_BL;
  13451. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13452. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13453. end
  13454. else
  13455. taicpu(p).opsize := S_BQ;
  13456. RegUsed := True;
  13457. end;
  13458. else
  13459. ;
  13460. end;
  13461. S_WL:
  13462. case taicpu(hp1).opsize of
  13463. S_LQ:
  13464. begin
  13465. if taicpu(p).opcode = A_MOVZX then
  13466. begin
  13467. taicpu(p).opsize := S_WL;
  13468. { 64-bit zero extension is implicit, so change to the 32-bit register }
  13469. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13470. end
  13471. else
  13472. taicpu(p).opsize := S_WQ;
  13473. RegUsed := True;
  13474. end;
  13475. else
  13476. ;
  13477. end;
  13478. {$endif x86_64}
  13479. else
  13480. ;
  13481. end;
  13482. if RegUsed then
  13483. begin
  13484. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  13485. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  13486. RemoveInstruction(hp1);
  13487. Result := True;
  13488. Exit;
  13489. end;
  13490. end;
  13491. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13492. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  13493. GetNextInstruction(hp1, hp2) and
  13494. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  13495. (
  13496. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  13497. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  13498. {$ifdef x86_64}
  13499. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  13500. {$endif x86_64}
  13501. ) and
  13502. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  13503. (
  13504. (
  13505. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  13506. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13507. ) or
  13508. (
  13509. { Only allow the operands in reverse order for TEST instructions }
  13510. (taicpu(hp2).opcode = A_TEST) and
  13511. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  13512. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  13513. )
  13514. ) then
  13515. begin
  13516. {
  13517. For example:
  13518. movzbl %al,%eax
  13519. movzbl (ref),%edx
  13520. andl %edx,%eax
  13521. (%edx deallocated)
  13522. Change to:
  13523. andb (ref),%al
  13524. movzbl %al,%eax
  13525. Rules are:
  13526. - First two instructions have the same opcode and opsize
  13527. - First instruction's operands are the same super-register
  13528. - Second instruction operates on a different register
  13529. - Third instruction is AND, OR, XOR or TEST
  13530. - Third instruction's operands are the destination registers of the first two instructions
  13531. - Third instruction writes to the destination register of the first instruction (except with TEST)
  13532. - Second instruction's destination register is deallocated afterwards
  13533. }
  13534. TransferUsedRegs(TmpUsedRegs);
  13535. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13536. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13537. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  13538. begin
  13539. case taicpu(p).opsize of
  13540. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13541. NewSize := S_B;
  13542. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13543. NewSize := S_W;
  13544. {$ifdef x86_64}
  13545. S_LQ:
  13546. NewSize := S_L;
  13547. {$endif x86_64}
  13548. else
  13549. InternalError(2021120301);
  13550. end;
  13551. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  13552. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  13553. taicpu(hp2).opsize := NewSize;
  13554. RemoveInstruction(hp1);
  13555. { With TEST, it's best to keep the MOVX instruction at the top }
  13556. if (taicpu(hp2).opcode <> A_TEST) then
  13557. begin
  13558. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  13559. asml.Remove(p);
  13560. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  13561. asml.InsertAfter(p, hp2);
  13562. p := hp2;
  13563. end
  13564. else
  13565. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  13566. Result := True;
  13567. Exit;
  13568. end;
  13569. end;
  13570. end;
  13571. if taicpu(p).opcode=A_MOVZX then
  13572. begin
  13573. { removes superfluous And's after movzx's }
  13574. if reg_and_hp1_is_instr and
  13575. (taicpu(hp1).opcode = A_AND) and
  13576. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13577. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  13578. {$ifdef x86_64}
  13579. { check for implicit extension to 64 bit }
  13580. or
  13581. ((taicpu(p).opsize in [S_BL,S_WL]) and
  13582. (taicpu(hp1).opsize=S_Q) and
  13583. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  13584. )
  13585. {$endif x86_64}
  13586. )
  13587. then
  13588. begin
  13589. case taicpu(p).opsize Of
  13590. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13591. if (taicpu(hp1).oper[0]^.val = $ff) then
  13592. begin
  13593. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  13594. RemoveInstruction(hp1);
  13595. Result:=true;
  13596. exit;
  13597. end;
  13598. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13599. if (taicpu(hp1).oper[0]^.val = $ffff) then
  13600. begin
  13601. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  13602. RemoveInstruction(hp1);
  13603. Result:=true;
  13604. exit;
  13605. end;
  13606. {$ifdef x86_64}
  13607. S_LQ:
  13608. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  13609. begin
  13610. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  13611. RemoveInstruction(hp1);
  13612. Result:=true;
  13613. exit;
  13614. end;
  13615. {$endif x86_64}
  13616. else
  13617. ;
  13618. end;
  13619. { we cannot get rid of the and, but can we get rid of the movz ?}
  13620. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  13621. begin
  13622. case taicpu(p).opsize Of
  13623. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  13624. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  13625. begin
  13626. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  13627. RemoveCurrentP(p,hp1);
  13628. Result:=true;
  13629. exit;
  13630. end;
  13631. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  13632. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  13633. begin
  13634. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  13635. RemoveCurrentP(p,hp1);
  13636. Result:=true;
  13637. exit;
  13638. end;
  13639. {$ifdef x86_64}
  13640. S_LQ:
  13641. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  13642. begin
  13643. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  13644. RemoveCurrentP(p,hp1);
  13645. Result:=true;
  13646. exit;
  13647. end;
  13648. {$endif x86_64}
  13649. else
  13650. ;
  13651. end;
  13652. end;
  13653. end;
  13654. { changes some movzx constructs to faster synonyms (all examples
  13655. are given with eax/ax, but are also valid for other registers)}
  13656. if MatchOpType(taicpu(p),top_reg,top_reg) then
  13657. begin
  13658. case taicpu(p).opsize of
  13659. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  13660. (the machine code is equivalent to movzbl %al,%eax), but the
  13661. code generator still generates that assembler instruction and
  13662. it is silently converted. This should probably be checked.
  13663. [Kit] }
  13664. S_BW:
  13665. begin
  13666. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  13667. (
  13668. not IsMOVZXAcceptable
  13669. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  13670. or (
  13671. (cs_opt_size in current_settings.optimizerswitches) and
  13672. (taicpu(p).oper[1]^.reg = NR_AX)
  13673. )
  13674. ) then
  13675. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  13676. begin
  13677. DebugMsg(SPeepholeOptimization + 'var7',p);
  13678. taicpu(p).opcode := A_AND;
  13679. taicpu(p).changeopsize(S_W);
  13680. taicpu(p).loadConst(0,$ff);
  13681. Result := True;
  13682. end
  13683. else if not IsMOVZXAcceptable and
  13684. GetNextInstruction(p, hp1) and
  13685. (tai(hp1).typ = ait_instruction) and
  13686. (taicpu(hp1).opcode = A_AND) and
  13687. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13688. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13689. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  13690. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  13691. begin
  13692. DebugMsg(SPeepholeOptimization + 'var8',p);
  13693. taicpu(p).opcode := A_MOV;
  13694. taicpu(p).changeopsize(S_W);
  13695. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  13696. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13697. Result := True;
  13698. end;
  13699. end;
  13700. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  13701. S_BL:
  13702. if not IsMOVZXAcceptable then
  13703. begin
  13704. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13705. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  13706. begin
  13707. DebugMsg(SPeepholeOptimization + 'var9',p);
  13708. taicpu(p).opcode := A_AND;
  13709. taicpu(p).changeopsize(S_L);
  13710. taicpu(p).loadConst(0,$ff);
  13711. Result := True;
  13712. end
  13713. else if GetNextInstruction(p, hp1) and
  13714. (tai(hp1).typ = ait_instruction) and
  13715. (taicpu(hp1).opcode = A_AND) and
  13716. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13717. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13718. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  13719. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  13720. begin
  13721. DebugMsg(SPeepholeOptimization + 'var10',p);
  13722. taicpu(p).opcode := A_MOV;
  13723. taicpu(p).changeopsize(S_L);
  13724. { do not use R_SUBWHOLE
  13725. as movl %rdx,%eax
  13726. is invalid in assembler PM }
  13727. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13728. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13729. Result := True;
  13730. end;
  13731. end;
  13732. {$endif i8086}
  13733. S_WL:
  13734. if not IsMOVZXAcceptable then
  13735. begin
  13736. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  13737. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  13738. begin
  13739. DebugMsg(SPeepholeOptimization + 'var11',p);
  13740. taicpu(p).opcode := A_AND;
  13741. taicpu(p).changeopsize(S_L);
  13742. taicpu(p).loadConst(0,$ffff);
  13743. Result := True;
  13744. end
  13745. else if GetNextInstruction(p, hp1) and
  13746. (tai(hp1).typ = ait_instruction) and
  13747. (taicpu(hp1).opcode = A_AND) and
  13748. (taicpu(hp1).oper[0]^.typ = top_const) and
  13749. (taicpu(hp1).oper[1]^.typ = top_reg) and
  13750. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13751. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  13752. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  13753. begin
  13754. DebugMsg(SPeepholeOptimization + 'var12',p);
  13755. taicpu(p).opcode := A_MOV;
  13756. taicpu(p).changeopsize(S_L);
  13757. { do not use R_SUBWHOLE
  13758. as movl %rdx,%eax
  13759. is invalid in assembler PM }
  13760. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13761. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13762. Result := True;
  13763. end;
  13764. end;
  13765. else
  13766. InternalError(2017050705);
  13767. end;
  13768. end
  13769. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  13770. begin
  13771. if GetNextInstruction(p, hp1) and
  13772. (tai(hp1).typ = ait_instruction) and
  13773. (taicpu(hp1).opcode = A_AND) and
  13774. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13775. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13776. begin
  13777. case taicpu(p).opsize Of
  13778. S_BL:
  13779. if (taicpu(hp1).opsize <> S_L) or
  13780. (taicpu(hp1).oper[0]^.val > $FF) then
  13781. begin
  13782. DebugMsg(SPeepholeOptimization + 'var13',p);
  13783. taicpu(hp1).changeopsize(S_L);
  13784. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13785. Include(OptsToCheck, aoc_ForceNewIteration);
  13786. end;
  13787. S_WL:
  13788. if (taicpu(hp1).opsize <> S_L) or
  13789. (taicpu(hp1).oper[0]^.val > $FFFF) then
  13790. begin
  13791. DebugMsg(SPeepholeOptimization + 'var14',p);
  13792. taicpu(hp1).changeopsize(S_L);
  13793. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  13794. Include(OptsToCheck, aoc_ForceNewIteration);
  13795. end;
  13796. S_BW:
  13797. if (taicpu(hp1).opsize <> S_W) or
  13798. (taicpu(hp1).oper[0]^.val > $FF) then
  13799. begin
  13800. DebugMsg(SPeepholeOptimization + 'var15',p);
  13801. taicpu(hp1).changeopsize(S_W);
  13802. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  13803. Include(OptsToCheck, aoc_ForceNewIteration);
  13804. end;
  13805. else
  13806. Internalerror(2017050704)
  13807. end;
  13808. end;
  13809. end;
  13810. end;
  13811. end;
  13812. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  13813. var
  13814. hp1, hp2 : tai;
  13815. MaskLength : Cardinal;
  13816. MaskedBits : TCgInt;
  13817. ActiveReg : TRegister;
  13818. begin
  13819. Result:=false;
  13820. { There are no optimisations for reference targets }
  13821. if (taicpu(p).oper[1]^.typ <> top_reg) then
  13822. Exit;
  13823. while GetNextInstruction(p, hp1) and
  13824. (hp1.typ = ait_instruction) do
  13825. begin
  13826. if (taicpu(p).oper[0]^.typ = top_const) then
  13827. begin
  13828. case taicpu(hp1).opcode of
  13829. A_AND:
  13830. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13831. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13832. { the second register must contain the first one, so compare their subreg types }
  13833. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  13834. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  13835. { change
  13836. and const1, reg
  13837. and const2, reg
  13838. to
  13839. and (const1 and const2), reg
  13840. }
  13841. begin
  13842. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  13843. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  13844. RemoveCurrentP(p, hp1);
  13845. Result:=true;
  13846. exit;
  13847. end;
  13848. A_CMP:
  13849. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  13850. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  13851. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  13852. { Just check that the condition on the next instruction is compatible }
  13853. GetNextInstruction(hp1, hp2) and
  13854. (hp2.typ = ait_instruction) and
  13855. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  13856. then
  13857. { change
  13858. and 2^n, reg
  13859. cmp 2^n, reg
  13860. j(c) / set(c) / cmov(c) (c is equal or not equal)
  13861. to
  13862. and 2^n, reg
  13863. test reg, reg
  13864. j(~c) / set(~c) / cmov(~c)
  13865. }
  13866. begin
  13867. { Keep TEST instruction in, rather than remove it, because
  13868. it may trigger other optimisations such as MovAndTest2Test }
  13869. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  13870. taicpu(hp1).opcode := A_TEST;
  13871. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  13872. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  13873. Result := True;
  13874. Exit;
  13875. end
  13876. else if ((taicpu(p).oper[0]^.val=$ff) or (taicpu(p).oper[0]^.val=$ffff) or (taicpu(p).oper[0]^.val=$ffffffff)) and
  13877. MatchOpType(taicpu(hp1),top_const,top_reg) and
  13878. (taicpu(p).oper[0]^.val>=taicpu(hp1).oper[0]^.val) and
  13879. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) then
  13880. { change
  13881. and $ff/$ff/$ffff, reg
  13882. cmp val<=$ff/val<=$ffff/val<=$ffffffff, reg
  13883. dealloc reg
  13884. to
  13885. cmp val<=$ff/val<=$ffff/val<=$ffffffff, resized reg
  13886. }
  13887. begin
  13888. TransferUsedRegs(TmpUsedRegs);
  13889. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13890. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  13891. begin
  13892. DebugMsg(SPeepholeOptimization + 'AND/CMP -> CMP', p);
  13893. case taicpu(p).oper[0]^.val of
  13894. $ff:
  13895. begin
  13896. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  13897. taicpu(hp1).opsize:=S_B;
  13898. end;
  13899. $ffff:
  13900. begin
  13901. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  13902. taicpu(hp1).opsize:=S_W;
  13903. end;
  13904. $ffffffff:
  13905. begin
  13906. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  13907. taicpu(hp1).opsize:=S_L;
  13908. end;
  13909. else
  13910. Internalerror(2023030401);
  13911. end;
  13912. RemoveCurrentP(p);
  13913. Result := True;
  13914. Exit;
  13915. end;
  13916. end;
  13917. A_MOVZX:
  13918. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  13919. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  13920. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  13921. (
  13922. (
  13923. (taicpu(p).opsize=S_W) and
  13924. (taicpu(hp1).opsize=S_BW)
  13925. ) or
  13926. (
  13927. (taicpu(p).opsize=S_L) and
  13928. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  13929. )
  13930. {$ifdef x86_64}
  13931. or
  13932. (
  13933. (taicpu(p).opsize=S_Q) and
  13934. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  13935. )
  13936. {$endif x86_64}
  13937. ) then
  13938. begin
  13939. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  13940. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  13941. ) or
  13942. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  13943. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  13944. then
  13945. begin
  13946. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  13947. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  13948. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  13949. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  13950. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  13951. }
  13952. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  13953. RemoveInstruction(hp1);
  13954. { See if there are other optimisations possible }
  13955. Continue;
  13956. end;
  13957. end;
  13958. A_SHL:
  13959. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13960. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  13961. begin
  13962. {$ifopt R+}
  13963. {$define RANGE_WAS_ON}
  13964. {$R-}
  13965. {$endif}
  13966. { get length of potential and mask }
  13967. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  13968. { really a mask? }
  13969. {$ifdef RANGE_WAS_ON}
  13970. {$R+}
  13971. {$endif}
  13972. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  13973. { unmasked part shifted out? }
  13974. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  13975. begin
  13976. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  13977. RemoveCurrentP(p, hp1);
  13978. Result:=true;
  13979. exit;
  13980. end;
  13981. end;
  13982. A_SHR:
  13983. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  13984. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  13985. (taicpu(hp1).oper[0]^.val <= 63) then
  13986. begin
  13987. { Does SHR combined with the AND cover all the bits?
  13988. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  13989. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  13990. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  13991. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  13992. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  13993. begin
  13994. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  13995. RemoveCurrentP(p, hp1);
  13996. Result := True;
  13997. Exit;
  13998. end;
  13999. end;
  14000. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14001. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  14002. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  14003. begin
  14004. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14005. (
  14006. (
  14007. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  14008. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  14009. ) or (
  14010. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  14011. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  14012. {$ifdef x86_64}
  14013. ) or (
  14014. (taicpu(hp1).opsize = S_LQ) and
  14015. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  14016. {$endif x86_64}
  14017. )
  14018. ) then
  14019. begin
  14020. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  14021. begin
  14022. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  14023. RemoveInstruction(hp1);
  14024. { See if there are other optimisations possible }
  14025. Continue;
  14026. end;
  14027. { The super-registers are the same though.
  14028. Note that this change by itself doesn't improve
  14029. code speed, but it opens up other optimisations. }
  14030. {$ifdef x86_64}
  14031. { Convert 64-bit register to 32-bit }
  14032. case taicpu(hp1).opsize of
  14033. S_BQ:
  14034. begin
  14035. taicpu(hp1).opsize := S_BL;
  14036. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14037. end;
  14038. S_WQ:
  14039. begin
  14040. taicpu(hp1).opsize := S_WL;
  14041. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  14042. end
  14043. else
  14044. ;
  14045. end;
  14046. {$endif x86_64}
  14047. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  14048. taicpu(hp1).opcode := A_MOVZX;
  14049. { See if there are other optimisations possible }
  14050. Continue;
  14051. end;
  14052. end;
  14053. else
  14054. ;
  14055. end;
  14056. end
  14057. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  14058. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  14059. begin
  14060. {$ifdef x86_64}
  14061. if (taicpu(p).opsize = S_Q) then
  14062. begin
  14063. { Never necessary }
  14064. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  14065. RemoveCurrentP(p, hp1);
  14066. Result := True;
  14067. Exit;
  14068. end;
  14069. {$endif x86_64}
  14070. { Forward check to determine necessity of and %reg,%reg }
  14071. TransferUsedRegs(TmpUsedRegs);
  14072. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14073. { Saves on a bunch of dereferences }
  14074. ActiveReg := taicpu(p).oper[1]^.reg;
  14075. case taicpu(hp1).opcode of
  14076. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  14077. if (
  14078. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14079. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14080. ) and
  14081. (
  14082. (taicpu(hp1).opcode <> A_MOV) or
  14083. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  14084. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  14085. ) and
  14086. not (
  14087. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  14088. (taicpu(hp1).opcode = A_MOV) and
  14089. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  14090. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  14091. ) and
  14092. (
  14093. (
  14094. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14095. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  14096. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  14097. ) or
  14098. (
  14099. {$ifdef x86_64}
  14100. (
  14101. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  14102. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  14103. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  14104. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  14105. ) and
  14106. {$endif x86_64}
  14107. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  14108. )
  14109. ) then
  14110. begin
  14111. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  14112. RemoveCurrentP(p, hp1);
  14113. Result := True;
  14114. Exit;
  14115. end;
  14116. A_ADD,
  14117. A_AND,
  14118. A_BSF,
  14119. A_BSR,
  14120. A_BTC,
  14121. A_BTR,
  14122. A_BTS,
  14123. A_OR,
  14124. A_SUB,
  14125. A_XOR:
  14126. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  14127. if (
  14128. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14129. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14130. ) and
  14131. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  14132. begin
  14133. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  14134. RemoveCurrentP(p, hp1);
  14135. Result := True;
  14136. Exit;
  14137. end;
  14138. A_CMP,
  14139. A_TEST:
  14140. if (
  14141. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  14142. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  14143. ) and
  14144. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  14145. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  14146. begin
  14147. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  14148. RemoveCurrentP(p, hp1);
  14149. Result := True;
  14150. Exit;
  14151. end;
  14152. A_BSWAP,
  14153. A_NEG,
  14154. A_NOT:
  14155. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  14156. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  14157. begin
  14158. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  14159. RemoveCurrentP(p, hp1);
  14160. Result := True;
  14161. Exit;
  14162. end;
  14163. else
  14164. ;
  14165. end;
  14166. end;
  14167. if (taicpu(hp1).is_jmp) and
  14168. (taicpu(hp1).opcode<>A_JMP) and
  14169. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  14170. begin
  14171. { change
  14172. and x, reg
  14173. jxx
  14174. to
  14175. test x, reg
  14176. jxx
  14177. if reg is deallocated before the
  14178. jump, but only if it's a conditional jump (PFV)
  14179. }
  14180. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  14181. taicpu(p).opcode := A_TEST;
  14182. Exit;
  14183. end;
  14184. Break;
  14185. end;
  14186. { Lone AND tests }
  14187. if (taicpu(p).oper[0]^.typ = top_const) then
  14188. begin
  14189. {
  14190. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  14191. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  14192. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  14193. }
  14194. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  14195. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  14196. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  14197. begin
  14198. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  14199. if taicpu(p).opsize = S_L then
  14200. begin
  14201. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  14202. Result := True;
  14203. end;
  14204. end;
  14205. end;
  14206. { Backward check to determine necessity of and %reg,%reg }
  14207. if (taicpu(p).oper[0]^.typ = top_reg) and
  14208. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  14209. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  14210. GetLastInstruction(p, hp2) and
  14211. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  14212. { Check size of adjacent instruction to determine if the AND is
  14213. effectively a null operation }
  14214. (
  14215. (taicpu(p).opsize = taicpu(hp2).opsize) or
  14216. { Note: Don't include S_Q }
  14217. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  14218. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  14219. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  14220. ) then
  14221. begin
  14222. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  14223. { If GetNextInstruction returned False, hp1 will be nil }
  14224. RemoveCurrentP(p, hp1);
  14225. Result := True;
  14226. Exit;
  14227. end;
  14228. end;
  14229. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  14230. var
  14231. hp1, hp2: tai;
  14232. NewRef: TReference;
  14233. Distance: Cardinal;
  14234. TempTracking: TAllUsedRegs;
  14235. DoAddMov2Lea: Boolean;
  14236. { This entire nested function is used in an if-statement below, but we
  14237. want to avoid all the used reg transfers and GetNextInstruction calls
  14238. until we really have to check }
  14239. function MemRegisterNotUsedLater: Boolean; inline;
  14240. var
  14241. hp2: tai;
  14242. begin
  14243. TransferUsedRegs(TmpUsedRegs);
  14244. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14245. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14246. else
  14247. { p and hp1 will be adjacent }
  14248. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14249. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  14250. end;
  14251. begin
  14252. Result := False;
  14253. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14254. (taicpu(p).oper[1]^.typ = top_reg) then
  14255. begin
  14256. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14257. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14258. (hp1.typ <> ait_instruction) or
  14259. not
  14260. (
  14261. (cs_opt_level3 in current_settings.optimizerswitches) or
  14262. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14263. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14264. ) then
  14265. Exit;
  14266. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14267. addq $x, %rax
  14268. movq %rax, %rdx
  14269. sarq $63, %rdx
  14270. (%rax still in use)
  14271. ...letting OptPass2ADD run its course (and without -Os) will produce:
  14272. leaq $x(%rax),%rdx
  14273. addq $x, %rax
  14274. sarq $63, %rdx
  14275. ...which is okay since it breaks the dependency chain between
  14276. addq and movq, but if OptPass2MOV is called first:
  14277. addq $x, %rax
  14278. cqto
  14279. ...which is better in all ways, taking only 2 cycles to execute
  14280. and much smaller in code size.
  14281. }
  14282. { The extra register tracking is quite strenuous }
  14283. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14284. MatchInstruction(hp1, A_MOV, []) then
  14285. begin
  14286. { Update the register tracking to the MOV instruction }
  14287. CopyUsedRegs(TempTracking);
  14288. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14289. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14290. else
  14291. { p and hp1 will be adjacent }
  14292. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14293. hp2 := hp1;
  14294. if OptPass2MOV(hp1) then
  14295. Include(OptsToCheck, aoc_ForceNewIteration);
  14296. { Reset the tracking to the current instruction }
  14297. RestoreUsedRegs(TempTracking);
  14298. ReleaseUsedRegs(TempTracking);
  14299. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14300. OptPass2ADD get called again }
  14301. if (hp1 <> hp2) then
  14302. begin
  14303. Result := True;
  14304. Exit;
  14305. end;
  14306. end;
  14307. { Change:
  14308. add %reg2,%reg1
  14309. (%reg2 not modified in between)
  14310. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  14311. To:
  14312. mov/s/z #(%reg1,%reg2),%reg1
  14313. }
  14314. if (taicpu(p).oper[0]^.typ = top_reg) and
  14315. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  14316. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  14317. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  14318. (
  14319. (
  14320. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  14321. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  14322. { r/esp cannot be an index }
  14323. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  14324. ) or (
  14325. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  14326. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  14327. )
  14328. ) and (
  14329. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  14330. (
  14331. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  14332. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  14333. MemRegisterNotUsedLater
  14334. )
  14335. ) then
  14336. begin
  14337. if (
  14338. { Instructions are guaranteed to be adjacent on -O2 and under }
  14339. (cs_opt_level3 in current_settings.optimizerswitches) and
  14340. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  14341. ) then
  14342. begin
  14343. { If the other register is used in between, move the MOV
  14344. instruction to right after the ADD instruction so a
  14345. saving can still be made }
  14346. Asml.Remove(hp1);
  14347. Asml.InsertAfter(hp1, p);
  14348. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14349. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14350. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  14351. RemoveCurrentp(p, hp1);
  14352. end
  14353. else
  14354. begin
  14355. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  14356. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  14357. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  14358. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  14359. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14360. { hp1 may not be the immediate next instruction under -O3 }
  14361. RemoveCurrentp(p)
  14362. else
  14363. RemoveCurrentp(p, hp1);
  14364. end;
  14365. Result := True;
  14366. Exit;
  14367. end;
  14368. { Change:
  14369. addl/q $x,%reg1
  14370. movl/q %reg1,%reg2
  14371. To:
  14372. leal/q $x(%reg1),%reg2
  14373. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14374. Breaks the dependency chain.
  14375. }
  14376. if (taicpu(p).oper[0]^.typ = top_const) and
  14377. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14378. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14379. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14380. (
  14381. { Instructions are guaranteed to be adjacent on -O2 and under }
  14382. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14383. (
  14384. { If the flags are used, don't make the optimisation,
  14385. otherwise they will be scrambled. Fixes #41148 }
  14386. (
  14387. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14388. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14389. ) and
  14390. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14391. )
  14392. ) then
  14393. begin
  14394. TransferUsedRegs(TmpUsedRegs);
  14395. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14396. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14397. else
  14398. { p and hp1 will be adjacent }
  14399. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14400. if (
  14401. SetAndTest(
  14402. (
  14403. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14404. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14405. ),
  14406. DoAddMov2Lea
  14407. ) or
  14408. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  14409. not (cs_opt_size in current_settings.optimizerswitches)
  14410. ) then
  14411. begin
  14412. { Change the MOV instruction to a LEA instruction, and update the
  14413. first operand }
  14414. reference_reset(NewRef, 1, []);
  14415. NewRef.base := taicpu(p).oper[1]^.reg;
  14416. NewRef.scalefactor := 1;
  14417. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  14418. taicpu(hp1).opcode := A_LEA;
  14419. taicpu(hp1).loadref(0, NewRef);
  14420. if DoAddMov2Lea then
  14421. begin
  14422. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14423. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  14424. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14425. { hp1 may not be the immediate next instruction under -O3 }
  14426. RemoveCurrentp(p)
  14427. else
  14428. RemoveCurrentp(p, hp1);
  14429. end
  14430. else
  14431. begin
  14432. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14433. { Move what is now the LEA instruction to before the ADD instruction }
  14434. Asml.Remove(hp1);
  14435. Asml.InsertBefore(hp1, p);
  14436. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14437. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  14438. p := hp1;
  14439. end;
  14440. Result := True;
  14441. end;
  14442. end;
  14443. end;
  14444. end;
  14445. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  14446. var
  14447. SubReg: TSubRegister;
  14448. hp1, hp2: tai;
  14449. CallJmp: Boolean;
  14450. begin
  14451. Result := False;
  14452. CallJmp := False;
  14453. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  14454. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  14455. with taicpu(p).oper[0]^.ref^ do
  14456. if not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  14457. if (offset = 0) then
  14458. begin
  14459. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  14460. begin
  14461. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  14462. taicpu(p).opcode := A_ADD;
  14463. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  14464. Result := True;
  14465. end
  14466. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  14467. begin
  14468. if (base <> NR_NO) then
  14469. begin
  14470. if (scalefactor <= 1) then
  14471. begin
  14472. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  14473. taicpu(p).opcode := A_ADD;
  14474. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  14475. Result := True;
  14476. end;
  14477. end
  14478. else
  14479. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  14480. if (scalefactor in [2, 4, 8]) then
  14481. begin
  14482. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  14483. taicpu(p).loadconst(0, BsrByte(scalefactor));
  14484. taicpu(p).opcode := A_SHL;
  14485. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  14486. Result := True;
  14487. end;
  14488. end;
  14489. end
  14490. { lea x(%reg1,%reg2),%reg3 and lea x(symbol,%reg2),%reg3 have a
  14491. lot of latency, so break off the offset if %reg3 is used soon
  14492. afterwards }
  14493. else if not (cs_opt_size in current_settings.optimizerswitches) and
  14494. { If 3-component addresses don't have additional latency, don't
  14495. perform this optimisation }
  14496. not (CPUX86_HINT_FAST_3COMP_ADDR in cpu_optimization_hints[current_settings.optimizecputype]) and
  14497. GetNextInstruction(p, hp1) and
  14498. (hp1.typ = ait_instruction) and
  14499. (
  14500. (
  14501. { Permit jumps and calls since they have a larger degree of overhead }
  14502. (
  14503. not SetAndTest(is_calljmp(taicpu(hp1).opcode), CallJmp) or
  14504. (
  14505. { ... unless the register specifies the location }
  14506. (taicpu(hp1).ops > 0) and
  14507. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  14508. )
  14509. ) and
  14510. (
  14511. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14512. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14513. )
  14514. )
  14515. or
  14516. (
  14517. { Check up to two instructions ahead }
  14518. GetNextInstruction(hp1, hp2) and
  14519. (hp2.typ = ait_instruction) and
  14520. (
  14521. not SetAndTest(is_calljmp(taicpu(hp2).opcode), CallJmp) or
  14522. (
  14523. { Same as above }
  14524. (taicpu(hp2).ops > 0) and
  14525. RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[0]^)
  14526. )
  14527. ) and
  14528. (
  14529. not CallJmp and { Use the Boolean result to avoid calling "is_calljmp" twice }
  14530. RegInInstruction(taicpu(p).oper[1]^.reg, hp2)
  14531. )
  14532. )
  14533. ) then
  14534. begin
  14535. { Offset will be a 32-bit signed integer, so it's safe to use in the 64-bit version of ADD }
  14536. hp2 := taicpu.op_const_reg(A_ADD, taicpu(p).opsize, offset, taicpu(p).oper[1]^.reg);
  14537. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14538. offset := 0;
  14539. if Assigned(symbol) or Assigned(relsymbol) then
  14540. DebugMsg(SPeepholeOptimization + 'lea x(sym,%reg1),%reg2 -> lea(sym,%reg1),%reg2; add $x,%reg2 to minimise instruction latency (Lea2LeaAdd)', p)
  14541. else
  14542. DebugMsg(SPeepholeOptimization + 'lea x(%reg1,%reg2),%reg3 -> lea(%reg1,%reg2),%reg3; add $x,%reg3 to minimise instruction latency (Lea2LeaAdd)', p);
  14543. { Inserting before the next instruction rather than after the
  14544. current instruction gives more accurate register tracking }
  14545. asml.InsertBefore(hp2, hp1);
  14546. AllocRegBetween(taicpu(p).oper[1]^.reg, p, hp2, UsedRegs);
  14547. Result := True;
  14548. end;
  14549. end;
  14550. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  14551. var
  14552. hp1, hp2: tai;
  14553. NewRef: TReference;
  14554. Distance: Cardinal;
  14555. TempTracking: TAllUsedRegs;
  14556. DoSubMov2Lea: Boolean;
  14557. begin
  14558. Result := False;
  14559. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  14560. MatchOpType(taicpu(p),top_const,top_reg) then
  14561. begin
  14562. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  14563. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  14564. (hp1.typ <> ait_instruction) or
  14565. not
  14566. (
  14567. (cs_opt_level3 in current_settings.optimizerswitches) or
  14568. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  14569. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  14570. ) then
  14571. Exit;
  14572. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  14573. subq $x, %rax
  14574. movq %rax, %rdx
  14575. sarq $63, %rdx
  14576. (%rax still in use)
  14577. ...letting OptPass2SUB run its course (and without -Os) will produce:
  14578. leaq $-x(%rax),%rdx
  14579. movq $x, %rax
  14580. sarq $63, %rdx
  14581. ...which is okay since it breaks the dependency chain between
  14582. subq and movq, but if OptPass2MOV is called first:
  14583. subq $x, %rax
  14584. cqto
  14585. ...which is better in all ways, taking only 2 cycles to execute
  14586. and much smaller in code size.
  14587. }
  14588. { The extra register tracking is quite strenuous }
  14589. if (cs_opt_level2 in current_settings.optimizerswitches) and
  14590. MatchInstruction(hp1, A_MOV, []) then
  14591. begin
  14592. { Update the register tracking to the MOV instruction }
  14593. CopyUsedRegs(TempTracking);
  14594. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14595. UpdateUsedRegsBetween(UsedRegs, p, hp1)
  14596. else
  14597. { p and hp1 will be adjacent }
  14598. UpdateUsedRegs(UsedRegs, tai(p.Next));
  14599. hp2 := hp1;
  14600. if OptPass2MOV(hp1) then
  14601. Include(OptsToCheck, aoc_ForceNewIteration);
  14602. { Reset the tracking to the current instruction }
  14603. RestoreUsedRegs(TempTracking);
  14604. ReleaseUsedRegs(TempTracking);
  14605. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  14606. OptPass2SUB get called again }
  14607. if (hp1 <> hp2) then
  14608. begin
  14609. Result := True;
  14610. Exit;
  14611. end;
  14612. end;
  14613. { Change:
  14614. subl/q $x,%reg1
  14615. movl/q %reg1,%reg2
  14616. To:
  14617. leal/q $-x(%reg1),%reg2
  14618. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  14619. Breaks the dependency chain and potentially permits the removal of
  14620. a CMP instruction if one follows.
  14621. }
  14622. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  14623. (taicpu(hp1).oper[1]^.typ = top_reg) and
  14624. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  14625. (
  14626. { Instructions are guaranteed to be adjacent on -O2 and under }
  14627. not (cs_opt_level3 in current_settings.optimizerswitches) or
  14628. (
  14629. { If the flags are used, don't make the optimisation,
  14630. otherwise they will be scrambled. Fixes #41148 }
  14631. (
  14632. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) or
  14633. not RegUsedBetween(NR_DEFAULTFLAGS, p, hp1)
  14634. ) and
  14635. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  14636. )
  14637. ) then
  14638. begin
  14639. TransferUsedRegs(TmpUsedRegs);
  14640. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14641. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1)
  14642. else
  14643. { p and hp1 will be adjacent }
  14644. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  14645. if (
  14646. SetAndTest(
  14647. (
  14648. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  14649. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  14650. ),
  14651. DoSubMov2Lea
  14652. ) or
  14653. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  14654. not (cs_opt_size in current_settings.optimizerswitches)
  14655. ) then
  14656. begin
  14657. { Change the MOV instruction to a LEA instruction, and update the
  14658. first operand }
  14659. reference_reset(NewRef, 1, []);
  14660. NewRef.base := taicpu(p).oper[1]^.reg;
  14661. NewRef.scalefactor := 1;
  14662. NewRef.offset := -taicpu(p).oper[0]^.val;
  14663. taicpu(hp1).opcode := A_LEA;
  14664. taicpu(hp1).loadref(0, NewRef);
  14665. if DoSubMov2Lea then
  14666. begin
  14667. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  14668. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  14669. if (cs_opt_level3 in current_settings.optimizerswitches) then
  14670. { hp1 may not be the immediate next instruction under -O3 }
  14671. RemoveCurrentp(p)
  14672. else
  14673. RemoveCurrentp(p, hp1);
  14674. end
  14675. else
  14676. begin
  14677. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  14678. { Move what is now the LEA instruction to before the SUB instruction }
  14679. Asml.Remove(hp1);
  14680. Asml.InsertBefore(hp1, p);
  14681. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14682. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  14683. p := hp1;
  14684. end;
  14685. Result := True;
  14686. end;
  14687. end;
  14688. end;
  14689. end;
  14690. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  14691. begin
  14692. { we can skip all instructions not messing with the stack pointer }
  14693. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  14694. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  14695. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  14696. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  14697. ({(taicpu(hp1).ops=0) or }
  14698. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  14699. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  14700. ) and }
  14701. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  14702. )
  14703. ) do
  14704. GetNextInstruction(hp1,hp1);
  14705. Result:=assigned(hp1);
  14706. end;
  14707. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  14708. var
  14709. hp1, hp2, hp3, hp4, hp5, hp6, hp7, hp8: tai;
  14710. begin
  14711. Result:=false;
  14712. hp5:=nil;
  14713. hp6:=nil;
  14714. hp7:=nil;
  14715. hp8:=nil;
  14716. { replace
  14717. leal(q) x(<stackpointer>),<stackpointer>
  14718. <optional .seh_stackalloc ...>
  14719. <optional .seh_endprologue ...>
  14720. call procname
  14721. <optional NOP>
  14722. leal(q) -x(<stackpointer>),<stackpointer>
  14723. <optional VZEROUPPER>
  14724. ret
  14725. by
  14726. jmp procname
  14727. but do it only on level 4 because it destroys stack back traces
  14728. }
  14729. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14730. MatchOpType(taicpu(p),top_ref,top_reg) and
  14731. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14732. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  14733. { the -8, -24, -40 are not required, but bail out early if possible,
  14734. higher values are unlikely }
  14735. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  14736. (taicpu(p).oper[0]^.ref^.offset=-24) or
  14737. (taicpu(p).oper[0]^.ref^.offset=-40)) and
  14738. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  14739. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  14740. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14741. GetNextInstruction(p, hp1) and
  14742. { Take a copy of hp1 }
  14743. SetAndTest(hp1, hp4) and
  14744. { trick to skip label }
  14745. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14746. { skip directives, .seh_stackalloc and .seh_endprologue on windows
  14747. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp7) and GetNextInstruction(hp1, hp1))) and
  14748. ((hp1.typ=ait_instruction) or (SetAndTest(hp1, hp8) and GetNextInstruction(hp1, hp1))) and }
  14749. SkipSimpleInstructions(hp1) and
  14750. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14751. GetNextInstruction(hp1, hp2) and
  14752. (MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) or
  14753. { skip nop instruction on win64 }
  14754. (MatchInstruction(hp2,A_NOP,[S_NO]) and
  14755. SetAndTest(hp2,hp6) and
  14756. GetNextInstruction(hp2,hp2) and
  14757. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]))
  14758. ) and
  14759. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  14760. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  14761. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  14762. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  14763. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  14764. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  14765. { Segment register will be NR_NO }
  14766. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  14767. GetNextInstruction(hp2, hp3) and
  14768. { trick to skip label }
  14769. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14770. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14771. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14772. SetAndTest(hp3,hp5) and
  14773. GetNextInstruction(hp3,hp3) and
  14774. MatchInstruction(hp3,A_RET,[S_NO])
  14775. )
  14776. ) and
  14777. (taicpu(hp3).ops=0) then
  14778. begin
  14779. taicpu(hp1).opcode := A_JMP;
  14780. taicpu(hp1).is_jmp := true;
  14781. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  14782. { search for the stackalloc directive and remove it }
  14783. hp7:=tai(p.next);
  14784. while assigned(hp7) and (tai(hp7).typ<>ait_instruction) do
  14785. begin
  14786. if (hp7.typ=ait_seh_directive) and (tai_seh_directive(hp7).kind=ash_stackalloc) then
  14787. begin
  14788. { sanity check }
  14789. if taicpu(p).oper[0]^.ref^.offset<>-tai_seh_directive(hp7).data.offset then
  14790. Internalerror(2024012201);
  14791. hp8:=tai(hp7.next);
  14792. RemoveInstruction(tai(hp7));
  14793. hp7:=hp8;
  14794. break;
  14795. end
  14796. else
  14797. hp7:=tai(hp7.next);
  14798. end;
  14799. RemoveCurrentP(p, hp4);
  14800. RemoveInstruction(hp2);
  14801. RemoveInstruction(hp3);
  14802. { if there is a vzeroupper instruction then move it before the jmp }
  14803. if Assigned(hp5) then
  14804. begin
  14805. AsmL.Remove(hp5);
  14806. ASmL.InsertBefore(hp5,hp1)
  14807. end;
  14808. { remove nop on win64 }
  14809. if Assigned(hp6) then
  14810. RemoveInstruction(hp6);
  14811. Result:=true;
  14812. end;
  14813. end;
  14814. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  14815. {$ifdef x86_64}
  14816. var
  14817. hp1, hp2, hp3, hp4, hp5: tai;
  14818. {$endif x86_64}
  14819. begin
  14820. Result:=false;
  14821. {$ifdef x86_64}
  14822. hp5:=nil;
  14823. { replace
  14824. push %rax
  14825. call procname
  14826. pop %rcx
  14827. ret
  14828. by
  14829. jmp procname
  14830. but do it only on level 4 because it destroys stack back traces
  14831. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  14832. for all supported calling conventions
  14833. }
  14834. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14835. MatchOpType(taicpu(p),top_reg) and
  14836. (taicpu(p).oper[0]^.reg=NR_RAX) and
  14837. GetNextInstruction(p, hp1) and
  14838. { Take a copy of hp1 }
  14839. SetAndTest(hp1, hp4) and
  14840. { trick to skip label }
  14841. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  14842. SkipSimpleInstructions(hp1) and
  14843. MatchInstruction(hp1,A_CALL,[S_NO]) and
  14844. GetNextInstruction(hp1, hp2) and
  14845. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  14846. MatchOpType(taicpu(hp2),top_reg) and
  14847. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  14848. GetNextInstruction(hp2, hp3) and
  14849. { trick to skip label }
  14850. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  14851. (MatchInstruction(hp3,A_RET,[S_NO]) or
  14852. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  14853. SetAndTest(hp3,hp5) and
  14854. GetNextInstruction(hp3,hp3) and
  14855. MatchInstruction(hp3,A_RET,[S_NO])
  14856. )
  14857. ) and
  14858. (taicpu(hp3).ops=0) then
  14859. begin
  14860. taicpu(hp1).opcode := A_JMP;
  14861. taicpu(hp1).is_jmp := true;
  14862. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  14863. RemoveCurrentP(p, hp4);
  14864. RemoveInstruction(hp2);
  14865. RemoveInstruction(hp3);
  14866. if Assigned(hp5) then
  14867. begin
  14868. AsmL.Remove(hp5);
  14869. ASmL.InsertBefore(hp5,hp1)
  14870. end;
  14871. Result:=true;
  14872. end;
  14873. {$endif x86_64}
  14874. end;
  14875. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  14876. var
  14877. Value, RegName: string;
  14878. hp1: tai;
  14879. begin
  14880. Result:=false;
  14881. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  14882. begin
  14883. case taicpu(p).oper[0]^.val of
  14884. 0:
  14885. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  14886. if not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14887. (
  14888. { See if we can still convert the instruction }
  14889. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14890. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14891. ) then
  14892. begin
  14893. { change "mov $0,%reg" into "xor %reg,%reg" }
  14894. taicpu(p).opcode := A_XOR;
  14895. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  14896. Result := True;
  14897. {$ifdef x86_64}
  14898. end
  14899. else if (taicpu(p).opsize = S_Q) then
  14900. begin
  14901. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14902. { The actual optimization }
  14903. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14904. taicpu(p).changeopsize(S_L);
  14905. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14906. Result := True;
  14907. end;
  14908. $1..$FFFFFFFF:
  14909. begin
  14910. { Code size reduction by J. Gareth "Kit" Moreton }
  14911. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  14912. case taicpu(p).opsize of
  14913. S_Q:
  14914. begin
  14915. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  14916. Value := debug_tostr(taicpu(p).oper[0]^.val);
  14917. { The actual optimization }
  14918. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14919. taicpu(p).changeopsize(S_L);
  14920. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  14921. Result := True;
  14922. end;
  14923. else
  14924. { Do nothing };
  14925. end;
  14926. {$endif x86_64}
  14927. end;
  14928. -1:
  14929. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  14930. if (cs_opt_size in current_settings.optimizerswitches) and
  14931. (taicpu(p).opsize <> S_B) and
  14932. (
  14933. not RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs) or
  14934. (
  14935. { See if we can still convert the instruction }
  14936. GetNextInstructionUsingReg(p, hp1, NR_DEFAULTFLAGS) and
  14937. RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1)
  14938. )
  14939. ) then
  14940. begin
  14941. { change "mov $-1,%reg" into "or $-1,%reg" }
  14942. { NOTES:
  14943. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  14944. - This operation creates a false dependency on the register, so only do it when optimising for size
  14945. - 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
  14946. }
  14947. taicpu(p).opcode := A_OR;
  14948. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  14949. Result := True;
  14950. end;
  14951. else
  14952. { Do nothing };
  14953. end;
  14954. end;
  14955. end;
  14956. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  14957. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  14958. begin
  14959. Result := False;
  14960. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  14961. Exit;
  14962. { For sizes less than S_L, the byte size is equal or larger with BTx,
  14963. so don't bother optimising }
  14964. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  14965. Exit;
  14966. if (taicpu(p).oper[0]^.typ <> top_const) or
  14967. { If the value can fit into an 8-bit signed integer, a smaller
  14968. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  14969. falls within this range }
  14970. (
  14971. (taicpu(p).oper[0]^.val > -128) and
  14972. (taicpu(p).oper[0]^.val <= 127)
  14973. ) then
  14974. Exit;
  14975. { If we're optimising for size, this is acceptable }
  14976. if (cs_opt_size in current_settings.optimizerswitches) then
  14977. Exit(True);
  14978. if (taicpu(p).oper[1]^.typ = top_reg) and
  14979. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14980. Exit(True);
  14981. if (taicpu(p).oper[1]^.typ <> top_reg) and
  14982. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  14983. Exit(True);
  14984. end;
  14985. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  14986. var
  14987. hp1: tai;
  14988. Value: TCGInt;
  14989. begin
  14990. Result := False;
  14991. if MatchOpType(taicpu(p), top_const, top_reg) then
  14992. begin
  14993. { Detect:
  14994. andw x, %ax (0 <= x < $8000)
  14995. ...
  14996. movzwl %ax,%eax
  14997. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  14998. }
  14999. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  15000. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  15001. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  15002. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  15003. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  15004. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  15005. begin
  15006. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  15007. taicpu(hp1).opcode := A_CWDE;
  15008. taicpu(hp1).clearop(0);
  15009. taicpu(hp1).clearop(1);
  15010. taicpu(hp1).ops := 0;
  15011. { A change was made, but not with p, so don't set Result, but
  15012. notify the compiler that a change was made }
  15013. Include(OptsToCheck, aoc_ForceNewIteration);
  15014. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  15015. end;
  15016. end;
  15017. { If "not x" is a power of 2 (popcnt = 1), change:
  15018. and $x, %reg/ref
  15019. To:
  15020. btr lb(x), %reg/ref
  15021. }
  15022. if IsBTXAcceptable(p) and
  15023. (
  15024. { Make sure a TEST doesn't follow that plays with the register }
  15025. not GetNextInstruction(p, hp1) or
  15026. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  15027. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  15028. ) then
  15029. begin
  15030. {$push}{$R-}{$Q-}
  15031. { Value is a sign-extended 32-bit integer - just correct it
  15032. if it's represented as an unsigned value. Also, IsBTXAcceptable
  15033. checks to see if this operand is an immediate. }
  15034. Value := not taicpu(p).oper[0]^.val;
  15035. {$pop}
  15036. {$ifdef x86_64}
  15037. if taicpu(p).opsize = S_L then
  15038. {$endif x86_64}
  15039. Value := Value and $FFFFFFFF;
  15040. if (PopCnt(QWord(Value)) = 1) then
  15041. begin
  15042. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  15043. taicpu(p).opcode := A_BTR;
  15044. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  15045. Result := True;
  15046. Exit;
  15047. end;
  15048. end;
  15049. end;
  15050. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  15051. begin
  15052. Result := False;
  15053. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  15054. Exit;
  15055. { Convert:
  15056. movswl %ax,%eax -> cwtl
  15057. movslq %eax,%rax -> cdqe
  15058. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  15059. refer to the same opcode and depends only on the assembler's
  15060. current operand-size attribute. [Kit]
  15061. }
  15062. with taicpu(p) do
  15063. case opsize of
  15064. S_WL:
  15065. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  15066. begin
  15067. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  15068. opcode := A_CWDE;
  15069. clearop(0);
  15070. clearop(1);
  15071. ops := 0;
  15072. Result := True;
  15073. end;
  15074. {$ifdef x86_64}
  15075. S_LQ:
  15076. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  15077. begin
  15078. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  15079. opcode := A_CDQE;
  15080. clearop(0);
  15081. clearop(1);
  15082. ops := 0;
  15083. Result := True;
  15084. end;
  15085. {$endif x86_64}
  15086. else
  15087. ;
  15088. end;
  15089. end;
  15090. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  15091. var
  15092. hp1: tai;
  15093. begin
  15094. Result := False;
  15095. { All these optimisations work on "shr const,%reg" }
  15096. if not MatchOpType(taicpu(p), top_const, top_reg) then
  15097. Exit;
  15098. if HandleSHRMerge(p, True) then
  15099. begin
  15100. Result := True;
  15101. Exit;
  15102. end;
  15103. { Detect the following (looking backwards):
  15104. shr %cl,%reg
  15105. shr x, %reg
  15106. Swap the two SHR instructions to minimise a pipeline stall.
  15107. }
  15108. if GetLastInstruction(p, hp1) and
  15109. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  15110. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  15111. { First operand will be %cl }
  15112. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  15113. { Just to be sure }
  15114. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  15115. begin
  15116. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  15117. { Moving the entries this way ensures the register tracking remains correct }
  15118. Asml.Remove(p);
  15119. Asml.InsertBefore(p, hp1);
  15120. p := hp1;
  15121. { Don't set Result to True because the current instruction is now
  15122. "shr %cl,%reg" and there's nothing more we can do with it }
  15123. end;
  15124. end;
  15125. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  15126. var
  15127. hp1, hp2: tai;
  15128. Opposite, SecondOpposite: TAsmOp;
  15129. NewCond: TAsmCond;
  15130. begin
  15131. Result := False;
  15132. { Change:
  15133. add/sub 128,(dest)
  15134. To:
  15135. sub/add -128,(dest)
  15136. This generaally takes fewer bytes to encode because -128 can be stored
  15137. in a signed byte, whereas +128 cannot.
  15138. }
  15139. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  15140. begin
  15141. if taicpu(p).opcode = A_ADD then
  15142. Opposite := A_SUB
  15143. else
  15144. Opposite := A_ADD;
  15145. { Be careful if the flags are in use, because the CF flag inverts
  15146. when changing from ADD to SUB and vice versa }
  15147. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  15148. GetNextInstruction(p, hp1) then
  15149. begin
  15150. TransferUsedRegs(TmpUsedRegs);
  15151. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  15152. hp2 := hp1;
  15153. { Scan ahead to check if everything's safe }
  15154. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  15155. begin
  15156. if (hp1.typ <> ait_instruction) then
  15157. { Probably unsafe since the flags are still in use }
  15158. Exit;
  15159. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  15160. { Stop searching at an unconditional jump }
  15161. Break;
  15162. if not
  15163. (
  15164. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  15165. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  15166. ) and
  15167. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  15168. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  15169. Exit;
  15170. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15171. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  15172. { Move to the next instruction }
  15173. GetNextInstruction(hp1, hp1);
  15174. end;
  15175. while Assigned(hp2) and (hp2 <> hp1) do
  15176. begin
  15177. NewCond := C_None;
  15178. case taicpu(hp2).condition of
  15179. C_A, C_NBE:
  15180. NewCond := C_BE;
  15181. C_B, C_C, C_NAE:
  15182. NewCond := C_AE;
  15183. C_AE, C_NB, C_NC:
  15184. NewCond := C_B;
  15185. C_BE, C_NA:
  15186. NewCond := C_A;
  15187. else
  15188. { No change needed };
  15189. end;
  15190. if NewCond <> C_None then
  15191. begin
  15192. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  15193. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  15194. taicpu(hp2).condition := NewCond;
  15195. end
  15196. else
  15197. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  15198. begin
  15199. { Because of the flipping of the carry bit, to ensure
  15200. the operation remains equivalent, ADC becomes SBB
  15201. and vice versa, and the constant is not-inverted.
  15202. If multiple ADCs or SBBs appear in a row, each one
  15203. changed causes the carry bit to invert, so they all
  15204. need to be flipped }
  15205. if taicpu(hp2).opcode = A_ADC then
  15206. SecondOpposite := A_SBB
  15207. else
  15208. SecondOpposite := A_ADC;
  15209. if taicpu(hp2).oper[0]^.typ <> top_const then
  15210. { Should have broken out of this optimisation already }
  15211. InternalError(2021112901);
  15212. 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]^) + ' -> ' +
  15213. 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);
  15214. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  15215. taicpu(hp2).opcode := SecondOpposite;
  15216. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  15217. end;
  15218. { Move to the next instruction }
  15219. GetNextInstruction(hp2, hp2);
  15220. end;
  15221. if (hp2 <> hp1) then
  15222. InternalError(2021111501);
  15223. end;
  15224. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  15225. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  15226. taicpu(p).opcode := Opposite;
  15227. taicpu(p).oper[0]^.val := -128;
  15228. { No further optimisations can be made on this instruction, so move
  15229. onto the next one to save time }
  15230. p := tai(p.Next);
  15231. UpdateUsedRegs(p);
  15232. Result := True;
  15233. Exit;
  15234. end;
  15235. { Detect:
  15236. add/sub %reg2,(dest)
  15237. add/sub x, (dest)
  15238. (dest can be a register or a reference)
  15239. Swap the instructions to minimise a pipeline stall. This reverses the
  15240. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  15241. optimisations could be made.
  15242. }
  15243. if (taicpu(p).oper[0]^.typ = top_reg) and
  15244. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  15245. (
  15246. (
  15247. (taicpu(p).oper[1]^.typ = top_reg) and
  15248. { We can try searching further ahead if we're writing to a register }
  15249. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  15250. ) or
  15251. (
  15252. (taicpu(p).oper[1]^.typ = top_ref) and
  15253. GetNextInstruction(p, hp1)
  15254. )
  15255. ) and
  15256. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  15257. (taicpu(hp1).oper[0]^.typ = top_const) and
  15258. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  15259. begin
  15260. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  15261. TransferUsedRegs(TmpUsedRegs);
  15262. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  15263. hp2 := p;
  15264. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  15265. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  15266. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  15267. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15268. begin
  15269. asml.remove(hp1);
  15270. asml.InsertBefore(hp1, p);
  15271. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  15272. Result := True;
  15273. end;
  15274. end;
  15275. end;
  15276. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  15277. var
  15278. hp1: tai;
  15279. begin
  15280. Result:=false;
  15281. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  15282. while GetNextInstruction(p, hp1) and
  15283. TrySwapMovCmp(p, hp1) do
  15284. begin
  15285. if MatchInstruction(hp1, A_MOV, []) then
  15286. begin
  15287. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15288. begin
  15289. { A little hacky, but since CMP doesn't read the flags, only
  15290. modify them, it's safe if they get scrambled by MOV -> XOR }
  15291. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15292. Result := PostPeepholeOptMov(hp1);
  15293. {$ifdef x86_64}
  15294. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15295. { Used to shrink instruction size }
  15296. PostPeepholeOptXor(hp1);
  15297. {$endif x86_64}
  15298. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15299. end
  15300. else
  15301. begin
  15302. Result := PostPeepholeOptMov(hp1);
  15303. {$ifdef x86_64}
  15304. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15305. { Used to shrink instruction size }
  15306. PostPeepholeOptXor(hp1);
  15307. {$endif x86_64}
  15308. end;
  15309. end;
  15310. { Enabling this flag is actually a null operation, but it marks
  15311. the code as 'modified' during this pass }
  15312. Include(OptsToCheck, aoc_ForceNewIteration);
  15313. end;
  15314. { change "cmp $0, %reg" to "test %reg, %reg" }
  15315. if MatchOpType(taicpu(p),top_const,top_reg) and
  15316. (taicpu(p).oper[0]^.val = 0) then
  15317. begin
  15318. taicpu(p).opcode := A_TEST;
  15319. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  15320. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  15321. Result:=true;
  15322. end;
  15323. end;
  15324. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  15325. var
  15326. IsTestConstX, IsValid : Boolean;
  15327. hp1,hp2 : tai;
  15328. begin
  15329. Result:=false;
  15330. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  15331. if (taicpu(p).opcode = A_TEST) then
  15332. while GetNextInstruction(p, hp1) and
  15333. TrySwapMovCmp(p, hp1) do
  15334. begin
  15335. if MatchInstruction(hp1, A_MOV, []) then
  15336. begin
  15337. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  15338. begin
  15339. { A little hacky, but since TEST doesn't read the flags, only
  15340. modify them, it's safe if they get scrambled by MOV -> XOR }
  15341. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15342. Result := PostPeepholeOptMov(hp1);
  15343. {$ifdef x86_64}
  15344. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15345. { Used to shrink instruction size }
  15346. PostPeepholeOptXor(hp1);
  15347. {$endif x86_64}
  15348. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  15349. end
  15350. else
  15351. begin
  15352. Result := PostPeepholeOptMov(hp1);
  15353. {$ifdef x86_64}
  15354. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  15355. { Used to shrink instruction size }
  15356. PostPeepholeOptXor(hp1);
  15357. {$endif x86_64}
  15358. end;
  15359. end;
  15360. { Enabling this flag is actually a null operation, but it marks
  15361. the code as 'modified' during this pass }
  15362. Include(OptsToCheck, aoc_ForceNewIteration);
  15363. end;
  15364. { If x is a power of 2 (popcnt = 1), change:
  15365. or $x, %reg/ref
  15366. To:
  15367. bts lb(x), %reg/ref
  15368. }
  15369. if (taicpu(p).opcode = A_OR) and
  15370. IsBTXAcceptable(p) and
  15371. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15372. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15373. (
  15374. { Don't optimise if a test instruction follows }
  15375. not GetNextInstruction(p, hp1) or
  15376. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15377. ) then
  15378. begin
  15379. 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);
  15380. taicpu(p).opcode := A_BTS;
  15381. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15382. Result := True;
  15383. Exit;
  15384. end;
  15385. { If x is a power of 2 (popcnt = 1), change:
  15386. test $x, %reg/ref
  15387. je / sete / cmove (or jne / setne)
  15388. To:
  15389. bt lb(x), %reg/ref
  15390. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  15391. }
  15392. if (taicpu(p).opcode = A_TEST) and
  15393. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  15394. (taicpu(p).oper[0]^.typ = top_const) and
  15395. (
  15396. (cs_opt_size in current_settings.optimizerswitches) or
  15397. (
  15398. (taicpu(p).oper[1]^.typ = top_reg) and
  15399. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15400. ) or
  15401. (
  15402. (taicpu(p).oper[1]^.typ <> top_reg) and
  15403. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  15404. )
  15405. ) and
  15406. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15407. { For sizes less than S_L, the byte size is equal or larger with BT,
  15408. so don't bother optimising }
  15409. (taicpu(p).opsize >= S_L) then
  15410. begin
  15411. IsValid := True;
  15412. { Check the next set of instructions, watching the FLAGS register
  15413. and the conditions used }
  15414. TransferUsedRegs(TmpUsedRegs);
  15415. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  15416. hp1 := p;
  15417. hp2 := nil;
  15418. while GetNextInstruction(hp1, hp1) do
  15419. begin
  15420. if not Assigned(hp2) then
  15421. { The first instruction after TEST }
  15422. hp2 := hp1;
  15423. if (hp1.typ <> ait_instruction) then
  15424. begin
  15425. { If the flags are no longer in use, everything is fine }
  15426. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  15427. IsValid := False;
  15428. Break;
  15429. end;
  15430. case taicpu(hp1).condition of
  15431. C_None:
  15432. begin
  15433. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  15434. not RegLoadedWithNewValue(NR_DEFAULTFLAGS, hp1) then
  15435. { Something is not quite normal, so play safe and don't change }
  15436. IsValid := False;
  15437. Break;
  15438. end;
  15439. C_E, C_Z, C_NE, C_NZ:
  15440. { This is fine };
  15441. else
  15442. begin
  15443. { Unsupported condition }
  15444. IsValid := False;
  15445. Break;
  15446. end;
  15447. end;
  15448. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  15449. end;
  15450. if IsValid then
  15451. begin
  15452. while hp2 <> hp1 do
  15453. begin
  15454. case taicpu(hp2).condition of
  15455. C_Z, C_E:
  15456. taicpu(hp2).condition := C_NC;
  15457. C_NZ, C_NE:
  15458. taicpu(hp2).condition := C_C;
  15459. else
  15460. { Should not get this by this point }
  15461. InternalError(2022110701);
  15462. end;
  15463. GetNextInstruction(hp2, hp2);
  15464. end;
  15465. 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);
  15466. taicpu(p).opcode := A_BT;
  15467. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15468. Result := True;
  15469. Exit;
  15470. end;
  15471. end;
  15472. { removes the line marked with (x) from the sequence
  15473. and/or/xor/add/sub/... $x, %y
  15474. test/or %y, %y | test $-1, %y (x)
  15475. j(n)z _Label
  15476. as the first instruction already adjusts the ZF
  15477. %y operand may also be a reference }
  15478. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  15479. MatchOperand(taicpu(p).oper[0]^,-1);
  15480. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  15481. GetLastInstruction(p, hp1) and
  15482. (tai(hp1).typ = ait_instruction) and
  15483. GetNextInstruction(p,hp2) and
  15484. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  15485. case taicpu(hp1).opcode Of
  15486. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  15487. { These two instructions set the zero flag if the result is zero }
  15488. A_POPCNT, A_LZCNT:
  15489. begin
  15490. if (
  15491. { With POPCNT, an input of zero will set the zero flag
  15492. because the population count of zero is zero }
  15493. (taicpu(hp1).opcode = A_POPCNT) and
  15494. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  15495. (
  15496. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  15497. { Faster than going through the second half of the 'or'
  15498. condition below }
  15499. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  15500. )
  15501. ) or (
  15502. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  15503. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15504. { and in case of carry for A(E)/B(E)/C/NC }
  15505. (
  15506. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  15507. (
  15508. (taicpu(hp1).opcode <> A_ADD) and
  15509. (taicpu(hp1).opcode <> A_SUB) and
  15510. (taicpu(hp1).opcode <> A_LZCNT)
  15511. )
  15512. )
  15513. ) then
  15514. begin
  15515. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  15516. RemoveCurrentP(p, hp2);
  15517. Result:=true;
  15518. Exit;
  15519. end;
  15520. end;
  15521. A_SHL, A_SAL, A_SHR, A_SAR:
  15522. begin
  15523. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  15524. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  15525. { therefore, it's only safe to do this optimization for }
  15526. { shifts by a (nonzero) constant }
  15527. (taicpu(hp1).oper[0]^.typ = top_const) and
  15528. (taicpu(hp1).oper[0]^.val <> 0) and
  15529. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15530. { and in case of carry for A(E)/B(E)/C/NC }
  15531. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15532. begin
  15533. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  15534. RemoveCurrentP(p, hp2);
  15535. Result:=true;
  15536. Exit;
  15537. end;
  15538. end;
  15539. A_DEC, A_INC, A_NEG:
  15540. begin
  15541. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  15542. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  15543. { and in case of carry for A(E)/B(E)/C/NC }
  15544. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15545. begin
  15546. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  15547. RemoveCurrentP(p, hp2);
  15548. Result:=true;
  15549. Exit;
  15550. end;
  15551. end;
  15552. A_ANDN, A_BZHI:
  15553. begin
  15554. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15555. { Only the zero and sign flags are consistent with what the result is }
  15556. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  15557. begin
  15558. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  15559. RemoveCurrentP(p, hp2);
  15560. Result:=true;
  15561. Exit;
  15562. end;
  15563. end;
  15564. A_BEXTR:
  15565. begin
  15566. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  15567. { Only the zero flag is set }
  15568. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  15569. begin
  15570. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  15571. RemoveCurrentP(p, hp2);
  15572. Result:=true;
  15573. Exit;
  15574. end;
  15575. end;
  15576. else
  15577. ;
  15578. end; { case }
  15579. { change "test $-1,%reg" into "test %reg,%reg" }
  15580. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  15581. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  15582. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  15583. if MatchInstruction(p, A_OR, []) and
  15584. { Can only match if they're both registers }
  15585. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  15586. begin
  15587. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  15588. taicpu(p).opcode := A_TEST;
  15589. { No need to set Result to True, as we've done all the optimisations we can }
  15590. end;
  15591. end;
  15592. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  15593. var
  15594. hp1,hp3 : tai;
  15595. {$ifndef x86_64}
  15596. hp2 : taicpu;
  15597. {$endif x86_64}
  15598. begin
  15599. Result:=false;
  15600. hp3:=nil;
  15601. {$ifndef x86_64}
  15602. { don't do this on modern CPUs, this really hurts them due to
  15603. broken call/ret pairing }
  15604. if (current_settings.optimizecputype < cpu_Pentium2) and
  15605. not(cs_create_pic in current_settings.moduleswitches) and
  15606. GetNextInstruction(p, hp1) and
  15607. MatchInstruction(hp1,A_JMP,[S_NO]) and
  15608. MatchOpType(taicpu(hp1),top_ref) and
  15609. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  15610. begin
  15611. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  15612. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  15613. InsertLLItem(p.previous, p, hp2);
  15614. taicpu(p).opcode := A_JMP;
  15615. taicpu(p).is_jmp := true;
  15616. RemoveInstruction(hp1);
  15617. Result:=true;
  15618. end
  15619. else
  15620. {$endif x86_64}
  15621. { replace
  15622. call procname
  15623. ret
  15624. by
  15625. jmp procname
  15626. but do it only on level 4 because it destroys stack back traces
  15627. else if the subroutine is marked as no return, remove the ret
  15628. }
  15629. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  15630. (po_noreturn in current_procinfo.procdef.procoptions)) and
  15631. GetNextInstruction(p, hp1) and
  15632. (MatchInstruction(hp1,A_RET,[S_NO]) or
  15633. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  15634. SetAndTest(hp1,hp3) and
  15635. GetNextInstruction(hp1,hp1) and
  15636. MatchInstruction(hp1,A_RET,[S_NO])
  15637. )
  15638. ) and
  15639. (taicpu(hp1).ops=0) then
  15640. begin
  15641. if (cs_opt_level4 in current_settings.optimizerswitches) and
  15642. { we might destroy stack alignment here if we do not do a call }
  15643. (target_info.stackalign<=sizeof(SizeUInt)) then
  15644. begin
  15645. taicpu(p).opcode := A_JMP;
  15646. taicpu(p).is_jmp := true;
  15647. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  15648. end
  15649. else
  15650. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  15651. RemoveInstruction(hp1);
  15652. if Assigned(hp3) then
  15653. begin
  15654. AsmL.Remove(hp3);
  15655. AsmL.InsertBefore(hp3,p)
  15656. end;
  15657. Result:=true;
  15658. end;
  15659. end;
  15660. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  15661. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  15662. begin
  15663. case OpSize of
  15664. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  15665. Result := (Val <= $FF) and (Val >= -128);
  15666. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  15667. Result := (Val <= $FFFF) and (Val >= -32768);
  15668. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  15669. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  15670. else
  15671. Result := True;
  15672. end;
  15673. end;
  15674. var
  15675. hp1, hp2 : tai;
  15676. SizeChange: Boolean;
  15677. PreMessage: string;
  15678. begin
  15679. Result := False;
  15680. if (taicpu(p).oper[0]^.typ = top_reg) and
  15681. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  15682. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  15683. begin
  15684. { Change (using movzbl %al,%eax as an example):
  15685. movzbl %al, %eax movzbl %al, %eax
  15686. cmpl x, %eax testl %eax,%eax
  15687. To:
  15688. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  15689. movzbl %al, %eax movzbl %al, %eax
  15690. Smaller instruction and minimises pipeline stall as the CPU
  15691. doesn't have to wait for the register to get zero-extended. [Kit]
  15692. Also allow if the smaller of the two registers is being checked,
  15693. as this still removes the false dependency.
  15694. }
  15695. if
  15696. (
  15697. (
  15698. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  15699. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  15700. ) or (
  15701. { If MatchOperand returns True, they must both be registers }
  15702. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  15703. )
  15704. ) and
  15705. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  15706. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  15707. begin
  15708. 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);
  15709. asml.Remove(hp1);
  15710. asml.InsertBefore(hp1, p);
  15711. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  15712. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  15713. begin
  15714. taicpu(hp1).opcode := A_TEST;
  15715. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  15716. end;
  15717. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  15718. case taicpu(p).opsize of
  15719. S_BW, S_BL:
  15720. begin
  15721. SizeChange := taicpu(hp1).opsize <> S_B;
  15722. taicpu(hp1).changeopsize(S_B);
  15723. end;
  15724. S_WL:
  15725. begin
  15726. SizeChange := taicpu(hp1).opsize <> S_W;
  15727. taicpu(hp1).changeopsize(S_W);
  15728. end
  15729. else
  15730. InternalError(2020112701);
  15731. end;
  15732. UpdateUsedRegs(tai(p.Next));
  15733. { Check if the register is used aferwards - if not, we can
  15734. remove the movzx instruction completely }
  15735. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  15736. begin
  15737. { Hp1 is a better position than p for debugging purposes }
  15738. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  15739. RemoveCurrentp(p, hp1);
  15740. Result := True;
  15741. end;
  15742. if SizeChange then
  15743. DebugMsg(SPeepholeOptimization + PreMessage +
  15744. 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)
  15745. else
  15746. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  15747. Exit;
  15748. end;
  15749. { Change (using movzwl %ax,%eax as an example):
  15750. movzwl %ax, %eax
  15751. movb %al, (dest) (Register is smaller than read register in movz)
  15752. To:
  15753. movb %al, (dest) (Move one back to avoid a false dependency)
  15754. movzwl %ax, %eax
  15755. }
  15756. if (taicpu(hp1).opcode = A_MOV) and
  15757. (taicpu(hp1).oper[0]^.typ = top_reg) and
  15758. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  15759. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  15760. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  15761. begin
  15762. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  15763. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  15764. asml.Remove(hp1);
  15765. asml.InsertBefore(hp1, p);
  15766. if taicpu(hp1).oper[1]^.typ = top_reg then
  15767. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  15768. { Check if the register is used aferwards - if not, we can
  15769. remove the movzx instruction completely }
  15770. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  15771. begin
  15772. { Hp1 is a better position than p for debugging purposes }
  15773. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  15774. RemoveCurrentp(p, hp1);
  15775. Result := True;
  15776. end;
  15777. Exit;
  15778. end;
  15779. end;
  15780. end;
  15781. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  15782. var
  15783. hp1: tai;
  15784. {$ifdef x86_64}
  15785. PreMessage, RegName: string;
  15786. {$endif x86_64}
  15787. begin
  15788. Result := False;
  15789. { If x is a power of 2 (popcnt = 1), change:
  15790. xor $x, %reg/ref
  15791. To:
  15792. btc lb(x), %reg/ref
  15793. }
  15794. if IsBTXAcceptable(p) and
  15795. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  15796. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  15797. (
  15798. { Don't optimise if a test instruction follows }
  15799. not GetNextInstruction(p, hp1) or
  15800. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  15801. ) then
  15802. begin
  15803. 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);
  15804. taicpu(p).opcode := A_BTC;
  15805. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  15806. Result := True;
  15807. Exit;
  15808. end;
  15809. {$ifdef x86_64}
  15810. { Code size reduction by J. Gareth "Kit" Moreton }
  15811. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  15812. as this removes the REX prefix }
  15813. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  15814. Exit;
  15815. if taicpu(p).oper[0]^.typ <> top_reg then
  15816. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  15817. InternalError(2018011500);
  15818. case taicpu(p).opsize of
  15819. S_Q:
  15820. begin
  15821. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  15822. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  15823. { The actual optimization }
  15824. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  15825. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  15826. taicpu(p).changeopsize(S_L);
  15827. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  15828. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  15829. end;
  15830. else
  15831. ;
  15832. end;
  15833. {$endif x86_64}
  15834. end;
  15835. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  15836. var
  15837. XReg: TRegister;
  15838. begin
  15839. Result := False;
  15840. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  15841. Smaller encoding and slightly faster on some platforms (also works for
  15842. ZMM-sized registers) }
  15843. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  15844. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  15845. begin
  15846. XReg := taicpu(p).oper[0]^.reg;
  15847. if (taicpu(p).oper[1]^.reg = XReg) then
  15848. begin
  15849. taicpu(p).changeopsize(S_XMM);
  15850. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  15851. if (cs_opt_size in current_settings.optimizerswitches) then
  15852. begin
  15853. { Change input registers to %xmm0 to reduce size. Note that
  15854. there's a risk of a false dependency doing this, so only
  15855. optimise for size here }
  15856. XReg := NR_XMM0;
  15857. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  15858. end
  15859. else
  15860. begin
  15861. setsubreg(XReg, R_SUBMMX);
  15862. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  15863. end;
  15864. taicpu(p).oper[0]^.reg := XReg;
  15865. taicpu(p).oper[1]^.reg := XReg;
  15866. Result := True;
  15867. end;
  15868. end;
  15869. end;
  15870. function TX86AsmOptimizer.PostPeepholeOptRET(var p: tai): Boolean;
  15871. var
  15872. hp1, p_new: tai;
  15873. begin
  15874. Result := False;
  15875. { Check for:
  15876. ret
  15877. .Lbl:
  15878. ret
  15879. Remove first 'ret'
  15880. }
  15881. if GetNextInstruction(p, hp1) and
  15882. { Remember where the label is }
  15883. SetAndTest(hp1, p_new) and
  15884. (hp1.typ in [ait_align, ait_label]) and
  15885. SkipLabels(hp1, hp1) and
  15886. MatchInstruction(hp1, A_RET, []) and
  15887. { To be safe, make sure the RET instructions are identical }
  15888. (taicpu(p).ops = taicpu(hp1).ops) and
  15889. (
  15890. (taicpu(p).ops = 0) or
  15891. (
  15892. (taicpu(p).ops = 1) and
  15893. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^)
  15894. )
  15895. ) then
  15896. begin
  15897. DebugMsg(SPeepholeOptimization + 'Removed superfluous RET', p);
  15898. UpdateUsedRegs(tai(p.Next));
  15899. RemoveCurrentP(p, p_new);
  15900. Result := True;
  15901. Exit;
  15902. end;
  15903. end;
  15904. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  15905. var
  15906. OperIdx: Integer;
  15907. begin
  15908. for OperIdx := 0 to p.ops - 1 do
  15909. if p.oper[OperIdx]^.typ = top_ref then
  15910. optimize_ref(p.oper[OperIdx]^.ref^, False);
  15911. end;
  15912. end.